commit 4c89a8ee8c51d9a8864a435c7540e0611af683cb Author: NetMan <13informatyka14@gmail.com> Date: Thu Jan 11 09:52:05 2024 +0100 Initial commit diff --git a/08_calculator/README.md b/08_calculator/README.md new file mode 100644 index 0000000..e50b776 --- /dev/null +++ b/08_calculator/README.md @@ -0,0 +1,8 @@ +# Exercise 08 - Calculator + +The goal for this exercise is to create a calculator that does the following: + +add, subtract, get the sum, multiply, get the power, and find the factorial + +In order to do this please fill out each function with your solution. Make sure to return the value so you can test it in Jest! To see the expected value +take a look at the spec file that houses the Jest test cases. \ No newline at end of file diff --git a/08_calculator/calculator.js b/08_calculator/calculator.js new file mode 100644 index 0000000..c22e8d2 --- /dev/null +++ b/08_calculator/calculator.js @@ -0,0 +1,33 @@ +const add = function() { + +}; + +const subtract = function() { + +}; + +const sum = function() { + +}; + +const multiply = function() { + +}; + +const power = function() { + +}; + +const factorial = function() { + +}; + +// Do not edit below this line +module.exports = { + add, + subtract, + sum, + multiply, + power, + factorial +}; diff --git a/08_calculator/calculator.spec.js b/08_calculator/calculator.spec.js new file mode 100644 index 0000000..48b08c9 --- /dev/null +++ b/08_calculator/calculator.spec.js @@ -0,0 +1,77 @@ +const calculator = require('./calculator'); + +describe('add', () => { + test('adds 0 and 0', () => { + expect(calculator.add(0, 0)).toBe(0); + }); + + test.skip('adds 2 and 2', () => { + expect(calculator.add(2, 2)).toBe(4); + }); + + test.skip('adds positive numbers', () => { + expect(calculator.add(2, 6)).toBe(8); + }); +}); + +describe('subtract', () => { + test.skip('subtracts numbers', () => { + expect(calculator.subtract(10, 4)).toBe(6); + }); +}); + +describe('sum', () => { + test.skip('computes the sum of an empty array', () => { + expect(calculator.sum([])).toBe(0); + }); + + test.skip('computes the sum of an array of one number', () => { + expect(calculator.sum([7])).toBe(7); + }); + + test.skip('computes the sum of an array of two numbers', () => { + expect(calculator.sum([7, 11])).toBe(18); + }); + + test.skip('computes the sum of an array of many numbers', () => { + expect(calculator.sum([1, 3, 5, 7, 9])).toBe(25); + }); +}); + +describe('multiply', () => { + test.skip('multiplies two numbers', () => { + expect(calculator.multiply([2, 4])).toBe(8); + }); + + test.skip('multiplies several numbers', () => { + expect(calculator.multiply([2, 4, 6, 8, 10, 12, 14])).toBe(645120); + }); +}); + +describe('power', () => { + test.skip('raises one number to the power of another number', () => { + expect(calculator.power(4, 3)).toBe(64); // 4 to third power is 64 + }); +}); + +describe('factorial', () => { + test.skip('computes the factorial of 0', () => { + expect(calculator.factorial(0)).toBe(1); // 0! = 1 + }); + + test.skip('computes the factorial of 1', () => { + expect(calculator.factorial(1)).toBe(1); + }); + + test.skip('computes the factorial of 2', () => { + expect(calculator.factorial(2)).toBe(2); + }); + + test.skip('computes the factorial of 5', () => { + expect(calculator.factorial(5)).toBe(120); + }); + + test.skip('computes the factorial of 10', () => { + expect(calculator.factorial(10)).toBe(3628800); + }); +}); diff --git a/08_calculator/solution/calculator-solution.js b/08_calculator/solution/calculator-solution.js new file mode 100644 index 0000000..b195387 --- /dev/null +++ b/08_calculator/solution/calculator-solution.js @@ -0,0 +1,46 @@ +const add = function (a, b) { + return a + b; +}; + +const subtract = function (a, b) { + return a - b; +}; + +const sum = function (array) { + return array.reduce((total, current) => total + current, 0); +}; + +const multiply = function (array) { + return array.reduce((product, current) => product * current) +}; + +const power = function (a, b) { + return Math.pow(a, b); +}; + +const factorial = function (n) { + if (n === 0) return 1; + let product = 1; + for (let i = n; i > 0; i--) { + product *= i; + } + return product; +}; + +// This is another implementation of Factorial that uses recursion +// THANKS to @ThirtyThreeB! +const recursiveFactorial = function (n) { + if (n === 0) { + return 1; + } + return n * recursiveFactorial(n - 1); +}; + +module.exports = { + add, + subtract, + sum, + multiply, + power, + factorial, +}; diff --git a/08_calculator/solution/calculator-solution.spec.js b/08_calculator/solution/calculator-solution.spec.js new file mode 100644 index 0000000..453707c --- /dev/null +++ b/08_calculator/solution/calculator-solution.spec.js @@ -0,0 +1,77 @@ +const calculator = require('./calculator-solution'); + +describe('add', () => { + test('adds 0 and 0', () => { + expect(calculator.add(0, 0)).toBe(0); + }); + + test('adds 2 and 2', () => { + expect(calculator.add(2, 2)).toBe(4); + }); + + test('adds positive numbers', () => { + expect(calculator.add(2, 6)).toBe(8); + }); +}); + +describe('subtract', () => { + test('subtracts numbers', () => { + expect(calculator.subtract(10, 4)).toBe(6); + }); +}); + +describe('sum', () => { + test('computes the sum of an empty array', () => { + expect(calculator.sum([])).toBe(0); + }); + + test('computes the sum of an array of one number', () => { + expect(calculator.sum([7])).toBe(7); + }); + + test('computes the sum of an array of two numbers', () => { + expect(calculator.sum([7, 11])).toBe(18); + }); + + test('computes the sum of an array of many numbers', () => { + expect(calculator.sum([1, 3, 5, 7, 9])).toBe(25); + }); +}); + +describe('multiply', () => { + test('multiplies two numbers', () => { + expect(calculator.multiply([2, 4])).toBe(8); + }); + + test('multiplies several numbers', () => { + expect(calculator.multiply([2, 4, 6, 8, 10, 12, 14])).toBe(645120); + }); +}); + +describe('power', () => { + test('raises one number to the power of another number', () => { + expect(calculator.power(4, 3)).toBe(64); // 4 to third power is 64 + }); +}); + +describe('factorial', () => { + test('computes the factorial of 0', () => { + expect(calculator.factorial(0)).toBe(1); // 0! = 1 + }); + + test('computes the factorial of 1', () => { + expect(calculator.factorial(1)).toBe(1); + }); + + test('computes the factorial of 2', () => { + expect(calculator.factorial(2)).toBe(2); + }); + + test('computes the factorial of 5', () => { + expect(calculator.factorial(5)).toBe(120); + }); + + test('computes the factorial of 10', () => { + expect(calculator.factorial(10)).toBe(3628800); + }); +}); diff --git a/09_palindromes/README.md b/09_palindromes/README.md new file mode 100644 index 0000000..b924a45 --- /dev/null +++ b/09_palindromes/README.md @@ -0,0 +1,19 @@ +# Exercise 09 - Palindromes + +Write a function that determines whether or not a given string is a palindrome. + +A palindrome is a string that is spelled the same both forwards and backwards, usually without considering punctuation or word breaks: + +### some palindromes: + - A car, a man, a maraca. + - Rats live on no evil star. + - Lid off a daffodil. + - Animal loots foliated detail of stool lamina. + - A nut for a jar of tuna. + +```javascript +palindromes('racecar') // true +palindromes('tacos') // false +``` + + diff --git a/09_palindromes/palindromes.js b/09_palindromes/palindromes.js new file mode 100644 index 0000000..8d21018 --- /dev/null +++ b/09_palindromes/palindromes.js @@ -0,0 +1,6 @@ +const palindromes = function () { + +}; + +// Do not edit below this line +module.exports = palindromes; diff --git a/09_palindromes/palindromes.spec.js b/09_palindromes/palindromes.spec.js new file mode 100644 index 0000000..90d53e4 --- /dev/null +++ b/09_palindromes/palindromes.spec.js @@ -0,0 +1,28 @@ +const palindromes = require('./palindromes') + +describe('palindromes', () => { + test('works with single words', () => { + expect(palindromes('racecar')).toBe(true); + }); + test.skip('works with punctuation ', () => { + expect(palindromes('racecar!')).toBe(true); + }); + test.skip('works with upper-case letters ', () => { + expect(palindromes('Racecar!')).toBe(true); + }); + test.skip('works with multiple words', () => { + expect(palindromes('A car, a man, a maraca.')).toBe(true); + }); + test.skip('works with multiple words', () => { + expect(palindromes('Animal loots foliated detail of stool lamina.')).toBe(true); + }); + test.skip('doesn\'t just always return true', () => { + expect(palindromes('ZZZZ car, a man, a maracaz.')).toBe(false); + }); + test.skip('works with numbers in a string', () => { + expect(palindromes('rac3e3car')).toBe(true); + }); + test.skip('works with unevenly spaced numbers in a string', () => { + expect(palindromes('r3ace3car')).toBe(false); + }); +}); diff --git a/09_palindromes/solution/palindromes-solution.js b/09_palindromes/solution/palindromes-solution.js new file mode 100644 index 0000000..7950015 --- /dev/null +++ b/09_palindromes/solution/palindromes-solution.js @@ -0,0 +1,6 @@ +const palindromes = function (string) { + const processedString = string.toLowerCase().replace(/[^a-z0-9]/g, ""); + return processedString.split("").reverse().join("") == processedString; +}; + +module.exports = palindromes; diff --git a/09_palindromes/solution/palindromes-solution.spec.js b/09_palindromes/solution/palindromes-solution.spec.js new file mode 100644 index 0000000..6e31d91 --- /dev/null +++ b/09_palindromes/solution/palindromes-solution.spec.js @@ -0,0 +1,30 @@ +const palindromes = require('./palindromes-solution'); + +describe('palindromes', () => { + test('works with single words', () => { + expect(palindromes('racecar')).toBe(true); + }); + test('works with punctuation ', () => { + expect(palindromes('racecar!')).toBe(true); + }); + test('works with upper-case letters ', () => { + expect(palindromes('Racecar!')).toBe(true); + }); + test('works with multiple words', () => { + expect(palindromes('A car, a man, a maraca.')).toBe(true); + }); + test('works with multiple words', () => { + expect(palindromes('Animal loots foliated detail of stool lamina.')).toBe( + true + ); + }); + test("doesn't just always return true", () => { + expect(palindromes('ZZZZ car, a man, a maraca.')).toBe(false); + }); + test('works with numbers in a string', () => { + expect(palindromes('rac3e3car')).toBe(true); + }); + test('works with unevenly spaced numbers in a string', () => { + expect(palindromes('r3ace3car')).toBe(false); + }); +}); diff --git a/10_fibonacci/README.md b/10_fibonacci/README.md new file mode 100644 index 0000000..718b25a --- /dev/null +++ b/10_fibonacci/README.md @@ -0,0 +1,12 @@ +# Exercise 10 - Fibonacci + +Create a function that returns a specific member of the Fibonacci sequence: + +> A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. +> In this exercise, the Fibonacci sequence used is 1, 1, 2, 3, 5, 8, etc. +> To learn more about Fibonacci sequences, go to: https://en.wikipedia.org/wiki/Fibonacci_sequence + +```javascript +fibonacci(4); // returns the 4th member of the series: 3 (1, 1, 2, 3) +fibonacci(6); // returns 8 +``` diff --git a/10_fibonacci/fibonacci.js b/10_fibonacci/fibonacci.js new file mode 100644 index 0000000..bb2c8cc --- /dev/null +++ b/10_fibonacci/fibonacci.js @@ -0,0 +1,6 @@ +const fibonacci = function() { + +}; + +// Do not edit below this line +module.exports = fibonacci; diff --git a/10_fibonacci/fibonacci.spec.js b/10_fibonacci/fibonacci.spec.js new file mode 100644 index 0000000..de632d8 --- /dev/null +++ b/10_fibonacci/fibonacci.spec.js @@ -0,0 +1,37 @@ +const fibonacci = require('./fibonacci') + +describe('fibonacci', () => { + test('4th fibonacci number is 3', () => { + expect(fibonacci(4)).toBe(3); + }); + test.skip('6th fibonacci number is 8', () => { + expect(fibonacci(6)).toBe(8); + }); + test.skip('10th fibonacci number is 55', () => { + expect(fibonacci(10)).toBe(55); + }); + test.skip('15th fibonacci number is 610', () => { + expect(fibonacci(15)).toBe(610); + }); + test.skip('25th fibonacci number is 75025', () => { + expect(fibonacci(25)).toBe(75025); + }); + test.skip('0th fibonacci number is 0', () => { + expect(fibonacci(0)).toBe(0); + }); + test.skip('doesn\'t accept negatives', () => { + expect(fibonacci(-25)).toBe("OOPS"); + }); + test.skip('DOES accept strings', () => { + expect(fibonacci("0")).toBe(0); + }); + test.skip('DOES accept strings', () => { + expect(fibonacci("1")).toBe(1); + }); + test.skip('DOES accept strings', () => { + expect(fibonacci("2")).toBe(1); + }); + test.skip('DOES accept strings', () => { + expect(fibonacci("8")).toBe(21); + }); +}); diff --git a/10_fibonacci/solution/fibonacci-solution.js b/10_fibonacci/solution/fibonacci-solution.js new file mode 100644 index 0000000..1327ce9 --- /dev/null +++ b/10_fibonacci/solution/fibonacci-solution.js @@ -0,0 +1,34 @@ +const fibonacci = function(countArg) { + // checks argument's type and makes sure we use + // a number throughout rest of function. + let count + if (typeof countArg !== 'number') { + count = parseInt(countArg) + } else { + count = countArg + } + + if (count < 0) return "OOPS"; + if (count == 0) return 0; + + let firstPrev = 1; + let secondPrev = 0; + + for (let i = 2; i <= count; i++) { + let current = firstPrev + secondPrev; + secondPrev = firstPrev; + firstPrev = current; + } + + return firstPrev; + +}; + +// Another way to do it is by using an iterative approach with an array containing two values, 0 and 1. +// const fib = [0, 1]; +// for (let i = 2; i <= count; i++) { +// fib[i] = fib[i - 1] + fib[i - 2]; +// } +// return fib[count]; + +module.exports = fibonacci; diff --git a/10_fibonacci/solution/fibonacci-solution.spec.js b/10_fibonacci/solution/fibonacci-solution.spec.js new file mode 100644 index 0000000..fdb0bad --- /dev/null +++ b/10_fibonacci/solution/fibonacci-solution.spec.js @@ -0,0 +1,37 @@ +const fibonacci = require('./fibonacci-solution') + +describe('fibonacci', () => { + test('4th fibonacci number is 3', () => { + expect(fibonacci(4)).toBe(3); + }); + test('6th fibonacci number is 8', () => { + expect(fibonacci(6)).toBe(8); + }); + test('10th fibonacci number is 55', () => { + expect(fibonacci(10)).toBe(55); + }); + test('15th fibonacci number is 610', () => { + expect(fibonacci(15)).toBe(610); + }); + test('25th fibonacci number is 75025', () => { + expect(fibonacci(25)).toBe(75025); + }); + test('0th fibonacci number is 0', () => { + expect(fibonacci(0)).toBe(0); + }); + test('doesn\'t accept negatives', () => { + expect(fibonacci(-25)).toBe("OOPS"); + }); + test('DOES accept strings', () => { + expect(fibonacci("0")).toBe(0); + }); + test('DOES accept strings', () => { + expect(fibonacci("1")).toBe(1); + }); + test('DOES accept strings', () => { + expect(fibonacci("2")).toBe(1); + }); + test('DOES accept strings', () => { + expect(fibonacci("8")).toBe(21); + }); +}); \ No newline at end of file diff --git a/11_getTheTitles/README.md b/11_getTheTitles/README.md new file mode 100644 index 0000000..fb8bf95 --- /dev/null +++ b/11_getTheTitles/README.md @@ -0,0 +1,26 @@ +# Exercise 11 - Get the Titles! + +You are given an array of objects that represent books with an author and a title that looks like this: + +```javascript +const books = [ + { + title: 'Book', + author: 'Name' + }, + { + title: 'Book2', + author: 'Name2' + } +] +``` + +Your job is to write a function that takes the array and returns an array of titles: + +```javascript +getTheTitles(books) // ['Book','Book2'] +``` + +## Hints + +- You should use a built-in javascript method to do most of the work for you! diff --git a/11_getTheTitles/getTheTitles.js b/11_getTheTitles/getTheTitles.js new file mode 100644 index 0000000..74b04df --- /dev/null +++ b/11_getTheTitles/getTheTitles.js @@ -0,0 +1,6 @@ +const getTheTitles = function() { + +}; + +// Do not edit below this line +module.exports = getTheTitles; diff --git a/11_getTheTitles/getTheTitles.spec.js b/11_getTheTitles/getTheTitles.spec.js new file mode 100644 index 0000000..945d9f0 --- /dev/null +++ b/11_getTheTitles/getTheTitles.spec.js @@ -0,0 +1,18 @@ +const getTheTitles = require('./getTheTitles') + +describe('getTheTitles', () => { + const books = [ + { + title: 'Book', + author: 'Name' + }, + { + title: 'Book2', + author: 'Name2' + } + ] + + test('gets titles', () => { + expect(getTheTitles(books)).toEqual(['Book','Book2']); + }); +}); diff --git a/11_getTheTitles/solution/getTheTitles-solution.js b/11_getTheTitles/solution/getTheTitles-solution.js new file mode 100644 index 0000000..3146e88 --- /dev/null +++ b/11_getTheTitles/solution/getTheTitles-solution.js @@ -0,0 +1,5 @@ +const getTheTitles = function (array) { + return array.map((book) => book.title); +}; + +module.exports = getTheTitles; diff --git a/11_getTheTitles/solution/getTheTitles-solution.spec.js b/11_getTheTitles/solution/getTheTitles-solution.spec.js new file mode 100644 index 0000000..37e01dd --- /dev/null +++ b/11_getTheTitles/solution/getTheTitles-solution.spec.js @@ -0,0 +1,18 @@ +const getTheTitles = require('./getTheTitles-solution'); + +describe('getTheTitles', () => { + const books = [ + { + title: 'Book', + author: 'Name', + }, + { + title: 'Book2', + author: 'Name2', + }, + ]; + + test('gets titles', () => { + expect(getTheTitles(books)).toEqual(['Book', 'Book2']); + }); +}); diff --git a/12_findTheOldest/README.md b/12_findTheOldest/README.md new file mode 100644 index 0000000..087f45e --- /dev/null +++ b/12_findTheOldest/README.md @@ -0,0 +1,10 @@ +# Exercise 12 - Find the Oldest + +Given an array of objects representing people with a birth and death year, return the oldest person. + +Now that you've reached the final exercise, you should be fairly comfortable getting the information you need from test case(s). Take a look at how the array of objects is constructed in this exercise's test cases to help you write your function. + +## Hints +- You should return the whole person object, but the tests mostly just check to make sure the name is correct. +- This can be done with a couple of chained array methods, or by using `reduce`. +- One of the tests checks for people with no death-date.. use JavaScript's Date function to get their age as of today. diff --git a/12_findTheOldest/findTheOldest.js b/12_findTheOldest/findTheOldest.js new file mode 100644 index 0000000..366856a --- /dev/null +++ b/12_findTheOldest/findTheOldest.js @@ -0,0 +1,6 @@ +const findTheOldest = function() { + +}; + +// Do not edit below this line +module.exports = findTheOldest; diff --git a/12_findTheOldest/findTheOldest.spec.js b/12_findTheOldest/findTheOldest.spec.js new file mode 100644 index 0000000..732faaa --- /dev/null +++ b/12_findTheOldest/findTheOldest.spec.js @@ -0,0 +1,62 @@ +const findTheOldest = require('./findTheOldest') + +describe('findTheOldest', () => { + test('finds the person with the greatest age!', () => { + const people = [ + { + name: "Carly", + yearOfBirth: 1942, + yearOfDeath: 1970, + }, + { + name: "Ray", + yearOfBirth: 1962, + yearOfDeath: 2011, + }, + { + name: "Jane", + yearOfBirth: 1912, + yearOfDeath: 1941, + }, + ] + expect(findTheOldest(people).name).toBe('Ray'); + }); + test.skip('finds the person with the greatest age if someone is still living', () => { + const people = [ + { + name: "Carly", + yearOfBirth: 2018, + }, + { + name: "Ray", + yearOfBirth: 1962, + yearOfDeath: 2011, + }, + { + name: "Jane", + yearOfBirth: 1912, + yearOfDeath: 1941, + }, + ] + expect(findTheOldest(people).name).toBe('Ray'); + }); + test.skip('finds the person with the greatest age if the OLDEST is still living', () => { + const people = [ + { + name: "Carly", + yearOfBirth: 1066, + }, + { + name: "Ray", + yearOfBirth: 1962, + yearOfDeath: 2011, + }, + { + name: "Jane", + yearOfBirth: 1912, + yearOfDeath: 1941, + }, + ] + expect(findTheOldest(people).name).toBe('Carly'); + }); +}); diff --git a/12_findTheOldest/solution/findTheOldest-solution.js b/12_findTheOldest/solution/findTheOldest-solution.js new file mode 100644 index 0000000..ae4e272 --- /dev/null +++ b/12_findTheOldest/solution/findTheOldest-solution.js @@ -0,0 +1,19 @@ +const findTheOldest = function (array) { + return array.reduce((oldest, currentPerson) => { + const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath); + const currentAge = getAge( + currentPerson.yearOfBirth, + currentPerson.yearOfDeath + ); + return oldestAge < currentAge ? currentPerson : oldest; + }); +}; + +const getAge = function (birth, death) { + if (!death) { + death = new Date().getFullYear(); + } + return death - birth; +}; + +module.exports = findTheOldest; diff --git a/12_findTheOldest/solution/findTheOldest-solution.spec.js b/12_findTheOldest/solution/findTheOldest-solution.spec.js new file mode 100644 index 0000000..c92550c --- /dev/null +++ b/12_findTheOldest/solution/findTheOldest-solution.spec.js @@ -0,0 +1,62 @@ +const findTheOldest = require('./findTheOldest-solution'); + +describe('findTheOldest', () => { + test('finds the oldest person!', () => { + const people = [ + { + name: 'Carly', + yearOfBirth: 1942, + yearOfDeath: 1970, + }, + { + name: 'Ray', + yearOfBirth: 1962, + yearOfDeath: 2011, + }, + { + name: 'Jane', + yearOfBirth: 1912, + yearOfDeath: 1941, + }, + ]; + expect(findTheOldest(people).name).toBe('Ray'); + }); + test('finds the oldest person if someone is still living', () => { + const people = [ + { + name: 'Carly', + yearOfBirth: 2018, + }, + { + name: 'Ray', + yearOfBirth: 1962, + yearOfDeath: 2011, + }, + { + name: 'Jane', + yearOfBirth: 1912, + yearOfDeath: 1941, + }, + ]; + expect(findTheOldest(people).name).toBe('Ray'); + }); + test('finds the oldest person if the OLDEST is still living', () => { + const people = [ + { + name: 'Carly', + yearOfBirth: 1066, + }, + { + name: 'Ray', + yearOfBirth: 1962, + yearOfDeath: 2011, + }, + { + name: 'Jane', + yearOfBirth: 1912, + yearOfDeath: 1941, + }, + ]; + expect(findTheOldest(people).name).toBe('Carly'); + }); +}); diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 120000 index 0000000..cf76760 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/node_modules/.bin/browserslist b/node_modules/.bin/browserslist new file mode 120000 index 0000000..3cd991b --- /dev/null +++ b/node_modules/.bin/browserslist @@ -0,0 +1 @@ +../browserslist/cli.js \ No newline at end of file diff --git a/node_modules/.bin/eslint b/node_modules/.bin/eslint new file mode 120000 index 0000000..810e4bc --- /dev/null +++ b/node_modules/.bin/eslint @@ -0,0 +1 @@ +../eslint/bin/eslint.js \ No newline at end of file diff --git a/node_modules/.bin/esparse b/node_modules/.bin/esparse new file mode 120000 index 0000000..7423b18 --- /dev/null +++ b/node_modules/.bin/esparse @@ -0,0 +1 @@ +../esprima/bin/esparse.js \ No newline at end of file diff --git a/node_modules/.bin/esvalidate b/node_modules/.bin/esvalidate new file mode 120000 index 0000000..16069ef --- /dev/null +++ b/node_modules/.bin/esvalidate @@ -0,0 +1 @@ +../esprima/bin/esvalidate.js \ No newline at end of file diff --git a/node_modules/.bin/import-local-fixture b/node_modules/.bin/import-local-fixture new file mode 120000 index 0000000..ff4b104 --- /dev/null +++ b/node_modules/.bin/import-local-fixture @@ -0,0 +1 @@ +../import-local/fixtures/cli.js \ No newline at end of file diff --git a/node_modules/.bin/is-docker b/node_modules/.bin/is-docker new file mode 120000 index 0000000..9896ba5 --- /dev/null +++ b/node_modules/.bin/is-docker @@ -0,0 +1 @@ +../is-docker/cli.js \ No newline at end of file diff --git a/node_modules/.bin/jest b/node_modules/.bin/jest new file mode 120000 index 0000000..61c1861 --- /dev/null +++ b/node_modules/.bin/jest @@ -0,0 +1 @@ +../jest/bin/jest.js \ No newline at end of file diff --git a/node_modules/.bin/js-yaml b/node_modules/.bin/js-yaml new file mode 120000 index 0000000..9dbd010 --- /dev/null +++ b/node_modules/.bin/js-yaml @@ -0,0 +1 @@ +../js-yaml/bin/js-yaml.js \ No newline at end of file diff --git a/node_modules/.bin/jsesc b/node_modules/.bin/jsesc new file mode 120000 index 0000000..7237604 --- /dev/null +++ b/node_modules/.bin/jsesc @@ -0,0 +1 @@ +../jsesc/bin/jsesc \ No newline at end of file diff --git a/node_modules/.bin/json5 b/node_modules/.bin/json5 new file mode 120000 index 0000000..217f379 --- /dev/null +++ b/node_modules/.bin/json5 @@ -0,0 +1 @@ +../json5/lib/cli.js \ No newline at end of file diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which new file mode 120000 index 0000000..6f8415e --- /dev/null +++ b/node_modules/.bin/node-which @@ -0,0 +1 @@ +../which/bin/node-which \ No newline at end of file diff --git a/node_modules/.bin/parser b/node_modules/.bin/parser new file mode 120000 index 0000000..ce7bf97 --- /dev/null +++ b/node_modules/.bin/parser @@ -0,0 +1 @@ +../@babel/parser/bin/babel-parser.js \ No newline at end of file diff --git a/node_modules/.bin/resolve b/node_modules/.bin/resolve new file mode 120000 index 0000000..b6afda6 --- /dev/null +++ b/node_modules/.bin/resolve @@ -0,0 +1 @@ +../resolve/bin/resolve \ No newline at end of file diff --git a/node_modules/.bin/rimraf b/node_modules/.bin/rimraf new file mode 120000 index 0000000..4cd49a4 --- /dev/null +++ b/node_modules/.bin/rimraf @@ -0,0 +1 @@ +../rimraf/bin.js \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.bin/update-browserslist-db b/node_modules/.bin/update-browserslist-db new file mode 120000 index 0000000..b11e16f --- /dev/null +++ b/node_modules/.bin/update-browserslist-db @@ -0,0 +1 @@ +../update-browserslist-db/cli.js \ No newline at end of file diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 120000 index 0000000..588f70e --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1 @@ +../uuid/dist/bin/uuid \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..380b46e --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,5532 @@ +{ + "name": "javascript-exercises", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@aashutoshrathi/word-wrap": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz", + "integrity": "sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz", + "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", + "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", + "dev": true, + "dependencies": { + "@babel/highlight": "^7.23.4", + "chalk": "^2.4.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/code-frame/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/code-frame/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "node_modules/@babel/code-frame/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/code-frame/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.22.9", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.22.9.tgz", + "integrity": "sha512-5UamI7xkUcJ3i9qVDS+KFDEK8/7oJ55/sJMB1Ge7IEapr7KfdfV/HErR+koZwOfd+SgtFKOKRhRakdg++DcJpQ==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.22.11.tgz", + "integrity": "sha512-lh7RJrtPdhibbxndr6/xx0w8+CVlY5FJZiaSz908Fpy+G0xkBFTvwLcKJFF4PJxVfGhVWNebikpWGnOoC71juQ==", + "dev": true, + "dependencies": { + "@ampproject/remapping": "^2.2.0", + "@babel/code-frame": "^7.22.10", + "@babel/generator": "^7.22.10", + "@babel/helper-compilation-targets": "^7.22.10", + "@babel/helper-module-transforms": "^7.22.9", + "@babel/helpers": "^7.22.11", + "@babel/parser": "^7.22.11", + "@babel/template": "^7.22.5", + "@babel/traverse": "^7.22.11", + "@babel/types": "^7.22.11", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", + "dev": true + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", + "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.23.6", + "@jridgewell/gen-mapping": "^0.3.2", + "@jridgewell/trace-mapping": "^0.3.17", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.22.10", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.22.10.tgz", + "integrity": "sha512-JMSwHD4J7SLod0idLq5PKgI+6g/hLD/iuWBq08ZX49xE14VpVEojJ5rHWptpirV2j020MvypRLAXAO50igCJ5Q==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.22.9", + "@babel/helper-validator-option": "^7.22.5", + "browserslist": "^4.21.9", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-environment-visitor": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-function-name": { + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", + "dev": true, + "dependencies": { + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-hoist-variables": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", + "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.5.tgz", + "integrity": "sha512-8Dl6+HD/cKifutF5qGd/8ZJi84QeAKh+CEe1sBzz8UayBBGg1dAIJrdHOcOM5b2MpzWL2yuotJTtGjETq0qjXg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.22.9", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.22.9.tgz", + "integrity": "sha512-t+WA2Xn5K+rTeGtC8jCsdAH52bjggG5TKRuRrAGNM/mjIbO4GxvlLMFOEz9wXY5I2XQ60PMFsAG2WIcG82dQMQ==", + "dev": true, + "dependencies": { + "@babel/helper-environment-visitor": "^7.22.5", + "@babel/helper-module-imports": "^7.22.5", + "@babel/helper-simple-access": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/helper-validator-identifier": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz", + "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", + "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-split-export-declaration": { + "version": "7.22.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", + "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.22.5.tgz", + "integrity": "sha512-R3oB6xlIVKUnxNUxbmgq7pKjxpru24zlimpE8WK47fACIlM0II/Hm1RS8IaOI7NgCr6LNS+jl5l75m20npAziw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.22.11.tgz", + "integrity": "sha512-vyOXC8PBWaGc5h7GMsNx68OH33cypkEDJCHvYVVgVbbxJDROYVtexSk0gK5iCF1xNjRIN2s8ai7hwkWDq5szWg==", + "dev": true, + "dependencies": { + "@babel/template": "^7.22.5", + "@babel/traverse": "^7.22.11", + "@babel/types": "^7.22.11" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", + "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/highlight/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/parser": { + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz", + "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==", + "dev": true, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.22.5.tgz", + "integrity": "sha512-gvyP4hZrgrs/wWMaocvxZ44Hw0b3W8Pe+cMxc8V1ULQ07oh8VNbIRaoD1LRZVTvD+0nieDKjfgKg89sD7rrKrg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.22.5.tgz", + "integrity": "sha512-1mS2o03i7t1c6VzH6fdQ3OA8tcEIxwG18zIPRp+UY1Ihv6W+XZzBCVxExF9upussPXJ0xE9XRHwMoNs1ep/nRQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", + "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.22.13", + "@babel/parser": "^7.22.15", + "@babel/types": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.23.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.7.tgz", + "integrity": "sha512-tY3mM8rH9jM0YHFGyfC0/xf+SB5eKUu7HPj7/k3fpi9dAlsMc5YbQvDi0Sh2QTPXqMhyaAtzAr807TIyfQrmyg==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.23.5", + "@babel/generator": "^7.23.6", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/parser": "^7.23.6", + "@babel/types": "^7.23.6", + "debug": "^4.3.1", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse/node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/types": { + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.6.tgz", + "integrity": "sha512-+uarb83brBzPKN38NX1MkB6vb6+mwvR6amUulqAE7ccQw1pEl+bCia9TbdG1lsnFP7lZySvUn37CHyXQdfTwzg==", + "dev": true, + "dependencies": { + "@babel/helper-string-parser": "^7.23.4", + "@babel/helper-validator-identifier": "^7.22.20", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "dev": true + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", + "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^3.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.7.0.tgz", + "integrity": "sha512-+HencqxU7CFJnQb7IKtuNBqS6Yx3Tz4kOL8BJXo+JyeiBm5MEX6pO8onXDkjrkCRlfYXS1Axro15ZjVFe9YgsA==", + "dev": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.2.tgz", + "integrity": "sha512-+wvgpDsrB1YqAMdEUCcnTlpfVBH7Vqn6A/NT3D8WVXFIaKMlErPIZT3oCIAVCOtarRpMtelZLqJeU3t7WY6X6g==", + "dev": true, + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "node_modules/@eslint/eslintrc/node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@eslint/js": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.47.0.tgz", + "integrity": "sha512-P6omY1zv5MItm93kLM8s2vr1HICJH8v0dvddDhysbIuZ+vcjOHg5Zbkf1mTkcmi2JA9oBG2anOkRnW8WJTS8Og==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@humanwhocodes/config-array": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.10.tgz", + "integrity": "sha512-KVVjQmNUepDVGXNuoRRdmmEjruj0KfiGSbS8LVc12LMsWDQzRXJ0qdhN8L8uUigKpfEHRhlaQFY0ib1tnUbNeQ==", + "dev": true, + "dependencies": { + "@humanwhocodes/object-schema": "^1.2.1", + "debug": "^4.1.1", + "minimatch": "^3.0.5" + }, + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/object-schema": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", + "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", + "dev": true + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.6.4.tgz", + "integrity": "sha512-wNK6gC0Ha9QeEPSkeJedQuTQqxZYnDPuDcDhVuVatRvMkL4D0VTvFVZj+Yuh6caG2aOfzkUZ36KtCmLNtR02hw==", + "dev": true, + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.6.3", + "jest-util": "^29.6.3", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/core": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.6.4.tgz", + "integrity": "sha512-U/vq5ccNTSVgYH7mHnodHmCffGWHJnz/E1BEWlLuK5pM4FZmGfBn/nrJGLjUsSmyx3otCeqc1T31F4y08AMDLg==", + "dev": true, + "dependencies": { + "@jest/console": "^29.6.4", + "@jest/reporters": "^29.6.4", + "@jest/test-result": "^29.6.4", + "@jest/transform": "^29.6.4", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.6.3", + "jest-config": "^29.6.4", + "jest-haste-map": "^29.6.4", + "jest-message-util": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.6.4", + "jest-resolve-dependencies": "^29.6.4", + "jest-runner": "^29.6.4", + "jest-runtime": "^29.6.4", + "jest-snapshot": "^29.6.4", + "jest-util": "^29.6.3", + "jest-validate": "^29.6.3", + "jest-watcher": "^29.6.4", + "micromatch": "^4.0.4", + "pretty-format": "^29.6.3", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/environment": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.6.4.tgz", + "integrity": "sha512-sQ0SULEjA1XUTHmkBRl7A1dyITM9yb1yb3ZNKPX3KlTd6IG7mWUe3e2yfExtC2Zz1Q+mMckOLHmL/qLiuQJrBQ==", + "dev": true, + "dependencies": { + "@jest/fake-timers": "^29.6.4", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.6.4.tgz", + "integrity": "sha512-Warhsa7d23+3X5bLbrbYvaehcgX5TLYhI03JKoedTiI8uJU4IhqYBWF7OSSgUyz4IgLpUYPkK0AehA5/fRclAA==", + "dev": true, + "dependencies": { + "expect": "^29.6.4", + "jest-snapshot": "^29.6.4" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.6.4.tgz", + "integrity": "sha512-FEhkJhqtvBwgSpiTrocquJCdXPsyvNKcl/n7A3u7X4pVoF4bswm11c9d4AV+kfq2Gpv/mM8x7E7DsRvH+djkrg==", + "dev": true, + "dependencies": { + "jest-get-type": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/fake-timers": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.6.4.tgz", + "integrity": "sha512-6UkCwzoBK60edXIIWb0/KWkuj7R7Qq91vVInOe3De6DSpaEiqjKcJw4F7XUet24Wupahj9J6PlR09JqJ5ySDHw==", + "dev": true, + "dependencies": { + "@jest/types": "^29.6.3", + "@sinonjs/fake-timers": "^10.0.2", + "@types/node": "*", + "jest-message-util": "^29.6.3", + "jest-mock": "^29.6.3", + "jest-util": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/globals": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.6.4.tgz", + "integrity": "sha512-wVIn5bdtjlChhXAzVXavcY/3PEjf4VqM174BM3eGL5kMxLiZD5CLnbmkEyA1Dwh9q8XjP6E8RwjBsY/iCWrWsA==", + "dev": true, + "dependencies": { + "@jest/environment": "^29.6.4", + "@jest/expect": "^29.6.4", + "@jest/types": "^29.6.3", + "jest-mock": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/reporters": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.6.4.tgz", + "integrity": "sha512-sxUjWxm7QdchdrD3NfWKrL8FBsortZeibSJv4XLjESOOjSUOkjQcb0ZHJwfhEGIvBvTluTzfG2yZWZhkrXJu8g==", + "dev": true, + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.6.4", + "@jest/test-result": "^29.6.4", + "@jest/transform": "^29.6.4", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.6.3", + "jest-util": "^29.6.3", + "jest-worker": "^29.6.4", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "dev": true, + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", + "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-result": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.6.4.tgz", + "integrity": "sha512-uQ1C0AUEN90/dsyEirgMLlouROgSY+Wc/JanVVk0OiUKa5UFh7sJpMEM3aoUBAz2BRNvUJ8j3d294WFuRxSyOQ==", + "dev": true, + "dependencies": { + "@jest/console": "^29.6.4", + "@jest/types": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.6.4.tgz", + "integrity": "sha512-E84M6LbpcRq3fT4ckfKs9ryVanwkaIB0Ws9bw3/yP4seRLg/VaCZ/LgW0MCq5wwk4/iP/qnilD41aj2fsw2RMg==", + "dev": true, + "dependencies": { + "@jest/test-result": "^29.6.4", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.6.4", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.6.4.tgz", + "integrity": "sha512-8thgRSiXUqtr/pPGY/OsyHuMjGyhVnWrFAwoxmIemlBuiMyU1WFs0tXoNxzcr4A4uErs/ABre76SGmrr5ab/AA==", + "dev": true, + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.6.4", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.6.3", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", + "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", + "dev": true, + "dependencies": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", + "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "dev": true, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.19", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz", + "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.8", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", + "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "dev": true + }, + "node_modules/@sinonjs/commons": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz", + "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==", + "dev": true, + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^3.0.0" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.1.tgz", + "integrity": "sha512-aACu/U/omhdk15O4Nfb+fHgH/z3QsfQzpnvRZhYhThms83ZnAOZz7zZAWO7mn2yyNQaA4xTO8GLK3uqFU4bYYw==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.6.4", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", + "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", + "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.1.tgz", + "integrity": "sha512-MitHFXnhtgwsGZWtT68URpOvLN4EREih1u3QtQiN4VdAxWKRVvGCSvw/Qth0M0Qq3pJpnGOu5JaM/ydK7OGbqg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.20.7" + } + }, + "node_modules/@types/graceful-fs": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.6.tgz", + "integrity": "sha512-Sig0SNORX9fdW+bQuTEovKj3uHcUL6LQKbCrrqb1X7J6/ReAbhCXRAhc+SMejhLELFj2QcyuxmUooZ4bt5ReSw==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", + "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", + "dev": true + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "dev": true, + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", + "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", + "dev": true, + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "dev": true + }, + "node_modules/@types/node": { + "version": "20.5.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.6.tgz", + "integrity": "sha512-Gi5wRGPbbyOTX+4Y2iULQ27oUPrefaB0PxGQJnfyWN3kvEDGM3mIB5M/gQLmitZf7A9FmLeaqxD3L1CXpm3VKQ==", + "dev": true + }, + "node_modules/@types/stack-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", + "dev": true + }, + "node_modules/@types/yargs": { + "version": "17.0.24", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.24.tgz", + "integrity": "sha512-6i0aC7jV6QzQB8ne1joVZ0eSFIstHsCrobmOtghM11yGlH0j43FKL2UhWdELkyps0zuf7qVTUVCCR+tgSlyLLw==", + "dev": true, + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", + "dev": true + }, + "node_modules/acorn": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", + "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "dev": true, + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-escapes/node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.0.tgz", + "integrity": "sha512-LPuwb2P+NrQw3XhxGc36+XSvuBPopovXYTR9Ew++Du9Yb/bx5AzBfrIsBoj0EZUifjQU+sHL21sseZ3jerWO/A==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "is-array-buffer": "^3.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-includes": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.6.tgz", + "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "get-intrinsic": "^1.1.3", + "is-string": "^1.0.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlastindex": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.2.tgz", + "integrity": "sha512-tb5thFFlUcp7NdNF6/MpDk/1r/4awWG1FIz3YqDf+/zJSTezBb+/5WViH41obXULHVpDzoiCLpJ/ZO9YbJMsdw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "es-shim-unscopables": "^1.0.0", + "get-intrinsic": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flat": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.1.tgz", + "integrity": "sha512-roTU0KWIOmJ4DRLmwKd19Otg0/mT3qPNt0Qb3GWW8iObuZXxrjB/pzn0R3hqpRSWg4HCwqx+0vwOnWnvlOyeIA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "es-shim-unscopables": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.1.tgz", + "integrity": "sha512-8UGn9O1FDVvMNB0UlLv4voxRMze7+FpHyF5mSMRjWHUMlpoDViniy05870VlxhfgTnLbpuwTzvD76MTtWxB/mQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "es-shim-unscopables": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.1.tgz", + "integrity": "sha512-09x0ZWFEjj4WD8PDbykUwo3t9arLn8NIzmmYEJFpYekOAQjpkGSyrQhNoRTcwwcFRu+ycWF78QZ63oWTqSjBcw==", + "dev": true, + "dependencies": { + "array-buffer-byte-length": "^1.0.0", + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "get-intrinsic": "^1.2.1", + "is-array-buffer": "^3.0.2", + "is-shared-array-buffer": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", + "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/babel-jest": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.6.4.tgz", + "integrity": "sha512-meLj23UlSLddj6PC+YTOFRgDAtjnZom8w/ACsrx0gtPtv5cJZk0A5Unk5bV4wixD7XaPCN1fQvpww8czkZURmw==", + "dev": true, + "dependencies": { + "@jest/transform": "^29.6.4", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.6.3", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.8.0" + } + }, + "node_modules/babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", + "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", + "dev": true, + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/babel-plugin-jest-hoist": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", + "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", + "dev": true, + "dependencies": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/babel-preset-current-node-syntax": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", + "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", + "dev": true, + "dependencies": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.8.3", + "@babel/plugin-syntax-import-meta": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.8.3", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-top-level-await": "^7.8.3" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/babel-preset-jest": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", + "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", + "dev": true, + "dependencies": { + "babel-plugin-jest-hoist": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.21.10", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.10.tgz", + "integrity": "sha512-bipEBdZfVH5/pwrvqc+Ub0kUPVfGUhlKxbvfD+z1BDnPEO/X98ruXGA1WP5ASpAFKan7Qr6j736IacbZQuAlKQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "caniuse-lite": "^1.0.30001517", + "electron-to-chromium": "^1.4.477", + "node-releases": "^2.0.13", + "update-browserslist-db": "^1.0.11" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "dev": true, + "dependencies": { + "node-int64": "^0.4.0" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001522", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001522.tgz", + "integrity": "sha512-TKiyTVZxJGhsTszLuzb+6vUZSjVOAhClszBr2Ta2k9IwtNBT/4dzmL6aywt0HCgEZlmwJzXJd8yNiob6HgwTRg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ] + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/ci-info": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.8.0.tgz", + "integrity": "sha512-eXTggHWSooYhq49F2opQhuHWgzucfF2YgODK4e1566GQs5BIfP30B0oenwBJHfWxAs2fyPB1s7Mg949zLf61Yw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "engines": { + "node": ">=8" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz", + "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==", + "dev": true + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "dev": true, + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, + "node_modules/collect-v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz", + "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==", + "dev": true + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "node_modules/confusing-browser-globals": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/confusing-browser-globals/-/confusing-browser-globals-1.0.11.tgz", + "integrity": "sha512-JsPKdmh8ZkmnHxDk55FZ1TqVLvEQTvoByJZRN9jzI0UjxK/QgAmsphz7PGtqgPieQZ/CQcHWXCR7ATDNhGe+YA==", + "dev": true + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dedent": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.1.tgz", + "integrity": "sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg==", + "dev": true, + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "dependencies": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/diff-sequences": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "dev": true, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.4.501", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.501.tgz", + "integrity": "sha512-NCF5hZUg73MEP0guvIM+BjPs9W07UeAuc5XCNqRZZTKJxLjE0ZS/Zo5UsV8bbs2y/jeKRPFPzdWdBfOGEZTXKg==", + "dev": true + }, + "node_modules/emittery": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sindresorhus/emittery?sponsor=1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-abstract": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.22.1.tgz", + "integrity": "sha512-ioRRcXMO6OFyRpyzV3kE1IIBd4WG5/kltnzdxSCqoP8CMGs/Li+M1uF5o7lOkZVFjDs+NLesthnF66Pg/0q0Lw==", + "dev": true, + "dependencies": { + "array-buffer-byte-length": "^1.0.0", + "arraybuffer.prototype.slice": "^1.0.1", + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "es-set-tostringtag": "^2.0.1", + "es-to-primitive": "^1.2.1", + "function.prototype.name": "^1.1.5", + "get-intrinsic": "^1.2.1", + "get-symbol-description": "^1.0.0", + "globalthis": "^1.0.3", + "gopd": "^1.0.1", + "has": "^1.0.3", + "has-property-descriptors": "^1.0.0", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "internal-slot": "^1.0.5", + "is-array-buffer": "^3.0.2", + "is-callable": "^1.2.7", + "is-negative-zero": "^2.0.2", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "is-string": "^1.0.7", + "is-typed-array": "^1.1.10", + "is-weakref": "^1.0.2", + "object-inspect": "^1.12.3", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.5.0", + "safe-array-concat": "^1.0.0", + "safe-regex-test": "^1.0.0", + "string.prototype.trim": "^1.2.7", + "string.prototype.trimend": "^1.0.6", + "string.prototype.trimstart": "^1.0.6", + "typed-array-buffer": "^1.0.0", + "typed-array-byte-length": "^1.0.0", + "typed-array-byte-offset": "^1.0.0", + "typed-array-length": "^1.0.4", + "unbox-primitive": "^1.0.2", + "which-typed-array": "^1.1.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.1.tgz", + "integrity": "sha512-g3OMbtlwY3QewlqAiMLI47KywjWZoEytKr8pf6iTC8uJq5bIAH52Z9pnQ8pVL6whrCto53JZDuUIsifGeLorTg==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.1.3", + "has": "^1.0.3", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-shim-unscopables": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.0.tgz", + "integrity": "sha512-Jm6GPcCdC30eMLbZ2x8z2WuRwAws3zTBBKuusffYVUrNj/GVSUAZ+xKMaUpfNDR5IbyNA5LJbaecoUVbmUcB1w==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + } + }, + "node_modules/es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "dependencies": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.47.0.tgz", + "integrity": "sha512-spUQWrdPt+pRVP1TTJLmfRNJJHHZryFmptzcafwSvHsceV81djHOdnEeDmkdotZyLNjDhrOasNK8nikkoG1O8Q==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.2", + "@eslint/js": "^8.47.0", + "@humanwhocodes/config-array": "^0.11.10", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-config-airbnb-base": { + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/eslint-config-airbnb-base/-/eslint-config-airbnb-base-15.0.0.tgz", + "integrity": "sha512-xaX3z4ZZIcFLvh2oUNvcX5oEofXda7giYmuplVxoOg5A7EXJMrUyqRgR+mhDhPK8LZ4PttFOBvCYDbX3sUoUig==", + "dev": true, + "dependencies": { + "confusing-browser-globals": "^1.0.10", + "object.assign": "^4.1.2", + "object.entries": "^1.1.5", + "semver": "^6.3.0" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + }, + "peerDependencies": { + "eslint": "^7.32.0 || ^8.2.0", + "eslint-plugin-import": "^2.25.2" + } + }, + "node_modules/eslint-config-airbnb-base/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-import-resolver-node": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", + "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "dev": true, + "dependencies": { + "debug": "^3.2.7", + "is-core-module": "^2.13.0", + "resolve": "^1.22.4" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-module-utils": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.8.0.tgz", + "integrity": "sha512-aWajIYfsqCKRDgUfjEXNN/JlrzauMuSEy5sbd7WXbtW3EH6A6MpwEh42c7qD+MqQo9QMJ6fWLAeIJynx0g6OAw==", + "dev": true, + "dependencies": { + "debug": "^3.2.7" + }, + "engines": { + "node": ">=4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import": { + "version": "2.28.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.28.1.tgz", + "integrity": "sha512-9I9hFlITvOV55alzoKBI+K9q74kv0iKMeY6av5+umsNwayt59fz692daGyjR+oStBQgx6nwR9rXldDev3Clw+A==", + "dev": true, + "dependencies": { + "array-includes": "^3.1.6", + "array.prototype.findlastindex": "^1.2.2", + "array.prototype.flat": "^1.3.1", + "array.prototype.flatmap": "^1.3.1", + "debug": "^3.2.7", + "doctrine": "^2.1.0", + "eslint-import-resolver-node": "^0.3.7", + "eslint-module-utils": "^2.8.0", + "has": "^1.0.3", + "is-core-module": "^2.13.0", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.6", + "object.groupby": "^1.0.0", + "object.values": "^1.1.6", + "semver": "^6.3.1", + "tsconfig-paths": "^3.14.2" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8" + } + }, + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import/node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-scope": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", + "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "node_modules/eslint/node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/eslint/node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/espree": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "dev": true, + "dependencies": { + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/acorn": { + "version": "8.10.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", + "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esquery": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", + "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", + "dev": true, + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/expect": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.6.4.tgz", + "integrity": "sha512-F2W2UyQ8XYyftHT57dtfg8Ue3X5qLgm2sSug0ivvLRH/VKNRL/pDxg/TH7zVzbQB0tu80clNFy6LU7OS/VSEKA==", + "dev": true, + "dependencies": { + "@jest/expect-utils": "^29.6.4", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.6.4", + "jest-message-util": "^29.6.3", + "jest-util": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true + }, + "node_modules/fastq": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", + "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", + "dev": true, + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fb-watchman": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", + "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", + "dev": true, + "dependencies": { + "bser": "2.1.1" + } + }, + "node_modules/file-entry-cache": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "dev": true, + "dependencies": { + "flat-cache": "^3.0.4" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/flat-cache": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", + "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", + "dev": true, + "dependencies": { + "flatted": "^3.1.0", + "rimraf": "^3.0.2" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/flatted": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.7.tgz", + "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", + "dev": true + }, + "node_modules/for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "dev": true, + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "node_modules/function.prototype.name": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.5.tgz", + "integrity": "sha512-uN7m/BzVKQnCUF/iW8jYea67v++2u7m5UgENbHRtdDVclOUP+FMPlCNdmk0h/ysGyo2tavMJEDqJAkJdRa1vMA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "es-abstract": "^1.19.0", + "functions-have-names": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-symbol-description": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz", + "integrity": "sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "13.21.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.21.0.tgz", + "integrity": "sha512-ybyme3s4yy/t/3s35bewwXKOf7cvzfreG2lH0lZl0JB7I4GxRP2ghxOK/Nb9EkRXdbBXZLfq/p/0W2JUONB/Gg==", + "dev": true, + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.3.tgz", + "integrity": "sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA==", + "dev": true, + "dependencies": { + "define-properties": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true + }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true + }, + "node_modules/growly": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz", + "integrity": "sha512-+xGQY0YyAWCnqy7Cd++hc2JqMYzlm0dG30Jd0beaA64sROr8C4nt8Yc9V5Ro3avlSUDTN0ulqP/VBKi1/lLygw==", + "dev": true, + "optional": true, + "peer": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.1.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", + "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "dev": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/ignore": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "dev": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-local": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", + "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", + "dev": true, + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/internal-slot": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.5.tgz", + "integrity": "sha512-Y+R5hJrzs52QCG2laLn4udYVnxsfny9CpOhNhUvk/SSSVyF6T27FzRbF0sroPidSu3X8oEAkOn2K804mjpt6UQ==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.2.0", + "has": "^1.0.3", + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.2.tgz", + "integrity": "sha512-y+FyyR/w8vfIRq4eQcM1EYgSTnmHXPqaF+IgzgraytCFq5Xh8lllDVmAZolPJiZttZLeFSINPYMaEJ7/vWUa1w==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.0", + "is-typed-array": "^1.1.10" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true + }, + "node_modules/is-bigint": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "dev": true, + "dependencies": { + "has-bigints": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.0.tgz", + "integrity": "sha512-Z7dk6Qo8pOCp3l4tsX2C5ZVas4V+UxwQodwZhLopL91TX8UyyHEXafPcyoeeWuLrwzHcr3igO78wNLwHJHsMCQ==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "optional": true, + "peer": true, + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz", + "integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz", + "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-string": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "dev": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.12.tgz", + "integrity": "sha512-Z14TF2JNG8Lss5/HMqt0//T9JeHXttXy5pH/DBU4vi98ozO2btxzq9MwYDZYnKwU8nRsz/+GVFVRDq3DkVuSPg==", + "dev": true, + "dependencies": { + "which-typed-array": "^1.1.11" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", + "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "optional": true, + "peer": true, + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.0.tgz", + "integrity": "sha512-x58orMzEVfzPUKqlbLd1hXCnySCxKdDKa6Rjg97CwuLLRI4g3FHTdnExu1OqffVFay6zeMW+T6/DowFLndWnIw==", + "dev": true, + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz", + "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==", + "dev": true, + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.6.4.tgz", + "integrity": "sha512-tEFhVQFF/bzoYV1YuGyzLPZ6vlPrdfvDmmAxudA1dLEuiztqg2Rkx20vkKY32xiDROcD2KXlgZ7Cu8RPeEHRKw==", + "dev": true, + "dependencies": { + "@jest/core": "^29.6.4", + "@jest/types": "^29.6.3", + "import-local": "^3.0.2", + "jest-cli": "^29.6.4" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.6.3.tgz", + "integrity": "sha512-G5wDnElqLa4/c66ma5PG9eRjE342lIbF6SUnTJi26C3J28Fv2TVY2rOyKB9YGbSA5ogwevgmxc4j4aVjrEK6Yg==", + "dev": true, + "dependencies": { + "execa": "^5.0.0", + "jest-util": "^29.6.3", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-changed-files/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-circus": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.6.4.tgz", + "integrity": "sha512-YXNrRyntVUgDfZbjXWBMPslX1mQ8MrSG0oM/Y06j9EYubODIyHWP8hMUbjbZ19M3M+zamqEur7O80HODwACoJw==", + "dev": true, + "dependencies": { + "@jest/environment": "^29.6.4", + "@jest/expect": "^29.6.4", + "@jest/test-result": "^29.6.4", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^1.0.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.6.3", + "jest-matcher-utils": "^29.6.4", + "jest-message-util": "^29.6.3", + "jest-runtime": "^29.6.4", + "jest-snapshot": "^29.6.4", + "jest-util": "^29.6.3", + "p-limit": "^3.1.0", + "pretty-format": "^29.6.3", + "pure-rand": "^6.0.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-cli": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.6.4.tgz", + "integrity": "sha512-+uMCQ7oizMmh8ZwRfZzKIEszFY9ksjjEQnTEMTaL7fYiL3Kw4XhqT9bYh+A4DQKUb67hZn2KbtEnDuHvcgK4pQ==", + "dev": true, + "dependencies": { + "@jest/core": "^29.6.4", + "@jest/test-result": "^29.6.4", + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "import-local": "^3.0.2", + "jest-config": "^29.6.4", + "jest-util": "^29.6.3", + "jest-validate": "^29.6.3", + "prompts": "^2.0.1", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-config": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.6.4.tgz", + "integrity": "sha512-JWohr3i9m2cVpBumQFv2akMEnFEPVOh+9L2xIBJhJ0zOaci2ZXuKJj0tgMKQCBZAKA09H049IR4HVS/43Qb19A==", + "dev": true, + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.6.4", + "@jest/types": "^29.6.3", + "babel-jest": "^29.6.4", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.6.4", + "jest-environment-node": "^29.6.4", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.6.4", + "jest-runner": "^29.6.4", + "jest-util": "^29.6.3", + "jest-validate": "^29.6.3", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.6.3", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-diff": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.6.4.tgz", + "integrity": "sha512-9F48UxR9e4XOEZvoUXEHSWY4qC4zERJaOfrbBg9JpbJOO43R1vN76REt/aMGZoY6GD5g84nnJiBIVlscegefpw==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.6.3", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-docblock": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.6.3.tgz", + "integrity": "sha512-2+H+GOTQBEm2+qFSQ7Ma+BvyV+waiIFxmZF5LdpBsAEjWX8QYjSCa4FrkIYtbfXUJJJnFCYrOtt6TZ+IAiTjBQ==", + "dev": true, + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.6.3.tgz", + "integrity": "sha512-KoXfJ42k8cqbkfshW7sSHcdfnv5agDdHCPA87ZBdmHP+zJstTJc0ttQaJ/x7zK6noAL76hOuTIJ6ZkQRS5dcyg==", + "dev": true, + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "jest-util": "^29.6.3", + "pretty-format": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-environment-node": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.6.4.tgz", + "integrity": "sha512-i7SbpH2dEIFGNmxGCpSc2w9cA4qVD+wfvg2ZnfQ7XVrKL0NA5uDVBIiGH8SR4F0dKEv/0qI5r+aDomDf04DpEQ==", + "dev": true, + "dependencies": { + "@jest/environment": "^29.6.4", + "@jest/fake-timers": "^29.6.4", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.6.3", + "jest-util": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-get-type": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", + "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", + "dev": true, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-haste-map": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.6.4.tgz", + "integrity": "sha512-12Ad+VNTDHxKf7k+M65sviyynRoZYuL1/GTuhEVb8RYsNSNln71nANRb/faSyWvx0j+gHcivChXHIoMJrGYjog==", + "dev": true, + "dependencies": { + "@jest/types": "^29.6.3", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.6.3", + "jest-worker": "^29.6.4", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/jest-leak-detector": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.6.3.tgz", + "integrity": "sha512-0kfbESIHXYdhAdpLsW7xdwmYhLf1BRu4AA118/OxFm0Ho1b2RcTmO4oF6aAMaxpxdxnJ3zve2rgwzNBD4Zbm7Q==", + "dev": true, + "dependencies": { + "jest-get-type": "^29.6.3", + "pretty-format": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.6.4.tgz", + "integrity": "sha512-KSzwyzGvK4HcfnserYqJHYi7sZVqdREJ9DMPAKVbS98JsIAvumihaNUbjrWw0St7p9IY7A9UskCW5MYlGmBQFQ==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.6.4", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.6.3.tgz", + "integrity": "sha512-FtzaEEHzjDpQp51HX4UMkPZjy46ati4T5pEMyM6Ik48ztu4T9LQplZ6OsimHx7EuM9dfEh5HJa6D3trEftu3dA==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.6.3", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.6.3", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-mock": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.6.3.tgz", + "integrity": "sha512-Z7Gs/mOyTSR4yPsaZ72a/MtuK6RnC3JYqWONe48oLaoEcYwEDxqvbXz85G4SJrm2Z5Ar9zp6MiHF4AlFlRM4Pg==", + "dev": true, + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-util": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", + "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", + "dev": true, + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, + "node_modules/jest-regex-util": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", + "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", + "dev": true, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.6.4.tgz", + "integrity": "sha512-fPRq+0vcxsuGlG0O3gyoqGTAxasagOxEuyoxHeyxaZbc9QNek0AmJWSkhjlMG+mTsj+8knc/mWb3fXlRNVih7Q==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.6.4", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.6.3", + "jest-validate": "^29.6.3", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.6.4.tgz", + "integrity": "sha512-7+6eAmr1ZBF3vOAJVsfLj1QdqeXG+WYhidfLHBRZqGN24MFRIiKG20ItpLw2qRAsW/D2ZUUmCNf6irUr/v6KHA==", + "dev": true, + "dependencies": { + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.6.4" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.6.4.tgz", + "integrity": "sha512-SDaLrMmtVlQYDuG0iSPYLycG8P9jLI+fRm8AF/xPKhYDB2g6xDWjXBrR5M8gEWsK6KVFlebpZ4QsrxdyIX1Jaw==", + "dev": true, + "dependencies": { + "@jest/console": "^29.6.4", + "@jest/environment": "^29.6.4", + "@jest/test-result": "^29.6.4", + "@jest/transform": "^29.6.4", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.6.3", + "jest-environment-node": "^29.6.4", + "jest-haste-map": "^29.6.4", + "jest-leak-detector": "^29.6.3", + "jest-message-util": "^29.6.3", + "jest-resolve": "^29.6.4", + "jest-runtime": "^29.6.4", + "jest-util": "^29.6.3", + "jest-watcher": "^29.6.4", + "jest-worker": "^29.6.4", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-runtime": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.6.4.tgz", + "integrity": "sha512-s/QxMBLvmwLdchKEjcLfwzP7h+jsHvNEtxGP5P+Fl1FMaJX2jMiIqe4rJw4tFprzCwuSvVUo9bn0uj4gNRXsbA==", + "dev": true, + "dependencies": { + "@jest/environment": "^29.6.4", + "@jest/fake-timers": "^29.6.4", + "@jest/globals": "^29.6.4", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.6.4", + "@jest/transform": "^29.6.4", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.6.4", + "jest-message-util": "^29.6.3", + "jest-mock": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.6.4", + "jest-snapshot": "^29.6.4", + "jest-util": "^29.6.3", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-snapshot": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.6.4.tgz", + "integrity": "sha512-VC1N8ED7+4uboUKGIDsbvNAZb6LakgIPgAF4RSpF13dN6YaMokfRqO+BaqK4zIh6X3JffgwbzuGqDEjHm/MrvA==", + "dev": true, + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.6.4", + "@jest/transform": "^29.6.4", + "@jest/types": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.6.4", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.6.4", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.6.4", + "jest-message-util": "^29.6.3", + "jest-util": "^29.6.3", + "natural-compare": "^1.4.0", + "pretty-format": "^29.6.3", + "semver": "^7.5.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-util": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.6.3.tgz", + "integrity": "sha512-QUjna/xSy4B32fzcKTSz1w7YYzgiHrjjJjevdRf61HYk998R5vVMMNmrHESYZVDS5DSWs+1srPLPKxXPkeSDOA==", + "dev": true, + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.6.3.tgz", + "integrity": "sha512-e7KWZcAIX+2W1o3cHfnqpGajdCs1jSM3DkXjGeLSNmCazv1EeI1ggTeK5wdZhF+7N+g44JI2Od3veojoaumlfg==", + "dev": true, + "dependencies": { + "@jest/types": "^29.6.3", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "leven": "^3.1.0", + "pretty-format": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-watcher": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.6.4.tgz", + "integrity": "sha512-oqUWvx6+On04ShsT00Ir9T4/FvBeEh2M9PTubgITPxDa739p4hoQweWPRGyYeaojgT0xTpZKF0Y/rSY1UgMxvQ==", + "dev": true, + "dependencies": { + "@jest/test-result": "^29.6.4", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.6.3", + "string-length": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker": { + "version": "29.6.4", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.6.4.tgz", + "integrity": "sha512-6dpvFV4WjcWbDVGgHTWo/aupl8/LbBx2NSKfiwqf79xC/yeJjKHT1+StcKy/2KTmW16hE68ccKVOtXf+WZGz7Q==", + "dev": true, + "dependencies": { + "@types/node": "*", + "jest-util": "^29.6.3", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dev": true, + "dependencies": { + "tmpl": "1.0.5" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true + }, + "node_modules/node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", + "dev": true + }, + "node_modules/node-notifier": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-8.0.2.tgz", + "integrity": "sha512-oJP/9NAdd9+x2Q+rfphB2RJCHjod70RcRLjosiPMMu5gjIfwVnOUGq2nbTjTUbmy0DJ/tFIVT30+Qe3nzl4TJg==", + "dev": true, + "optional": true, + "peer": true, + "dependencies": { + "growly": "^1.3.0", + "is-wsl": "^2.2.0", + "semver": "^7.3.2", + "shellwords": "^0.1.1", + "uuid": "^8.3.0", + "which": "^2.0.2" + } + }, + "node_modules/node-releases": { + "version": "2.0.13", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz", + "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==", + "dev": true + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/object-inspect": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", + "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.entries": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.6.tgz", + "integrity": "sha512-leTPzo4Zvg3pmbQ3rDK69Rl8GQvIqMWubrkxONG9/ojtFE2rD9fjMKfSI5BxW3osRH1m6VdzmqK8oAY9aT4x5w==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.fromentries": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.6.tgz", + "integrity": "sha512-VciD13dswC4j1Xt5394WR4MzmAQmlgN72phd/riNp9vtD7tp4QQWJ0R4wvclXcafgcYK8veHRed2W6XeGBvcfg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.groupby": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.0.tgz", + "integrity": "sha512-70MWG6NfRH9GnbZOikuhPPYzpUpof9iW2J9E4dW7FXTqPNb6rllE6u39SKwwiNh8lCwX3DDb5OgcKGiEBrTTyw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.21.2", + "get-intrinsic": "^1.2.1" + } + }, + "node_modules/object.values": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.6.tgz", + "integrity": "sha512-FVVTkD1vENCsAcwNs9k6jea2uHC/X0+JcjG8YA60FN5CMaJmG95wT9jek/xX9nornqGRrBkKtzuAu2wuHpKqvw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/optionator": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.3.tgz", + "integrity": "sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==", + "dev": true, + "dependencies": { + "@aashutoshrathi/word-wrap": "^1.2.3", + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", + "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/pretty-format": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.6.3.tgz", + "integrity": "sha512-ZsBgjVhFAj5KeK+nHfF1305/By3lechHQSMWCTl8iHSbfOm2TN5nHEtFc/+W7fAyUeCs2n5iow72gld4gW0xDw==", + "dev": true, + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/punycode": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", + "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/pure-rand": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.2.tgz", + "integrity": "sha512-6Yg0ekpKICSjPswYOuC5sku/TSWaRYlA0qsXqJgM/d/4pLPHPuTxK7Nbf7jFKzAeedUhR8C7K9Uv63FBsSo8xQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ] + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.0.tgz", + "integrity": "sha512-0SutC3pNudRKgquxGoRGIz946MZVHqbNfPjBdxeOhBrdgDKlRoXmYLQN9xRbrR09ZXWeGAdPuif7egofn6v5LA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "functions-have-names": "^1.2.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.4", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.4.tgz", + "integrity": "sha512-PXNdCiPqDqeUou+w1C2eTQbNfxKSuMxqTCuvlmmMsk1NWHL5fRrhY6Pl0qEYYc6+QqGClco1Qj8XnjPego4wfg==", + "dev": true, + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-cwd/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve.exports": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz", + "integrity": "sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "dev": true, + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-array-concat": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.0.0.tgz", + "integrity": "sha512-9dVEFruWIsnie89yym+xWTAYASdpw3CJV7Li/6zBewGf9z2i1j31rP6jnY0pHEO4QZh6N0K11bFjWmdR8UGdPQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.0", + "has-symbols": "^1.0.3", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.0.tgz", + "integrity": "sha512-JBUUzyOgEwXQY1NuPtvcj/qcBDbDmEvWufhlnXZIm75DEHp+afM1r1ujJpJsV/gSM4t59tpDyPi1sd6ZaPFfsA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-regex": "^1.1.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/shellwords": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz", + "integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==", + "dev": true, + "optional": true, + "peer": true + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/stack-utils/node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "dev": true, + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.7.tgz", + "integrity": "sha512-p6TmeT1T3411M8Cgg9wBTMRtY2q9+PNy9EV1i2lIXUN/btt763oIfxwN3RR8VU6wHX8j/1CFy0L+YuThm6bgOg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.6.tgz", + "integrity": "sha512-JySq+4mrPf9EsDBEDYMOb/lM7XQLulwg5R/m1r0PXEFqrV0qHvl58sdTilSXtKOflCsK2E8jxf+GKC0T07RWwQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.6.tgz", + "integrity": "sha512-omqjMDaY92pbn5HOX7f9IccLA+U1tA9GvtU4JrodiXFfYB7jPzzHpRzpglLAjtUV6bB557zwClJezTqnAiYnQA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", + "dev": true + }, + "node_modules/tmpl": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", + "dev": true + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tsconfig-paths": { + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.14.2.tgz", + "integrity": "sha512-o/9iXgCYc5L/JxCHPe3Hvh8Q/2xm5Z+p18PESBU6Ff33695QnCHBEjcytY2q19ua7Mbl/DavtBOLq+oG0RCL+g==", + "dev": true, + "dependencies": { + "@types/json5": "^0.0.29", + "json5": "^1.0.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + } + }, + "node_modules/tsconfig-paths/node_modules/json5": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "dev": true, + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/tsconfig-paths/node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.0.tgz", + "integrity": "sha512-Y8KTSIglk9OZEr8zywiIHG/kmQ7KWyjseXs1CbSo8vC42w7hg2HgYTxSWwP0+is7bWDc1H+Fo026CpHFwm8tkw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.1", + "is-typed-array": "^1.1.10" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.0.tgz", + "integrity": "sha512-Or/+kvLxNpeQ9DtSydonMxCx+9ZXOswtwJn17SNLvhptaXYDJvkFFP5zbfU/uLmvnBJlI4yrnXRxpdWH/M5tNA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "has-proto": "^1.0.1", + "is-typed-array": "^1.1.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.0.tgz", + "integrity": "sha512-RD97prjEt9EL8YgAgpOkf3O4IF9lhJFr9g0htQkm0rchFp/Vx7LW5Q8fSXXub7BXAODyUQohRMyOc3faCPd0hg==", + "dev": true, + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "has-proto": "^1.0.1", + "is-typed-array": "^1.1.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.4.tgz", + "integrity": "sha512-KjZypGq+I/H7HI5HlOoGHkWUUGq+Q0TPhQurLbyrVrvnKTBgzLhIJ7j6J/XTQOi0d1RjyZ0wdas8bKs2p0x3Ng==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "is-typed-array": "^1.1.9" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/unbox-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", + "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-bigints": "^1.0.2", + "has-symbols": "^1.0.3", + "which-boxed-primitive": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.11.tgz", + "integrity": "sha512-dCwEFf0/oT85M1fHBg4F0jtLwJrutGoHSQXCh7u4o2t1drG+c0a9Flnqww6XUKSfQMPpJBRjU8d4RXB09qtvaA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "optional": true, + "peer": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/v8-to-istanbul": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.0.tgz", + "integrity": "sha512-6z3GW9x8G1gd+JIIgQQQxXuiJtCXeAjp6RaPEPLv62mH3iPHPxV6W3robxtCzNErRo6ZwTmzWhsbNvjyEBKzKA==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^1.6.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, + "node_modules/v8-to-istanbul/node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", + "dev": true + }, + "node_modules/walker": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", + "dev": true, + "dependencies": { + "makeerror": "1.0.12" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.11.tgz", + "integrity": "sha512-qe9UWWpkeG5yzZ0tNYxDmd7vo58HDBc39mZ0xWWpolAGADdFOzkfamWLDxkOWcvHQKVmdTyQdLD4NOfjLWTKew==", + "dev": true, + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "node_modules/write-file-atomic": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", + "dev": true, + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dev": true, + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/node_modules/@aashutoshrathi/word-wrap/LICENSE b/node_modules/@aashutoshrathi/word-wrap/LICENSE new file mode 100644 index 0000000..842218c --- /dev/null +++ b/node_modules/@aashutoshrathi/word-wrap/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2016, Jon Schlinkert + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@aashutoshrathi/word-wrap/README.md b/node_modules/@aashutoshrathi/word-wrap/README.md new file mode 100644 index 0000000..3abb882 --- /dev/null +++ b/node_modules/@aashutoshrathi/word-wrap/README.md @@ -0,0 +1,182 @@ +# word-wrap [![NPM version](https://img.shields.io/npm/v/word-wrap.svg?style=flat)](https://www.npmjs.com/package/word-wrap) [![NPM monthly downloads](https://img.shields.io/npm/dm/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![NPM total downloads](https://img.shields.io/npm/dt/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/word-wrap.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/word-wrap) + +> Wrap words to a specified length. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save word-wrap +``` + +## Usage + +```js +var wrap = require('word-wrap'); + +wrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); +``` + +Results in: + +``` + Lorem ipsum dolor sit amet, consectetur adipiscing + elit, sed do eiusmod tempor incididunt ut labore + et dolore magna aliqua. Ut enim ad minim veniam, + quis nostrud exercitation ullamco laboris nisi ut + aliquip ex ea commodo consequat. +``` + +## Options + +![image](https://cloud.githubusercontent.com/assets/383994/6543728/7a381c08-c4f6-11e4-8b7d-b6ba197569c9.png) + +### options.width + +Type: `Number` + +Default: `50` + +The width of the text before wrapping to a new line. + +**Example:** + +```js +wrap(str, {width: 60}); +``` + +### options.indent + +Type: `String` + +Default: `` (none) + +The string to use at the beginning of each line. + +**Example:** + +```js +wrap(str, {indent: ' '}); +``` + +### options.newline + +Type: `String` + +Default: `\n` + +The string to use at the end of each line. + +**Example:** + +```js +wrap(str, {newline: '\n\n'}); +``` + +### options.escape + +Type: `function` + +Default: `function(str){return str;}` + +An escape function to run on each line after splitting them. + +**Example:** + +```js +var xmlescape = require('xml-escape'); +wrap(str, { + escape: function(string){ + return xmlescape(string); + } +}); +``` + +### options.trim + +Type: `Boolean` + +Default: `false` + +Trim trailing whitespace from the returned string. This option is included since `.trim()` would also strip the leading indentation from the first line. + +**Example:** + +```js +wrap(str, {trim: true}); +``` + +### options.cut + +Type: `Boolean` + +Default: `false` + +Break a word between any two letters when the word is longer than the specified width. + +**Example:** + +```js +wrap(str, {cut: true}); +``` + +## About + +### Related projects + +* [common-words](https://www.npmjs.com/package/common-words): Updated list (JSON) of the 100 most common words in the English language. Useful for… [more](https://github.com/jonschlinkert/common-words) | [homepage](https://github.com/jonschlinkert/common-words "Updated list (JSON) of the 100 most common words in the English language. Useful for excluding these words from arrays.") +* [shuffle-words](https://www.npmjs.com/package/shuffle-words): Shuffle the words in a string and optionally the letters in each word using the… [more](https://github.com/jonschlinkert/shuffle-words) | [homepage](https://github.com/jonschlinkert/shuffle-words "Shuffle the words in a string and optionally the letters in each word using the Fisher-Yates algorithm. Useful for creating test fixtures, benchmarking samples, etc.") +* [unique-words](https://www.npmjs.com/package/unique-words): Return the unique words in a string or array. | [homepage](https://github.com/jonschlinkert/unique-words "Return the unique words in a string or array.") +* [wordcount](https://www.npmjs.com/package/wordcount): Count the words in a string. Support for english, CJK and Cyrillic. | [homepage](https://github.com/jonschlinkert/wordcount "Count the words in a string. Support for english, CJK and Cyrillic.") + +### Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 43 | [jonschlinkert](https://github.com/jonschlinkert) | +| 2 | [lordvlad](https://github.com/lordvlad) | +| 2 | [hildjj](https://github.com/hildjj) | +| 1 | [danilosampaio](https://github.com/danilosampaio) | +| 1 | [2fd](https://github.com/2fd) | +| 1 | [toddself](https://github.com/toddself) | +| 1 | [wolfgang42](https://github.com/wolfgang42) | +| 1 | [zachhale](https://github.com/zachhale) | + +### Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +### Running tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +### Author + +**Jon Schlinkert** + +* [github/jonschlinkert](https://github.com/jonschlinkert) +* [twitter/jonschlinkert](https://twitter.com/jonschlinkert) + +### License + +Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 02, 2017._ diff --git a/node_modules/@aashutoshrathi/word-wrap/index.d.ts b/node_modules/@aashutoshrathi/word-wrap/index.d.ts new file mode 100644 index 0000000..1acd425 --- /dev/null +++ b/node_modules/@aashutoshrathi/word-wrap/index.d.ts @@ -0,0 +1,50 @@ +/** + * Wrap words to a specified length. + */ +export = wrap; + +declare function wrap(str: string, options?: wrap.IOptions): string; + +declare namespace wrap { + export interface IOptions { + + /** + * The width of the text before wrapping to a new line. + * @default ´50´ + */ + width?: number; + + /** + * The string to use at the beginning of each line. + * @default ´´ (none) + */ + indent?: string; + + /** + * The string to use at the end of each line. + * @default ´\n´ + */ + newline?: string; + + /** + * An escape function to run on each line after splitting them. + * @default (str: string) => string; + */ + escape?: (str: string) => string; + + /** + * Trim trailing whitespace from the returned string. + * This option is included since .trim() would also strip + * the leading indentation from the first line. + * @default true + */ + trim?: boolean; + + /** + * Break a word between any two letters when the word is longer + * than the specified width. + * @default false + */ + cut?: boolean; + } +} diff --git a/node_modules/@aashutoshrathi/word-wrap/index.js b/node_modules/@aashutoshrathi/word-wrap/index.js new file mode 100644 index 0000000..461a17c --- /dev/null +++ b/node_modules/@aashutoshrathi/word-wrap/index.js @@ -0,0 +1,52 @@ +/*! + * word-wrap + * + * Copyright (c) 2014-2023, Jon Schlinkert. + * Released under the MIT License. + */ + +function trimTabAndSpaces(str) { + const lines = str.split('\n'); + const trimmedLines = lines.map((line) => line.trimEnd()); + return trimmedLines.join('\n'); +} + +module.exports = function(str, options) { + options = options || {}; + if (str == null) { + return str; + } + + var width = options.width || 50; + var indent = (typeof options.indent === 'string') + ? options.indent + : ''; + + var newline = options.newline || '\n' + indent; + var escape = typeof options.escape === 'function' + ? options.escape + : identity; + + var regexString = '.{1,' + width + '}'; + if (options.cut !== true) { + regexString += '([\\s\u200B]+|$)|[^\\s\u200B]+?([\\s\u200B]+|$)'; + } + + var re = new RegExp(regexString, 'g'); + var lines = str.match(re) || []; + var result = indent + lines.map(function(line) { + if (line.slice(-1) === '\n') { + line = line.slice(0, line.length - 1); + } + return escape(line); + }).join(newline); + + if (options.trim === true) { + result = trimTabAndSpaces(result); + } + return result; +}; + +function identity(str) { + return str; +} diff --git a/node_modules/@aashutoshrathi/word-wrap/package.json b/node_modules/@aashutoshrathi/word-wrap/package.json new file mode 100644 index 0000000..e33e077 --- /dev/null +++ b/node_modules/@aashutoshrathi/word-wrap/package.json @@ -0,0 +1,81 @@ +{ + "name": "@aashutoshrathi/word-wrap", + "description": "Wrap words to a specified length.", + "version": "1.2.6", + "homepage": "https://github.com/aashutoshrathi/word-wrap", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Aashutosh Rathi ", + "Danilo Sampaio (localhost:8080)", + "Fede Ramirez (https://2fd.github.io)", + "Joe Hildebrand (https://twitter.com/hildjj)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Todd Kennedy (https://tck.io)", + "Waldemar Reusch (https://github.com/lordvlad)", + "Wolfgang Faust (http://www.linestarve.com)", + "Zach Hale (http://zachhale.com)" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/aashutoshrathi/word-wrap.git" + }, + "bugs": { + "url": "https://github.com/aashutoshrathi/word-wrap/issues" + }, + "license": "MIT", + "files": [ + "index.js", + "index.d.ts" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "gulp-format-md": "^0.1.11", + "mocha": "^10.2.0" + }, + "keywords": [ + "break", + "carriage", + "line", + "new-line", + "newline", + "return", + "soft", + "text", + "word", + "word-wrap", + "words", + "wrap" + ], + "typings": "index.d.ts", + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "common-words", + "shuffle-words", + "unique-words", + "wordcount" + ] + }, + "reflinks": [ + "verb", + "verb-generate-readme" + ] + } +} diff --git a/node_modules/@ampproject/remapping/LICENSE b/node_modules/@ampproject/remapping/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@ampproject/remapping/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@ampproject/remapping/README.md b/node_modules/@ampproject/remapping/README.md new file mode 100644 index 0000000..1463c9f --- /dev/null +++ b/node_modules/@ampproject/remapping/README.md @@ -0,0 +1,218 @@ +# @ampproject/remapping + +> Remap sequential sourcemaps through transformations to point at the original source code + +Remapping allows you to take the sourcemaps generated through transforming your code and "remap" +them to the original source locations. Think "my minified code, transformed with babel and bundled +with webpack", all pointing to the correct location in your original source code. + +With remapping, none of your source code transformations need to be aware of the input's sourcemap, +they only need to generate an output sourcemap. This greatly simplifies building custom +transformations (think a find-and-replace). + +## Installation + +```sh +npm install @ampproject/remapping +``` + +## Usage + +```typescript +function remapping( + map: SourceMap | SourceMap[], + loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined), + options?: { excludeContent: boolean, decodedMappings: boolean } +): SourceMap; + +// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the +// "source" location (where child sources are resolved relative to, or the location of original +// source), and the ability to override the "content" of an original source for inclusion in the +// output sourcemap. +type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +} +``` + +`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer +in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents +a transformed file (it has a sourcmap associated with it), then the `loader` should return that +sourcemap. If not, the path will be treated as an original, untransformed source code. + +```js +// Babel transformed "helloworld.js" into "transformed.js" +const transformedMap = JSON.stringify({ + file: 'transformed.js', + // 1st column of 2nd line of output file translates into the 1st source + // file, line 3, column 2 + mappings: ';CAEE', + sources: ['helloworld.js'], + version: 3, +}); + +// Uglify minified "transformed.js" into "transformed.min.js" +const minifiedTransformedMap = JSON.stringify({ + file: 'transformed.min.js', + // 0th column of 1st line of output file translates into the 1st source + // file, line 2, column 1. + mappings: 'AACC', + names: [], + sources: ['transformed.js'], + version: 3, +}); + +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + // The "transformed.js" file is an transformed file. + if (file === 'transformed.js') { + // The root importer is empty. + console.assert(ctx.importer === ''); + // The depth in the sourcemap tree we're currently loading. + // The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc. + console.assert(ctx.depth === 1); + + return transformedMap; + } + + // Loader will be called to load transformedMap's source file pointers as well. + console.assert(file === 'helloworld.js'); + // `transformed.js`'s sourcemap points into `helloworld.js`. + console.assert(ctx.importer === 'transformed.js'); + // This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`. + console.assert(ctx.depth === 2); + return null; + } +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +In this example, `loader` will be called twice: + +1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the + associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can + be traced through it into the source files it represents. +2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so + we return `null`. + +The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If +you were to read the `mappings`, it says "0th column of the first line output line points to the 1st +column of the 2nd line of the file `helloworld.js`". + +### Multiple transformations of a file + +As a convenience, if you have multiple single-source transformations of a file, you may pass an +array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this +changes the `importer` and `depth` of each call to our loader. So our above example could have been +written as: + +```js +const remapped = remapping( + [minifiedTransformedMap, transformedMap], + () => null +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +### Advanced control of the loading graph + +#### `source` + +The `source` property can overridden to any value to change the location of the current load. Eg, +for an original source file, it allows us to change the location to the original source regardless +of what the sourcemap source entry says. And for transformed files, it allows us to change the +relative resolving location for child sources of the loaded sourcemap. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // We pretend the transformed.js file actually exists in the 'src/' directory. When the nested + // source files are loaded, they will now be relative to `src/`. + ctx.source = 'src/transformed.js'; + return transformedMap; + } + + console.assert(file === 'src/helloworld.js'); + // We could futher change the source of this original file, eg, to be inside a nested directory + // itself. This will be reflected in the remapped sourcemap. + ctx.source = 'src/nested/transformed.js'; + return null; + } +); + +console.log(remapped); +// { +// …, +// sources: ['src/nested/helloworld.js'], +// }; +``` + + +#### `content` + +The `content` property can be overridden when we encounter an original source file. Eg, this allows +you to manually provide the source content of the original file regardless of whether the +`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove +the source content. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap + // would not include any `sourcesContent` values. + return transformedMap; + } + + console.assert(file === 'helloworld.js'); + // We can read the file to provide the source content. + ctx.content = fs.readFileSync(file, 'utf8'); + return null; + } +); + +console.log(remapped); +// { +// …, +// sourcesContent: [ +// 'console.log("Hello world!")', +// ], +// }; +``` + +### Options + +#### excludeContent + +By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the +`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce +the size out the sourcemap. + +#### decodedMappings + +By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the +`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of +encoding into a VLQ string. diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs b/node_modules/@ampproject/remapping/dist/remapping.mjs new file mode 100644 index 0000000..b5edded --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs @@ -0,0 +1,191 @@ +import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping'; +import { GenMapping, maybeAddSegment, setSourceContent, toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping'; + +const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); +const EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content) { + return { source, line, column, name, content }; +} +function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source } = traced; + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + setSourceContent(gen, source, content); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content); + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +export { remapping as default }; +//# sourceMappingURL=remapping.mjs.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs.map b/node_modules/@ampproject/remapping/dist/remapping.mjs.map new file mode 100644 index 0000000..078a2b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.mjs","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null\n): SourceMapSegmentObject {\n return { source, line, column, name, content };\n}\n\nfunction Source(map: TraceMap, sources: Sources[], source: '', content: null): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(source: string, content: string | null): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n return OriginalSource(source, sourceContent);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":[],"mappings":";;;AA6BA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AAC/E,MAAM,aAAa,GAAc,EAAE,CAAC;AAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAY,EACZ,OAAsB,EAAA;IAEtB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AACjD,CAAC;AASD,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAmB,EACnB,OAAsB,EAAA;IAEtB,OAAO;QACL,GAAG;QACH,OAAO;QACP,MAAM;QACN,OAAO;KACD,CAAC;AACX,CAAC;AAED;;;AAGG;AACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;IACzD,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC;AAED;;;AAGG;AACa,SAAA,cAAc,CAAC,MAAc,EAAE,OAAsB,EAAA;IACnE,OAAO,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACtD,CAAC;AAED;;;AAGG;AACG,SAAU,aAAa,CAAC,IAAe,EAAA;;;AAG3C,IAAA,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IACpD,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC3C,IAAA,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC;AAC5B,IAAA,MAAM,YAAY,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;AAE1C,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC5C,QAAA,MAAM,QAAQ,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;AAEjC,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACxC,YAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC5B,YAAA,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YAC1B,IAAI,MAAM,GAAkC,kBAAkB,CAAC;;;AAI/D,YAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;gBACxB,MAAM,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AACvC,gBAAA,MAAM,GAAG,mBAAmB,CAC1B,MAAM,EACN,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAClD,CAAC;;;gBAIF,IAAI,MAAM,IAAI,IAAI;oBAAE,SAAS;AAC9B,aAAA;AAED,YAAA,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;AAEvD,YAAA,eAAe,CAAC,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;AAC5D,YAAA,IAAI,MAAM,IAAI,OAAO,IAAI,IAAI;AAAE,gBAAA,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACvE,SAAA;AACF,KAAA;AAED,IAAA,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;;AAGG;AACG,SAAU,mBAAmB,CACjC,MAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAY,EAAA;AAEZ,IAAA,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;AACf,QAAA,OAAO,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;AACzE,KAAA;AAED,IAAA,MAAM,OAAO,GAAG,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;;IAGvD,IAAI,OAAO,IAAI,IAAI;AAAE,QAAA,OAAO,IAAI,CAAC;;;AAGjC,IAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;AAAE,QAAA,OAAO,kBAAkB,CAAC;IAEpD,OAAO,mBAAmB,CACxB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAC1B,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAC3D,CAAC;AACJ;;AClJA,SAAS,OAAO,CAAI,KAAc,EAAA;AAChC,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK,CAAC;IACvC,OAAO,CAAC,KAAK,CAAC,CAAC;AACjB,CAAC;AAED;;;;;;;;;;AAUG;AACW,SAAU,kBAAkB,CACxC,KAAwC,EACxC,MAAuB,EAAA;IAEvB,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5D,IAAA,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAG,CAAC;AAExB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACpC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;AAC9B,YAAA,MAAM,IAAI,KAAK,CACb,CAAA,mBAAA,EAAsB,CAAC,CAAuC,qCAAA,CAAA;AAC5D,gBAAA,uEAAuE,CAC1E,CAAC;AACH,SAAA;AACF,KAAA;AAED,IAAA,IAAI,IAAI,GAAG,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;AACrC,IAAA,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;AACzC,QAAA,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AACnC,KAAA;AACD,IAAA,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,KAAK,CACZ,GAAa,EACb,MAAuB,EACvB,QAAgB,EAChB,aAAqB,EAAA;AAErB,IAAA,MAAM,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,GAAG,CAAC;AAEhD,IAAA,MAAM,KAAK,GAAG,aAAa,GAAG,CAAC,CAAC;IAChC,MAAM,QAAQ,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,UAAyB,EAAE,CAAS,KAAa;;;;;AAKrF,QAAA,MAAM,GAAG,GAAkB;YACzB,QAAQ;YACR,KAAK;YACL,MAAM,EAAE,UAAU,IAAI,EAAE;AACxB,YAAA,OAAO,EAAE,SAAS;SACnB,CAAC;;;QAIF,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAE1C,QAAA,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC;;AAGhC,QAAA,IAAI,SAAS;AAAE,YAAA,OAAO,KAAK,CAAC,IAAI,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;;;;;QAMpF,MAAM,aAAa,GACjB,OAAO,KAAK,SAAS,GAAG,OAAO,GAAG,cAAc,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;AAC9E,QAAA,OAAO,cAAc,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;AAC/C,KAAC,CAAC,CAAC;AAEH,IAAA,OAAO,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;AAClC;;ACjFA;;;AAGG;AACW,MAAO,SAAS,CAAA;IAS5B,WAAY,CAAA,GAAe,EAAE,OAAgB,EAAA;AAC3C,QAAA,MAAM,GAAG,GAAG,OAAO,CAAC,eAAe,GAAG,YAAY,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;QAC5E,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;AAC3B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;AACrB,QAAA,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAiC,CAAC;AACtD,QAAA,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,KAA2B,CAAC;AAE7C,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;AAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;AACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;AAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;AACzE,SAAA;KACF;IAED,QAAQ,GAAA;AACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;KAC7B;AACF;;ACpBD;;;;;;;;;;;;;;AAcG;AACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;IAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;IAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClD;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js b/node_modules/@ampproject/remapping/dist/remapping.umd.js new file mode 100644 index 0000000..e292d4c --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js @@ -0,0 +1,196 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@jridgewell/trace-mapping'), require('@jridgewell/gen-mapping')) : + typeof define === 'function' && define.amd ? define(['@jridgewell/trace-mapping', '@jridgewell/gen-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remapping = factory(global.traceMapping, global.genMapping)); +})(this, (function (traceMapping, genMapping) { 'use strict'; + + const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); + const EMPTY_SOURCES = []; + function SegmentObject(source, line, column, name, content) { + return { source, line, column, name, content }; + } + function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; + } + /** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ + function MapSource(map, sources) { + return Source(map, sources, '', null); + } + /** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ + function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); + } + /** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ + function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new genMapping.GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = traceMapping.decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source } = traced; + genMapping.maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + genMapping.setSourceContent(gen, source, content); + } + } + return gen; + } + /** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ + function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content); + } + const segment = traceMapping.traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); + } + + function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; + } + /** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ + function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new traceMapping.TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; + } + function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new traceMapping.TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); + } + + /** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ + class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? genMapping.toDecodedMap(map) : genMapping.toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } + } + + /** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ + function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); + } + + return remapping; + +})); +//# sourceMappingURL=remapping.umd.js.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js.map b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map new file mode 100644 index 0000000..9c89888 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.umd.js","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null\n): SourceMapSegmentObject {\n return { source, line, column, name, content };\n}\n\nfunction Source(map: TraceMap, sources: Sources[], source: '', content: null): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(source: string, content: string | null): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n return OriginalSource(source, sourceContent);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":["GenMapping","decodedMappings","maybeAddSegment","setSourceContent","traceSegment","TraceMap","toDecodedMap","toEncodedMap"],"mappings":";;;;;;IA6BA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IAC/E,MAAM,aAAa,GAAc,EAAE,CAAC;IAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAY,EACZ,OAAsB,EAAA;QAEtB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IACjD,CAAC;IASD,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAmB,EACnB,OAAsB,EAAA;QAEtB,OAAO;YACL,GAAG;YACH,OAAO;YACP,MAAM;YACN,OAAO;SACD,CAAC;IACX,CAAC;IAED;;;IAGG;IACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;QACzD,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IACxC,CAAC;IAED;;;IAGG;IACa,SAAA,cAAc,CAAC,MAAc,EAAE,OAAsB,EAAA;QACnE,OAAO,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED;;;IAGG;IACG,SAAU,aAAa,CAAC,IAAe,EAAA;;;IAG3C,IAAA,MAAM,GAAG,GAAG,IAAIA,qBAAU,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QACpD,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAC3C,IAAA,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC;IAC5B,IAAA,MAAM,YAAY,GAAGC,4BAAe,CAAC,GAAG,CAAC,CAAC;IAE1C,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IAC5C,QAAA,MAAM,QAAQ,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;IAEjC,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACxC,YAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC5B,YAAA,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;gBAC1B,IAAI,MAAM,GAAkC,kBAAkB,CAAC;;;IAI/D,YAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;oBACxB,MAAM,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACvC,gBAAA,MAAM,GAAG,mBAAmB,CAC1B,MAAM,EACN,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAClD,CAAC;;;oBAIF,IAAI,MAAM,IAAI,IAAI;wBAAE,SAAS;IAC9B,aAAA;IAED,YAAA,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IAEvD,YAAAC,0BAAe,CAAC,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAC5D,YAAA,IAAI,MAAM,IAAI,OAAO,IAAI,IAAI;IAAE,gBAAAC,2BAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACvE,SAAA;IACF,KAAA;IAED,IAAA,OAAO,GAAG,CAAC;IACb,CAAC;IAED;;;IAGG;IACG,SAAU,mBAAmB,CACjC,MAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAY,EAAA;IAEZ,IAAA,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;IACf,QAAA,OAAO,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IACzE,KAAA;IAED,IAAA,MAAM,OAAO,GAAGC,yBAAY,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;;QAGvD,IAAI,OAAO,IAAI,IAAI;IAAE,QAAA,OAAO,IAAI,CAAC;;;IAGjC,IAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;IAAE,QAAA,OAAO,kBAAkB,CAAC;QAEpD,OAAO,mBAAmB,CACxB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAC1B,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAC3D,CAAC;IACJ;;IClJA,SAAS,OAAO,CAAI,KAAc,EAAA;IAChC,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;IAAE,QAAA,OAAO,KAAK,CAAC;QACvC,OAAO,CAAC,KAAK,CAAC,CAAC;IACjB,CAAC;IAED;;;;;;;;;;IAUG;IACW,SAAU,kBAAkB,CACxC,KAAwC,EACxC,MAAuB,EAAA;QAEvB,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,IAAIC,qBAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IAC5D,IAAA,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAG,CAAC;IAExB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;IAC9B,YAAA,MAAM,IAAI,KAAK,CACb,CAAA,mBAAA,EAAsB,CAAC,CAAuC,qCAAA,CAAA;IAC5D,gBAAA,uEAAuE,CAC1E,CAAC;IACH,SAAA;IACF,KAAA;IAED,IAAA,IAAI,IAAI,GAAG,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;IACrC,IAAA,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;IACzC,QAAA,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;IACnC,KAAA;IACD,IAAA,OAAO,IAAI,CAAC;IACd,CAAC;IAED,SAAS,KAAK,CACZ,GAAa,EACb,MAAuB,EACvB,QAAgB,EAChB,aAAqB,EAAA;IAErB,IAAA,MAAM,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,GAAG,CAAC;IAEhD,IAAA,MAAM,KAAK,GAAG,aAAa,GAAG,CAAC,CAAC;QAChC,MAAM,QAAQ,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,UAAyB,EAAE,CAAS,KAAa;;;;;IAKrF,QAAA,MAAM,GAAG,GAAkB;gBACzB,QAAQ;gBACR,KAAK;gBACL,MAAM,EAAE,UAAU,IAAI,EAAE;IACxB,YAAA,OAAO,EAAE,SAAS;aACnB,CAAC;;;YAIF,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAE1C,QAAA,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC;;IAGhC,QAAA,IAAI,SAAS;IAAE,YAAA,OAAO,KAAK,CAAC,IAAIA,qBAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;;;;;YAMpF,MAAM,aAAa,GACjB,OAAO,KAAK,SAAS,GAAG,OAAO,GAAG,cAAc,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAC9E,QAAA,OAAO,cAAc,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC/C,KAAC,CAAC,CAAC;IAEH,IAAA,OAAO,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAClC;;ICjFA;;;IAGG;IACW,MAAO,SAAS,CAAA;QAS5B,WAAY,CAAA,GAAe,EAAE,OAAgB,EAAA;IAC3C,QAAA,MAAM,GAAG,GAAG,OAAO,CAAC,eAAe,GAAGC,uBAAY,CAAC,GAAG,CAAC,GAAGC,uBAAY,CAAC,GAAG,CAAC,CAAC;YAC5E,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;IAC3B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IACrB,QAAA,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAiC,CAAC;IACtD,QAAA,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,KAA2B,CAAC;IAE7C,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;IACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;IAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;IACzE,SAAA;SACF;QAED,QAAQ,GAAA;IACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SAC7B;IACF;;ICpBD;;;;;;;;;;;;;;IAcG;IACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;QAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;QAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAClD;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts new file mode 100644 index 0000000..f87fcea --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts @@ -0,0 +1,14 @@ +import type { MapSource as MapSourceType } from './source-map-tree'; +import type { SourceMapInput, SourceMapLoader } from './types'; +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; diff --git a/node_modules/@ampproject/remapping/dist/types/remapping.d.ts b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts new file mode 100644 index 0000000..0b58ea9 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts @@ -0,0 +1,19 @@ +import SourceMap from './source-map'; +import type { SourceMapInput, SourceMapLoader, Options } from './types'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types'; +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts new file mode 100644 index 0000000..3a9f7af --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts @@ -0,0 +1,42 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export declare type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; +}; +export declare type OriginalSource = { + map: null; + sources: Sources[]; + source: string; + content: string | null; +}; +export declare type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: null; +}; +export declare type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts new file mode 100644 index 0000000..ef999b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts @@ -0,0 +1,17 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + constructor(map: GenMapping, options: Options); + toString(): string; +} diff --git a/node_modules/@ampproject/remapping/dist/types/types.d.ts b/node_modules/@ampproject/remapping/dist/types/types.d.ts new file mode 100644 index 0000000..730a963 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/types.d.ts @@ -0,0 +1,14 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export declare type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +}; +export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export declare type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; diff --git a/node_modules/@ampproject/remapping/package.json b/node_modules/@ampproject/remapping/package.json new file mode 100644 index 0000000..bf3dad2 --- /dev/null +++ b/node_modules/@ampproject/remapping/package.json @@ -0,0 +1,75 @@ +{ + "name": "@ampproject/remapping", + "version": "2.2.1", + "description": "Remap sequential sourcemaps through transformations to point at the original source code", + "keywords": [ + "source", + "map", + "remap" + ], + "main": "dist/remapping.umd.js", + "module": "dist/remapping.mjs", + "types": "dist/types/remapping.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/remapping.d.ts", + "browser": "./dist/remapping.umd.js", + "require": "./dist/remapping.umd.js", + "import": "./dist/remapping.mjs" + }, + "./dist/remapping.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/ampproject/remapping.git" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "jest --coverage", + "test:watch": "jest --coverage --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/jest": "27.4.1", + "@typescript-eslint/eslint-plugin": "5.20.0", + "@typescript-eslint/parser": "5.20.0", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "jest": "27.5.1", + "jest-config": "27.5.1", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "ts-jest": "27.1.4", + "tslib": "2.4.0", + "typescript": "4.6.3" + }, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + } +} diff --git a/node_modules/@babel/code-frame/LICENSE b/node_modules/@babel/code-frame/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/code-frame/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/code-frame/README.md b/node_modules/@babel/code-frame/README.md new file mode 100644 index 0000000..7160755 --- /dev/null +++ b/node_modules/@babel/code-frame/README.md @@ -0,0 +1,19 @@ +# @babel/code-frame + +> Generate errors that contain a code frame that point to source locations. + +See our website [@babel/code-frame](https://babeljs.io/docs/babel-code-frame) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/code-frame +``` + +or using yarn: + +```sh +yarn add @babel/code-frame --dev +``` diff --git a/node_modules/@babel/code-frame/lib/index.js b/node_modules/@babel/code-frame/lib/index.js new file mode 100644 index 0000000..2f900eb --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js @@ -0,0 +1,157 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.codeFrameColumns = codeFrameColumns; +exports.default = _default; +var _highlight = require("@babel/highlight"); +var _chalk = _interopRequireWildcard(require("chalk"), true); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +let chalkWithForcedColor = undefined; +function getChalk(forceColor) { + if (forceColor) { + var _chalkWithForcedColor; + (_chalkWithForcedColor = chalkWithForcedColor) != null ? _chalkWithForcedColor : chalkWithForcedColor = new _chalk.default.constructor({ + enabled: true, + level: 1 + }); + return chalkWithForcedColor; + } + return _chalk.default; +} +let deprecationWarningShown = false; +function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; +} +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; +function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + if (startLine === -1) { + start = 0; + } + if (endLine === -1) { + end = source.length; + } + const lineDiff = endLine - startLine; + const markerLines = {}; + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + return { + start, + end, + markerLines + }; +} +function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const chalk = getChalk(opts.forceColor); + const defs = getDefs(chalk); + const maybeHighlight = (chalkFn, string) => { + return highlighted ? chalkFn(string) : string; + }; + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} |`; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + if (hasMarker) { + let markerLine = ""; + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } +} +function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); +} + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/code-frame/lib/index.js.map b/node_modules/@babel/code-frame/lib/index.js.map new file mode 100644 index 0000000..0882e00 --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_highlight","require","_chalk","_interopRequireWildcard","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","chalkWithForcedColor","undefined","getChalk","forceColor","_chalkWithForcedColor","chalk","constructor","enabled","level","deprecationWarningShown","getDefs","gutter","grey","marker","red","bold","message","NEWLINE","getMarkerLines","loc","source","opts","startLoc","assign","column","line","start","endLoc","end","linesAbove","linesBelow","startLine","startColumn","endLine","endColumn","Math","max","min","length","lineDiff","markerLines","lineNumber","sourceLength","codeFrameColumns","rawLines","highlighted","highlightCode","shouldHighlight","defs","maybeHighlight","chalkFn","string","lines","split","hasColumns","numberMaxWidth","String","highlightedLines","highlight","frame","slice","map","index","number","paddedNumber","hasMarker","lastMarkerLine","markerLine","Array","isArray","markerSpacing","replace","numberOfMarkers","repeat","join","reset","_default","colNumber","process","emitWarning","deprecationError","Error","name","console","warn","location"],"sources":["../src/index.ts"],"sourcesContent":["import highlight, { shouldHighlight } from \"@babel/highlight\";\n\nimport chalk, { Chalk as ChalkClass, type ChalkInstance as Chalk } from \"chalk\";\n\nlet chalkWithForcedColor: Chalk = undefined;\nfunction getChalk(forceColor: boolean) {\n if (forceColor) {\n chalkWithForcedColor ??= process.env.BABEL_8_BREAKING\n ? new ChalkClass({ level: 1 })\n : // @ts-expect-error .Instance was .constructor in chalk 2\n new chalk.constructor({ enabled: true, level: 1 });\n return chalkWithForcedColor;\n }\n return chalk;\n}\n\nlet deprecationWarningShown = false;\n\ntype Location = {\n column: number;\n line: number;\n};\n\ntype NodeLocation = {\n end?: Location;\n start: Location;\n};\n\nexport interface Options {\n /** Syntax highlight the code as JavaScript for terminals. default: false */\n highlightCode?: boolean;\n /** The number of lines to show above the error. default: 2 */\n linesAbove?: number;\n /** The number of lines to show below the error. default: 3 */\n linesBelow?: number;\n /**\n * Forcibly syntax highlight the code as JavaScript (for non-terminals);\n * overrides highlightCode.\n * default: false\n */\n forceColor?: boolean;\n /**\n * Pass in a string to be displayed inline (if possible) next to the\n * highlighted location in the code. If it can't be positioned inline,\n * it will be placed above the code frame.\n * default: nothing\n */\n message?: string;\n}\n\n/**\n * Chalk styles for code frame token types.\n */\nfunction getDefs(chalk: Chalk) {\n return {\n gutter: chalk.grey,\n marker: chalk.red.bold,\n message: chalk.red.bold,\n };\n}\n\n/**\n * RegExp to test for newlines in terminal.\n */\n\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/;\n\n/**\n * Extract what lines should be marked and highlighted.\n */\n\ntype MarkerLines = Record;\n\nfunction getMarkerLines(\n loc: NodeLocation,\n source: Array,\n opts: Options,\n): {\n start: number;\n end: number;\n markerLines: MarkerLines;\n} {\n const startLoc: Location = {\n column: 0,\n line: -1,\n ...loc.start,\n };\n const endLoc: Location = {\n ...startLoc,\n ...loc.end,\n };\n const { linesAbove = 2, linesBelow = 3 } = opts || {};\n const startLine = startLoc.line;\n const startColumn = startLoc.column;\n const endLine = endLoc.line;\n const endColumn = endLoc.column;\n\n let start = Math.max(startLine - (linesAbove + 1), 0);\n let end = Math.min(source.length, endLine + linesBelow);\n\n if (startLine === -1) {\n start = 0;\n }\n\n if (endLine === -1) {\n end = source.length;\n }\n\n const lineDiff = endLine - startLine;\n const markerLines: MarkerLines = {};\n\n if (lineDiff) {\n for (let i = 0; i <= lineDiff; i++) {\n const lineNumber = i + startLine;\n\n if (!startColumn) {\n markerLines[lineNumber] = true;\n } else if (i === 0) {\n const sourceLength = source[lineNumber - 1].length;\n\n markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];\n } else if (i === lineDiff) {\n markerLines[lineNumber] = [0, endColumn];\n } else {\n const sourceLength = source[lineNumber - i].length;\n\n markerLines[lineNumber] = [0, sourceLength];\n }\n }\n } else {\n if (startColumn === endColumn) {\n if (startColumn) {\n markerLines[startLine] = [startColumn, 0];\n } else {\n markerLines[startLine] = true;\n }\n } else {\n markerLines[startLine] = [startColumn, endColumn - startColumn];\n }\n }\n\n return { start, end, markerLines };\n}\n\nexport function codeFrameColumns(\n rawLines: string,\n loc: NodeLocation,\n opts: Options = {},\n): string {\n const highlighted =\n (opts.highlightCode || opts.forceColor) && shouldHighlight(opts);\n const chalk = getChalk(opts.forceColor);\n const defs = getDefs(chalk);\n const maybeHighlight = (chalkFn: Chalk, string: string) => {\n return highlighted ? chalkFn(string) : string;\n };\n const lines = rawLines.split(NEWLINE);\n const { start, end, markerLines } = getMarkerLines(loc, lines, opts);\n const hasColumns = loc.start && typeof loc.start.column === \"number\";\n\n const numberMaxWidth = String(end).length;\n\n const highlightedLines = highlighted ? highlight(rawLines, opts) : rawLines;\n\n let frame = highlightedLines\n .split(NEWLINE, end)\n .slice(start, end)\n .map((line, index) => {\n const number = start + 1 + index;\n const paddedNumber = ` ${number}`.slice(-numberMaxWidth);\n const gutter = ` ${paddedNumber} |`;\n const hasMarker = markerLines[number];\n const lastMarkerLine = !markerLines[number + 1];\n if (hasMarker) {\n let markerLine = \"\";\n if (Array.isArray(hasMarker)) {\n const markerSpacing = line\n .slice(0, Math.max(hasMarker[0] - 1, 0))\n .replace(/[^\\t]/g, \" \");\n const numberOfMarkers = hasMarker[1] || 1;\n\n markerLine = [\n \"\\n \",\n maybeHighlight(defs.gutter, gutter.replace(/\\d/g, \" \")),\n \" \",\n markerSpacing,\n maybeHighlight(defs.marker, \"^\").repeat(numberOfMarkers),\n ].join(\"\");\n\n if (lastMarkerLine && opts.message) {\n markerLine += \" \" + maybeHighlight(defs.message, opts.message);\n }\n }\n return [\n maybeHighlight(defs.marker, \">\"),\n maybeHighlight(defs.gutter, gutter),\n line.length > 0 ? ` ${line}` : \"\",\n markerLine,\n ].join(\"\");\n } else {\n return ` ${maybeHighlight(defs.gutter, gutter)}${\n line.length > 0 ? ` ${line}` : \"\"\n }`;\n }\n })\n .join(\"\\n\");\n\n if (opts.message && !hasColumns) {\n frame = `${\" \".repeat(numberMaxWidth + 1)}${opts.message}\\n${frame}`;\n }\n\n if (highlighted) {\n return chalk.reset(frame);\n } else {\n return frame;\n }\n}\n\n/**\n * Create a code frame, adding line numbers, code highlighting, and pointing to a given position.\n */\n\nexport default function (\n rawLines: string,\n lineNumber: number,\n colNumber?: number | null,\n opts: Options = {},\n): string {\n if (!deprecationWarningShown) {\n deprecationWarningShown = true;\n\n const message =\n \"Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.\";\n\n if (process.emitWarning) {\n // A string is directly supplied to emitWarning, because when supplying an\n // Error object node throws in the tests because of different contexts\n process.emitWarning(message, \"DeprecationWarning\");\n } else {\n const deprecationError = new Error(message);\n deprecationError.name = \"DeprecationWarning\";\n console.warn(new Error(message));\n }\n }\n\n colNumber = Math.max(colNumber, 0);\n\n const location: NodeLocation = {\n start: { column: colNumber, line: lineNumber },\n };\n\n return codeFrameColumns(rawLines, location, opts);\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAC,uBAAA,CAAAF,OAAA;AAAgF,SAAAG,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAF,wBAAAE,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAjB,CAAA,EAAAc,CAAA,SAAAI,CAAA,GAAAR,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAI,CAAA,KAAAA,CAAA,CAAAX,GAAA,IAAAW,CAAA,CAAAC,GAAA,IAAAR,MAAA,CAAAC,cAAA,CAAAJ,CAAA,EAAAM,CAAA,EAAAI,CAAA,IAAAV,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAgB,GAAA,CAAAnB,CAAA,EAAAQ,CAAA,GAAAA,CAAA;AAEhF,IAAIY,oBAA2B,GAAGC,SAAS;AAC3C,SAASC,QAAQA,CAACC,UAAmB,EAAE;EACrC,IAAIA,UAAU,EAAE;IAAA,IAAAC,qBAAA;IACd,CAAAA,qBAAA,GAAAJ,oBAAoB,YAAAI,qBAAA,GAApBJ,oBAAoB,GAGhB,IAAIK,cAAK,CAACC,WAAW,CAAC;MAAEC,OAAO,EAAE,IAAI;MAAEC,KAAK,EAAE;IAAE,CAAC,CAAC;IACtD,OAAOR,oBAAoB;EAC7B;EACA,OAAOK,cAAK;AACd;AAEA,IAAII,uBAAuB,GAAG,KAAK;AAqCnC,SAASC,OAAOA,CAACL,KAAY,EAAE;EAC7B,OAAO;IACLM,MAAM,EAAEN,KAAK,CAACO,IAAI;IAClBC,MAAM,EAAER,KAAK,CAACS,GAAG,CAACC,IAAI;IACtBC,OAAO,EAAEX,KAAK,CAACS,GAAG,CAACC;EACrB,CAAC;AACH;AAMA,MAAME,OAAO,GAAG,yBAAyB;AAQzC,SAASC,cAAcA,CACrBC,GAAiB,EACjBC,MAAqB,EACrBC,IAAa,EAKb;EACA,MAAMC,QAAkB,GAAA/B,MAAA,CAAAgC,MAAA;IACtBC,MAAM,EAAE,CAAC;IACTC,IAAI,EAAE,CAAC;EAAC,GACLN,GAAG,CAACO,KAAK,CACb;EACD,MAAMC,MAAgB,GAAApC,MAAA,CAAAgC,MAAA,KACjBD,QAAQ,EACRH,GAAG,CAACS,GAAG,CACX;EACD,MAAM;IAAEC,UAAU,GAAG,CAAC;IAAEC,UAAU,GAAG;EAAE,CAAC,GAAGT,IAAI,IAAI,CAAC,CAAC;EACrD,MAAMU,SAAS,GAAGT,QAAQ,CAACG,IAAI;EAC/B,MAAMO,WAAW,GAAGV,QAAQ,CAACE,MAAM;EACnC,MAAMS,OAAO,GAAGN,MAAM,CAACF,IAAI;EAC3B,MAAMS,SAAS,GAAGP,MAAM,CAACH,MAAM;EAE/B,IAAIE,KAAK,GAAGS,IAAI,CAACC,GAAG,CAACL,SAAS,IAAIF,UAAU,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;EACrD,IAAID,GAAG,GAAGO,IAAI,CAACE,GAAG,CAACjB,MAAM,CAACkB,MAAM,EAAEL,OAAO,GAAGH,UAAU,CAAC;EAEvD,IAAIC,SAAS,KAAK,CAAC,CAAC,EAAE;IACpBL,KAAK,GAAG,CAAC;EACX;EAEA,IAAIO,OAAO,KAAK,CAAC,CAAC,EAAE;IAClBL,GAAG,GAAGR,MAAM,CAACkB,MAAM;EACrB;EAEA,MAAMC,QAAQ,GAAGN,OAAO,GAAGF,SAAS;EACpC,MAAMS,WAAwB,GAAG,CAAC,CAAC;EAEnC,IAAID,QAAQ,EAAE;IACZ,KAAK,IAAIzC,CAAC,GAAG,CAAC,EAAEA,CAAC,IAAIyC,QAAQ,EAAEzC,CAAC,EAAE,EAAE;MAClC,MAAM2C,UAAU,GAAG3C,CAAC,GAAGiC,SAAS;MAEhC,IAAI,CAACC,WAAW,EAAE;QAChBQ,WAAW,CAACC,UAAU,CAAC,GAAG,IAAI;MAChC,CAAC,MAAM,IAAI3C,CAAC,KAAK,CAAC,EAAE;QAClB,MAAM4C,YAAY,GAAGtB,MAAM,CAACqB,UAAU,GAAG,CAAC,CAAC,CAACH,MAAM;QAElDE,WAAW,CAACC,UAAU,CAAC,GAAG,CAACT,WAAW,EAAEU,YAAY,GAAGV,WAAW,GAAG,CAAC,CAAC;MACzE,CAAC,MAAM,IAAIlC,CAAC,KAAKyC,QAAQ,EAAE;QACzBC,WAAW,CAACC,UAAU,CAAC,GAAG,CAAC,CAAC,EAAEP,SAAS,CAAC;MAC1C,CAAC,MAAM;QACL,MAAMQ,YAAY,GAAGtB,MAAM,CAACqB,UAAU,GAAG3C,CAAC,CAAC,CAACwC,MAAM;QAElDE,WAAW,CAACC,UAAU,CAAC,GAAG,CAAC,CAAC,EAAEC,YAAY,CAAC;MAC7C;IACF;EACF,CAAC,MAAM;IACL,IAAIV,WAAW,KAAKE,SAAS,EAAE;MAC7B,IAAIF,WAAW,EAAE;QACfQ,WAAW,CAACT,SAAS,CAAC,GAAG,CAACC,WAAW,EAAE,CAAC,CAAC;MAC3C,CAAC,MAAM;QACLQ,WAAW,CAACT,SAAS,CAAC,GAAG,IAAI;MAC/B;IACF,CAAC,MAAM;MACLS,WAAW,CAACT,SAAS,CAAC,GAAG,CAACC,WAAW,EAAEE,SAAS,GAAGF,WAAW,CAAC;IACjE;EACF;EAEA,OAAO;IAAEN,KAAK;IAAEE,GAAG;IAAEY;EAAY,CAAC;AACpC;AAEO,SAASG,gBAAgBA,CAC9BC,QAAgB,EAChBzB,GAAiB,EACjBE,IAAa,GAAG,CAAC,CAAC,EACV;EACR,MAAMwB,WAAW,GACf,CAACxB,IAAI,CAACyB,aAAa,IAAIzB,IAAI,CAAClB,UAAU,KAAK,IAAA4C,0BAAe,EAAC1B,IAAI,CAAC;EAClE,MAAMhB,KAAK,GAAGH,QAAQ,CAACmB,IAAI,CAAClB,UAAU,CAAC;EACvC,MAAM6C,IAAI,GAAGtC,OAAO,CAACL,KAAK,CAAC;EAC3B,MAAM4C,cAAc,GAAGA,CAACC,OAAc,EAAEC,MAAc,KAAK;IACzD,OAAON,WAAW,GAAGK,OAAO,CAACC,MAAM,CAAC,GAAGA,MAAM;EAC/C,CAAC;EACD,MAAMC,KAAK,GAAGR,QAAQ,CAACS,KAAK,CAACpC,OAAO,CAAC;EACrC,MAAM;IAAES,KAAK;IAAEE,GAAG;IAAEY;EAAY,CAAC,GAAGtB,cAAc,CAACC,GAAG,EAAEiC,KAAK,EAAE/B,IAAI,CAAC;EACpE,MAAMiC,UAAU,GAAGnC,GAAG,CAACO,KAAK,IAAI,OAAOP,GAAG,CAACO,KAAK,CAACF,MAAM,KAAK,QAAQ;EAEpE,MAAM+B,cAAc,GAAGC,MAAM,CAAC5B,GAAG,CAAC,CAACU,MAAM;EAEzC,MAAMmB,gBAAgB,GAAGZ,WAAW,GAAG,IAAAa,kBAAS,EAACd,QAAQ,EAAEvB,IAAI,CAAC,GAAGuB,QAAQ;EAE3E,IAAIe,KAAK,GAAGF,gBAAgB,CACzBJ,KAAK,CAACpC,OAAO,EAAEW,GAAG,CAAC,CACnBgC,KAAK,CAAClC,KAAK,EAAEE,GAAG,CAAC,CACjBiC,GAAG,CAAC,CAACpC,IAAI,EAAEqC,KAAK,KAAK;IACpB,MAAMC,MAAM,GAAGrC,KAAK,GAAG,CAAC,GAAGoC,KAAK;IAChC,MAAME,YAAY,GAAI,IAAGD,MAAO,EAAC,CAACH,KAAK,CAAC,CAACL,cAAc,CAAC;IACxD,MAAM5C,MAAM,GAAI,IAAGqD,YAAa,IAAG;IACnC,MAAMC,SAAS,GAAGzB,WAAW,CAACuB,MAAM,CAAC;IACrC,MAAMG,cAAc,GAAG,CAAC1B,WAAW,CAACuB,MAAM,GAAG,CAAC,CAAC;IAC/C,IAAIE,SAAS,EAAE;MACb,IAAIE,UAAU,GAAG,EAAE;MACnB,IAAIC,KAAK,CAACC,OAAO,CAACJ,SAAS,CAAC,EAAE;QAC5B,MAAMK,aAAa,GAAG7C,IAAI,CACvBmC,KAAK,CAAC,CAAC,EAAEzB,IAAI,CAACC,GAAG,CAAC6B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CACvCM,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;QACzB,MAAMC,eAAe,GAAGP,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;QAEzCE,UAAU,GAAG,CACX,KAAK,EACLlB,cAAc,CAACD,IAAI,CAACrC,MAAM,EAAEA,MAAM,CAAC4D,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,EACvD,GAAG,EACHD,aAAa,EACbrB,cAAc,CAACD,IAAI,CAACnC,MAAM,EAAE,GAAG,CAAC,CAAC4D,MAAM,CAACD,eAAe,CAAC,CACzD,CAACE,IAAI,CAAC,EAAE,CAAC;QAEV,IAAIR,cAAc,IAAI7C,IAAI,CAACL,OAAO,EAAE;UAClCmD,UAAU,IAAI,GAAG,GAAGlB,cAAc,CAACD,IAAI,CAAChC,OAAO,EAAEK,IAAI,CAACL,OAAO,CAAC;QAChE;MACF;MACA,OAAO,CACLiC,cAAc,CAACD,IAAI,CAACnC,MAAM,EAAE,GAAG,CAAC,EAChCoC,cAAc,CAACD,IAAI,CAACrC,MAAM,EAAEA,MAAM,CAAC,EACnCc,IAAI,CAACa,MAAM,GAAG,CAAC,GAAI,IAAGb,IAAK,EAAC,GAAG,EAAE,EACjC0C,UAAU,CACX,CAACO,IAAI,CAAC,EAAE,CAAC;IACZ,CAAC,MAAM;MACL,OAAQ,IAAGzB,cAAc,CAACD,IAAI,CAACrC,MAAM,EAAEA,MAAM,CAAE,GAC7Cc,IAAI,CAACa,MAAM,GAAG,CAAC,GAAI,IAAGb,IAAK,EAAC,GAAG,EAChC,EAAC;IACJ;EACF,CAAC,CAAC,CACDiD,IAAI,CAAC,IAAI,CAAC;EAEb,IAAIrD,IAAI,CAACL,OAAO,IAAI,CAACsC,UAAU,EAAE;IAC/BK,KAAK,GAAI,GAAE,GAAG,CAACc,MAAM,CAAClB,cAAc,GAAG,CAAC,CAAE,GAAElC,IAAI,CAACL,OAAQ,KAAI2C,KAAM,EAAC;EACtE;EAEA,IAAId,WAAW,EAAE;IACf,OAAOxC,KAAK,CAACsE,KAAK,CAAChB,KAAK,CAAC;EAC3B,CAAC,MAAM;IACL,OAAOA,KAAK;EACd;AACF;AAMe,SAAAiB,SACbhC,QAAgB,EAChBH,UAAkB,EAClBoC,SAAyB,EACzBxD,IAAa,GAAG,CAAC,CAAC,EACV;EACR,IAAI,CAACZ,uBAAuB,EAAE;IAC5BA,uBAAuB,GAAG,IAAI;IAE9B,MAAMO,OAAO,GACX,qGAAqG;IAEvG,IAAI8D,OAAO,CAACC,WAAW,EAAE;MAGvBD,OAAO,CAACC,WAAW,CAAC/D,OAAO,EAAE,oBAAoB,CAAC;IACpD,CAAC,MAAM;MACL,MAAMgE,gBAAgB,GAAG,IAAIC,KAAK,CAACjE,OAAO,CAAC;MAC3CgE,gBAAgB,CAACE,IAAI,GAAG,oBAAoB;MAC5CC,OAAO,CAACC,IAAI,CAAC,IAAIH,KAAK,CAACjE,OAAO,CAAC,CAAC;IAClC;EACF;EAEA6D,SAAS,GAAG1C,IAAI,CAACC,GAAG,CAACyC,SAAS,EAAE,CAAC,CAAC;EAElC,MAAMQ,QAAsB,GAAG;IAC7B3D,KAAK,EAAE;MAAEF,MAAM,EAAEqD,SAAS;MAAEpD,IAAI,EAAEgB;IAAW;EAC/C,CAAC;EAED,OAAOE,gBAAgB,CAACC,QAAQ,EAAEyC,QAAQ,EAAEhE,IAAI,CAAC;AACnD"} \ No newline at end of file diff --git a/node_modules/@babel/code-frame/node_modules/ansi-styles/index.js b/node_modules/@babel/code-frame/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..90a871c --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/ansi-styles/index.js @@ -0,0 +1,165 @@ +'use strict'; +const colorConvert = require('color-convert'); + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/node_modules/@babel/code-frame/node_modules/ansi-styles/license b/node_modules/@babel/code-frame/node_modules/ansi-styles/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/ansi-styles/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/code-frame/node_modules/ansi-styles/package.json b/node_modules/@babel/code-frame/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..65edb48 --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/ansi-styles/package.json @@ -0,0 +1,56 @@ +{ + "name": "ansi-styles", + "version": "3.2.1", + "description": "ANSI escape codes for styling strings in the terminal", + "license": "MIT", + "repository": "chalk/ansi-styles", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava", + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" + }, + "files": [ + "index.js" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "color-convert": "^1.9.0" + }, + "devDependencies": { + "ava": "*", + "babel-polyfill": "^6.23.0", + "svg-term-cli": "^2.1.1", + "xo": "*" + }, + "ava": { + "require": "babel-polyfill" + } +} diff --git a/node_modules/@babel/code-frame/node_modules/ansi-styles/readme.md b/node_modules/@babel/code-frame/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..3158e2d --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/ansi-styles/readme.md @@ -0,0 +1,147 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) + +> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + + + + +## Install + +``` +$ npm install ansi-styles +``` + + +## Usage + +```js +const style = require('ansi-styles'); + +console.log(`${style.green.open}Hello world!${style.green.close}`); + + +// Color conversion between 16/256/truecolor +// NOTE: If conversion goes to 16 colors or 256 colors, the original color +// may be degraded to fit that color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); +console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); +console.log(style.color.ansi16m.hex('#ABCDEF') + 'Hello world!' + style.color.close); +``` + +## API + +Each style has an `open` and `close` property. + + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `gray` ("bright black") +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `style.modifier` +- `style.color` +- `style.bgColor` + +###### Example + +```js +console.log(style.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +console.log(style.codes.get(36)); +//=> 39 +``` + + +## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) + +`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. + +To use these, call the associated conversion function with the intended output, for example: + +```js +style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code +style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code + +style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code +style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code + +style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code +style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code +``` + + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/node_modules/@babel/code-frame/node_modules/chalk/index.js b/node_modules/@babel/code-frame/node_modules/chalk/index.js new file mode 100644 index 0000000..1cc5fa8 --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/chalk/index.js @@ -0,0 +1,228 @@ +'use strict'; +const escapeStringRegexp = require('escape-string-regexp'); +const ansiStyles = require('ansi-styles'); +const stdoutColor = require('supports-color').stdout; + +const template = require('./templates.js'); + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript diff --git a/node_modules/@babel/code-frame/node_modules/chalk/index.js.flow b/node_modules/@babel/code-frame/node_modules/chalk/index.js.flow new file mode 100644 index 0000000..622caaa --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/chalk/index.js.flow @@ -0,0 +1,93 @@ +// @flow strict + +type TemplateStringsArray = $ReadOnlyArray; + +export type Level = $Values<{ + None: 0, + Basic: 1, + Ansi256: 2, + TrueColor: 3 +}>; + +export type ChalkOptions = {| + enabled?: boolean, + level?: Level +|}; + +export type ColorSupport = {| + level: Level, + hasBasic: boolean, + has256: boolean, + has16m: boolean +|}; + +export interface Chalk { + (...text: string[]): string, + (text: TemplateStringsArray, ...placeholders: string[]): string, + constructor(options?: ChalkOptions): Chalk, + enabled: boolean, + level: Level, + rgb(r: number, g: number, b: number): Chalk, + hsl(h: number, s: number, l: number): Chalk, + hsv(h: number, s: number, v: number): Chalk, + hwb(h: number, w: number, b: number): Chalk, + bgHex(color: string): Chalk, + bgKeyword(color: string): Chalk, + bgRgb(r: number, g: number, b: number): Chalk, + bgHsl(h: number, s: number, l: number): Chalk, + bgHsv(h: number, s: number, v: number): Chalk, + bgHwb(h: number, w: number, b: number): Chalk, + hex(color: string): Chalk, + keyword(color: string): Chalk, + + +reset: Chalk, + +bold: Chalk, + +dim: Chalk, + +italic: Chalk, + +underline: Chalk, + +inverse: Chalk, + +hidden: Chalk, + +strikethrough: Chalk, + + +visible: Chalk, + + +black: Chalk, + +red: Chalk, + +green: Chalk, + +yellow: Chalk, + +blue: Chalk, + +magenta: Chalk, + +cyan: Chalk, + +white: Chalk, + +gray: Chalk, + +grey: Chalk, + +blackBright: Chalk, + +redBright: Chalk, + +greenBright: Chalk, + +yellowBright: Chalk, + +blueBright: Chalk, + +magentaBright: Chalk, + +cyanBright: Chalk, + +whiteBright: Chalk, + + +bgBlack: Chalk, + +bgRed: Chalk, + +bgGreen: Chalk, + +bgYellow: Chalk, + +bgBlue: Chalk, + +bgMagenta: Chalk, + +bgCyan: Chalk, + +bgWhite: Chalk, + +bgBlackBright: Chalk, + +bgRedBright: Chalk, + +bgGreenBright: Chalk, + +bgYellowBright: Chalk, + +bgBlueBright: Chalk, + +bgMagentaBright: Chalk, + +bgCyanBright: Chalk, + +bgWhiteBrigh: Chalk, + + supportsColor: ColorSupport +}; + +declare module.exports: Chalk; diff --git a/node_modules/@babel/code-frame/node_modules/chalk/license b/node_modules/@babel/code-frame/node_modules/chalk/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/chalk/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/code-frame/node_modules/chalk/package.json b/node_modules/@babel/code-frame/node_modules/chalk/package.json new file mode 100644 index 0000000..bc32468 --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/chalk/package.json @@ -0,0 +1,71 @@ +{ + "name": "chalk", + "version": "2.4.2", + "description": "Terminal string styling done right", + "license": "MIT", + "repository": "chalk/chalk", + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava", + "bench": "matcha benchmark.js", + "coveralls": "nyc report --reporter=text-lcov | coveralls" + }, + "files": [ + "index.js", + "templates.js", + "types/index.d.ts", + "index.js.flow" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "str", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "devDependencies": { + "ava": "*", + "coveralls": "^3.0.0", + "execa": "^0.9.0", + "flow-bin": "^0.68.0", + "import-fresh": "^2.0.0", + "matcha": "^0.7.0", + "nyc": "^11.0.2", + "resolve-from": "^4.0.0", + "typescript": "^2.5.3", + "xo": "*" + }, + "types": "types/index.d.ts", + "xo": { + "envs": [ + "node", + "mocha" + ], + "ignores": [ + "test/_flow.js" + ] + } +} diff --git a/node_modules/@babel/code-frame/node_modules/chalk/readme.md b/node_modules/@babel/code-frame/node_modules/chalk/readme.md new file mode 100644 index 0000000..d298e2c --- /dev/null +++ b/node_modules/@babel/code-frame/node_modules/chalk/readme.md @@ -0,0 +1,314 @@ +

+
+
+ Chalk +
+
+
+

+ +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs) + +### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0) + + + + +## Highlights + +- Expressive API +- Highly performant +- Ability to nest styles +- [256/Truecolor color support](#256-and-truecolor-color-support) +- Auto-detects color support +- Doesn't extend `String.prototype` +- Clean and focused +- Actively maintained +- [Used by ~23,000 packages](https://www.npmjs.com/browse/depended/chalk) as of December 31, 2017 + + +## Install + +```console +$ npm install chalk +``` + + + + + + +## Usage + +```js +const chalk = require('chalk'); + +console.log(chalk.blue('Hello world!')); +``` + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +const chalk = require('chalk'); +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// ES2015 tagged template literal +log(chalk` +CPU: {red ${cpu.totalPercent}%} +RAM: {green ${ram.used / ram.total * 100}%} +DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.keyword('orange')('Yay for orange colored text!')); +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); +``` + +Easily define your own themes: + +```js +const chalk = require('chalk'); + +const error = chalk.bold.red; +const warning = chalk.keyword('orange'); + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` + + +## API + +### chalk.` or + + +
+

ESLint Report

+
+ ${reportSummary} - Generated on ${date} +
+
+ + + ${results} + +
+ + + +`.trimStart(); +} + +/** + * Given a word and a count, append an s if count is not one. + * @param {string} word A word in its singular form. + * @param {int} count A number controlling whether word should be pluralized. + * @returns {string} The original word with an s on the end if count is not one. + */ +function pluralize(word, count) { + return (count === 1 ? word : `${word}s`); +} + +/** + * Renders text along the template of x problems (x errors, x warnings) + * @param {string} totalErrors Total errors + * @param {string} totalWarnings Total warnings + * @returns {string} The formatted string, pluralized where necessary + */ +function renderSummary(totalErrors, totalWarnings) { + const totalProblems = totalErrors + totalWarnings; + let renderedText = `${totalProblems} ${pluralize("problem", totalProblems)}`; + + if (totalProblems !== 0) { + renderedText += ` (${totalErrors} ${pluralize("error", totalErrors)}, ${totalWarnings} ${pluralize("warning", totalWarnings)})`; + } + return renderedText; +} + +/** + * Get the color based on whether there are errors/warnings... + * @param {string} totalErrors Total errors + * @param {string} totalWarnings Total warnings + * @returns {int} The color code (0 = green, 1 = yellow, 2 = red) + */ +function renderColor(totalErrors, totalWarnings) { + if (totalErrors !== 0) { + return 2; + } + if (totalWarnings !== 0) { + return 1; + } + return 0; +} + +/** + * Get HTML (table row) describing a single message. + * @param {Object} it data for the message. + * @returns {string} HTML (table row) describing the message. + */ +function messageTemplate(it) { + const { + parentIndex, + lineNumber, + columnNumber, + severityNumber, + severityName, + message, + ruleUrl, + ruleId + } = it; + + return ` + + ${lineNumber}:${columnNumber} + ${severityName} + ${encodeHTML(message)} + + ${ruleId ? ruleId : ""} + + +`.trimStart(); +} + +/** + * Get HTML (table rows) describing the messages. + * @param {Array} messages Messages. + * @param {int} parentIndex Index of the parent HTML row. + * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis. + * @returns {string} HTML (table rows) describing the messages. + */ +function renderMessages(messages, parentIndex, rulesMeta) { + + /** + * Get HTML (table row) describing a message. + * @param {Object} message Message. + * @returns {string} HTML (table row) describing a message. + */ + return messages.map(message => { + const lineNumber = message.line || 0; + const columnNumber = message.column || 0; + let ruleUrl; + + if (rulesMeta) { + const meta = rulesMeta[message.ruleId]; + + if (meta && meta.docs && meta.docs.url) { + ruleUrl = meta.docs.url; + } + } + + return messageTemplate({ + parentIndex, + lineNumber, + columnNumber, + severityNumber: message.severity, + severityName: message.severity === 1 ? "Warning" : "Error", + message: message.message, + ruleId: message.ruleId, + ruleUrl + }); + }).join("\n"); +} + +/** + * Get HTML (table row) describing the result for a single file. + * @param {Object} it data for the file. + * @returns {string} HTML (table row) describing the result for the file. + */ +function resultTemplate(it) { + const { color, index, filePath, summary } = it; + + return ` + + + [+] ${encodeHTML(filePath)} + ${encodeHTML(summary)} + + +`.trimStart(); +} + +/** + * Render the results. + * @param {Array} results Test results. + * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis. + * @returns {string} HTML string describing the results. + */ +function renderResults(results, rulesMeta) { + return results.map((result, index) => resultTemplate({ + index, + color: renderColor(result.errorCount, result.warningCount), + filePath: result.filePath, + summary: renderSummary(result.errorCount, result.warningCount) + }) + renderMessages(result.messages, index, rulesMeta)).join("\n"); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results, data) { + let totalErrors, + totalWarnings; + + const metaData = data ? data.rulesMeta : {}; + + totalErrors = 0; + totalWarnings = 0; + + // Iterate over results to get totals + results.forEach(result => { + totalErrors += result.errorCount; + totalWarnings += result.warningCount; + }); + + return pageTemplate({ + date: new Date(), + reportColor: renderColor(totalErrors, totalWarnings), + reportSummary: renderSummary(totalErrors, totalWarnings), + results: renderResults(results, metaData) + }); +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js b/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js new file mode 100644 index 0000000..0ca1cba --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js @@ -0,0 +1,41 @@ +/** + * @fileoverview JSLint XML reporter + * @author Ian Christian Myers + */ +"use strict"; + +const xmlEscape = require("../xml-escape"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + let output = ""; + + output += ""; + output += ""; + + results.forEach(result => { + const messages = result.messages; + + output += ``; + + messages.forEach(message => { + output += [ + `` + ].join(" "); + }); + + output += ""; + + }); + + output += ""; + + return output; +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js b/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js new file mode 100644 index 0000000..6899471 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js @@ -0,0 +1,16 @@ +/** + * @fileoverview JSON reporter, including rules metadata + * @author Chris Meyer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results, data) { + return JSON.stringify({ + results, + metadata: data + }); +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/json.js b/node_modules/eslint/lib/cli-engine/formatters/json.js new file mode 100644 index 0000000..82138af --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/json.js @@ -0,0 +1,13 @@ +/** + * @fileoverview JSON reporter + * @author Burak Yigit Kaya aka BYK + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + return JSON.stringify(results); +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/junit.js b/node_modules/eslint/lib/cli-engine/formatters/junit.js new file mode 100644 index 0000000..a994b4b --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/junit.js @@ -0,0 +1,82 @@ +/** + * @fileoverview jUnit Reporter + * @author Jamund Ferguson + */ +"use strict"; + +const xmlEscape = require("../xml-escape"); +const path = require("path"); + +//------------------------------------------------------------------------------ +// Helper Functions +//------------------------------------------------------------------------------ + +/** + * Returns the severity of warning or error + * @param {Object} message message object to examine + * @returns {string} severity level + * @private + */ +function getMessageType(message) { + if (message.fatal || message.severity === 2) { + return "Error"; + } + return "Warning"; + +} + +/** + * Returns a full file path without extension + * @param {string} filePath input file path + * @returns {string} file path without extension + * @private + */ +function pathWithoutExt(filePath) { + return path.join(path.dirname(filePath), path.basename(filePath, path.extname(filePath))); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + let output = ""; + + output += "\n"; + output += "\n"; + + results.forEach(result => { + + const messages = result.messages; + const classname = pathWithoutExt(result.filePath); + + if (messages.length > 0) { + output += `\n`; + messages.forEach(message => { + const type = message.fatal ? "error" : "failure"; + + output += ``; + output += `<${type} message="${xmlEscape(message.message || "")}">`; + output += ""; + output += ``; + output += "\n"; + }); + output += "\n"; + } else { + output += `\n`; + output += `\n`; + output += "\n"; + } + + }); + + output += "\n"; + + return output; +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/stylish.js b/node_modules/eslint/lib/cli-engine/formatters/stylish.js new file mode 100644 index 0000000..a808448 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/stylish.js @@ -0,0 +1,101 @@ +/** + * @fileoverview Stylish reporter + * @author Sindre Sorhus + */ +"use strict"; + +const chalk = require("chalk"), + stripAnsi = require("strip-ansi"), + table = require("text-table"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Given a word and a count, append an s if count is not one. + * @param {string} word A word in its singular form. + * @param {int} count A number controlling whether word should be pluralized. + * @returns {string} The original word with an s on the end if count is not one. + */ +function pluralize(word, count) { + return (count === 1 ? word : `${word}s`); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + let output = "\n", + errorCount = 0, + warningCount = 0, + fixableErrorCount = 0, + fixableWarningCount = 0, + summaryColor = "yellow"; + + results.forEach(result => { + const messages = result.messages; + + if (messages.length === 0) { + return; + } + + errorCount += result.errorCount; + warningCount += result.warningCount; + fixableErrorCount += result.fixableErrorCount; + fixableWarningCount += result.fixableWarningCount; + + output += `${chalk.underline(result.filePath)}\n`; + + output += `${table( + messages.map(message => { + let messageType; + + if (message.fatal || message.severity === 2) { + messageType = chalk.red("error"); + summaryColor = "red"; + } else { + messageType = chalk.yellow("warning"); + } + + return [ + "", + message.line || 0, + message.column || 0, + messageType, + message.message.replace(/([^ ])\.$/u, "$1"), + chalk.dim(message.ruleId || "") + ]; + }), + { + align: ["", "r", "l"], + stringLength(str) { + return stripAnsi(str).length; + } + } + ).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`; + }); + + const total = errorCount + warningCount; + + if (total > 0) { + output += chalk[summaryColor].bold([ + "\u2716 ", total, pluralize(" problem", total), + " (", errorCount, pluralize(" error", errorCount), ", ", + warningCount, pluralize(" warning", warningCount), ")\n" + ].join("")); + + if (fixableErrorCount > 0 || fixableWarningCount > 0) { + output += chalk[summaryColor].bold([ + " ", fixableErrorCount, pluralize(" error", fixableErrorCount), " and ", + fixableWarningCount, pluralize(" warning", fixableWarningCount), + " potentially fixable with the `--fix` option.\n" + ].join("")); + } + } + + // Resets output color, for prevent change on top level + return total > 0 ? chalk.reset(output) : ""; +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/tap.js b/node_modules/eslint/lib/cli-engine/formatters/tap.js new file mode 100644 index 0000000..e4148a3 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/tap.js @@ -0,0 +1,95 @@ +/** + * @fileoverview TAP reporter + * @author Jonathan Kingston + */ +"use strict"; + +const yaml = require("js-yaml"); + +//------------------------------------------------------------------------------ +// Helper Functions +//------------------------------------------------------------------------------ + +/** + * Returns a canonical error level string based upon the error message passed in. + * @param {Object} message Individual error message provided by eslint + * @returns {string} Error level string + */ +function getMessageType(message) { + if (message.fatal || message.severity === 2) { + return "error"; + } + return "warning"; +} + +/** + * Takes in a JavaScript object and outputs a TAP diagnostics string + * @param {Object} diagnostic JavaScript object to be embedded as YAML into output. + * @returns {string} diagnostics string with YAML embedded - TAP version 13 compliant + */ +function outputDiagnostics(diagnostic) { + const prefix = " "; + let output = `${prefix}---\n`; + + output += prefix + yaml.dump(diagnostic).split("\n").join(`\n${prefix}`); + output += "...\n"; + return output; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + let output = `TAP version 13\n1..${results.length}\n`; + + results.forEach((result, id) => { + const messages = result.messages; + let testResult = "ok"; + let diagnostics = {}; + + if (messages.length > 0) { + messages.forEach(message => { + const severity = getMessageType(message); + const diagnostic = { + message: message.message, + severity, + data: { + line: message.line || 0, + column: message.column || 0, + ruleId: message.ruleId || "" + } + }; + + // This ensures a warning message is not flagged as error + if (severity === "error") { + testResult = "not ok"; + } + + /* + * If we have multiple messages place them under a messages key + * The first error will be logged as message key + * This is to adhere to TAP 13 loosely defined specification of having a message key + */ + if ("message" in diagnostics) { + if (typeof diagnostics.messages === "undefined") { + diagnostics.messages = []; + } + diagnostics.messages.push(diagnostic); + } else { + diagnostics = diagnostic; + } + }); + } + + output += `${testResult} ${id + 1} - ${result.filePath}\n`; + + // If we have an error include diagnostics + if (messages.length > 0) { + output += outputDiagnostics(diagnostics); + } + + }); + + return output; +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/unix.js b/node_modules/eslint/lib/cli-engine/formatters/unix.js new file mode 100644 index 0000000..c6c4ebb --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/unix.js @@ -0,0 +1,58 @@ +/** + * @fileoverview unix-style formatter. + * @author oshi-shinobu + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helper Functions +//------------------------------------------------------------------------------ + +/** + * Returns a canonical error level string based upon the error message passed in. + * @param {Object} message Individual error message provided by eslint + * @returns {string} Error level string + */ +function getMessageType(message) { + if (message.fatal || message.severity === 2) { + return "Error"; + } + return "Warning"; + +} + + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + let output = "", + total = 0; + + results.forEach(result => { + + const messages = result.messages; + + total += messages.length; + + messages.forEach(message => { + + output += `${result.filePath}:`; + output += `${message.line || 0}:`; + output += `${message.column || 0}:`; + output += ` ${message.message} `; + output += `[${getMessageType(message)}${message.ruleId ? `/${message.ruleId}` : ""}]`; + output += "\n"; + + }); + + }); + + if (total > 0) { + output += `\n${total} problem${total !== 1 ? "s" : ""}`; + } + + return output; +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js b/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js new file mode 100644 index 0000000..0d49431 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js @@ -0,0 +1,63 @@ +/** + * @fileoverview Visual Studio compatible formatter + * @author Ronald Pijnacker + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helper Functions +//------------------------------------------------------------------------------ + +/** + * Returns the severity of warning or error + * @param {Object} message message object to examine + * @returns {string} severity level + * @private + */ +function getMessageType(message) { + if (message.fatal || message.severity === 2) { + return "error"; + } + return "warning"; + +} + + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + let output = "", + total = 0; + + results.forEach(result => { + + const messages = result.messages; + + total += messages.length; + + messages.forEach(message => { + + output += result.filePath; + output += `(${message.line || 0}`; + output += message.column ? `,${message.column}` : ""; + output += `): ${getMessageType(message)}`; + output += message.ruleId ? ` ${message.ruleId}` : ""; + output += ` : ${message.message}`; + output += "\n"; + + }); + + }); + + if (total === 0) { + output += "no problems"; + } else { + output += `\n${total} problem${total !== 1 ? "s" : ""}`; + } + + return output; +}; diff --git a/node_modules/eslint/lib/cli-engine/hash.js b/node_modules/eslint/lib/cli-engine/hash.js new file mode 100644 index 0000000..8e46773 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/hash.js @@ -0,0 +1,35 @@ +/** + * @fileoverview Defining the hashing function in one place. + * @author Michael Ficarra + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const murmur = require("imurmurhash"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +/** + * hash the given string + * @param {string} str the string to hash + * @returns {string} the hash + */ +function hash(str) { + return murmur(str).result().toString(36); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = hash; diff --git a/node_modules/eslint/lib/cli-engine/index.js b/node_modules/eslint/lib/cli-engine/index.js new file mode 100644 index 0000000..52e45a6 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/index.js @@ -0,0 +1,7 @@ +"use strict"; + +const { CLIEngine } = require("./cli-engine"); + +module.exports = { + CLIEngine +}; diff --git a/node_modules/eslint/lib/cli-engine/lint-result-cache.js b/node_modules/eslint/lib/cli-engine/lint-result-cache.js new file mode 100644 index 0000000..e36eb74 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/lint-result-cache.js @@ -0,0 +1,191 @@ +/** + * @fileoverview Utility for caching lint results. + * @author Kevin Partington + */ +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const assert = require("assert"); +const fs = require("fs"); +const fileEntryCache = require("file-entry-cache"); +const stringify = require("json-stable-stringify-without-jsonify"); +const pkg = require("../../package.json"); +const hash = require("./hash"); + +const debug = require("debug")("eslint:lint-result-cache"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const configHashCache = new WeakMap(); +const nodeVersion = process && process.version; + +const validCacheStrategies = ["metadata", "content"]; +const invalidCacheStrategyErrorMessage = `Cache strategy must be one of: ${validCacheStrategies + .map(strategy => `"${strategy}"`) + .join(", ")}`; + +/** + * Tests whether a provided cacheStrategy is valid + * @param {string} cacheStrategy The cache strategy to use + * @returns {boolean} true if `cacheStrategy` is one of `validCacheStrategies`; false otherwise + */ +function isValidCacheStrategy(cacheStrategy) { + return ( + validCacheStrategies.includes(cacheStrategy) + ); +} + +/** + * Calculates the hash of the config + * @param {ConfigArray} config The config. + * @returns {string} The hash of the config + */ +function hashOfConfigFor(config) { + if (!configHashCache.has(config)) { + configHashCache.set(config, hash(`${pkg.version}_${nodeVersion}_${stringify(config)}`)); + } + + return configHashCache.get(config); +} + +//----------------------------------------------------------------------------- +// Public Interface +//----------------------------------------------------------------------------- + +/** + * Lint result cache. This wraps around the file-entry-cache module, + * transparently removing properties that are difficult or expensive to + * serialize and adding them back in on retrieval. + */ +class LintResultCache { + + /** + * Creates a new LintResultCache instance. + * @param {string} cacheFileLocation The cache file location. + * @param {"metadata" | "content"} cacheStrategy The cache strategy to use. + */ + constructor(cacheFileLocation, cacheStrategy) { + assert(cacheFileLocation, "Cache file location is required"); + assert(cacheStrategy, "Cache strategy is required"); + assert( + isValidCacheStrategy(cacheStrategy), + invalidCacheStrategyErrorMessage + ); + + debug(`Caching results to ${cacheFileLocation}`); + + const useChecksum = cacheStrategy === "content"; + + debug( + `Using "${cacheStrategy}" strategy to detect changes` + ); + + this.fileEntryCache = fileEntryCache.create( + cacheFileLocation, + void 0, + useChecksum + ); + this.cacheFileLocation = cacheFileLocation; + } + + /** + * Retrieve cached lint results for a given file path, if present in the + * cache. If the file is present and has not been changed, rebuild any + * missing result information. + * @param {string} filePath The file for which to retrieve lint results. + * @param {ConfigArray} config The config of the file. + * @returns {Object|null} The rebuilt lint results, or null if the file is + * changed or not in the filesystem. + */ + getCachedLintResults(filePath, config) { + + /* + * Cached lint results are valid if and only if: + * 1. The file is present in the filesystem + * 2. The file has not changed since the time it was previously linted + * 3. The ESLint configuration has not changed since the time the file + * was previously linted + * If any of these are not true, we will not reuse the lint results. + */ + const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); + const hashOfConfig = hashOfConfigFor(config); + const changed = + fileDescriptor.changed || + fileDescriptor.meta.hashOfConfig !== hashOfConfig; + + if (fileDescriptor.notFound) { + debug(`File not found on the file system: ${filePath}`); + return null; + } + + if (changed) { + debug(`Cache entry not found or no longer valid: ${filePath}`); + return null; + } + + // If source is present but null, need to reread the file from the filesystem. + if ( + fileDescriptor.meta.results && + fileDescriptor.meta.results.source === null + ) { + debug(`Rereading cached result source from filesystem: ${filePath}`); + fileDescriptor.meta.results.source = fs.readFileSync(filePath, "utf-8"); + } + + return fileDescriptor.meta.results; + } + + /** + * Set the cached lint results for a given file path, after removing any + * information that will be both unnecessary and difficult to serialize. + * Avoids caching results with an "output" property (meaning fixes were + * applied), to prevent potentially incorrect results if fixes are not + * written to disk. + * @param {string} filePath The file for which to set lint results. + * @param {ConfigArray} config The config of the file. + * @param {Object} result The lint result to be set for the file. + * @returns {void} + */ + setCachedLintResults(filePath, config, result) { + if (result && Object.prototype.hasOwnProperty.call(result, "output")) { + return; + } + + const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); + + if (fileDescriptor && !fileDescriptor.notFound) { + debug(`Updating cached result: ${filePath}`); + + // Serialize the result, except that we want to remove the file source if present. + const resultToSerialize = Object.assign({}, result); + + /* + * Set result.source to null. + * In `getCachedLintResults`, if source is explicitly null, we will + * read the file from the filesystem to set the value again. + */ + if (Object.prototype.hasOwnProperty.call(resultToSerialize, "source")) { + resultToSerialize.source = null; + } + + fileDescriptor.meta.results = resultToSerialize; + fileDescriptor.meta.hashOfConfig = hashOfConfigFor(config); + } + } + + /** + * Persists the in-memory cache to disk. + * @returns {void} + */ + reconcile() { + debug(`Persisting cached results: ${this.cacheFileLocation}`); + this.fileEntryCache.reconcile(); + } +} + +module.exports = LintResultCache; diff --git a/node_modules/eslint/lib/cli-engine/load-rules.js b/node_modules/eslint/lib/cli-engine/load-rules.js new file mode 100644 index 0000000..81bab63 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/load-rules.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Module for loading rules from files and directories. + * @author Michael Ficarra + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("fs"), + path = require("path"); + +const rulesDirCache = {}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Load all rule modules from specified directory. + * @param {string} relativeRulesDir Path to rules directory, may be relative. + * @param {string} cwd Current working directory + * @returns {Object} Loaded rule modules. + */ +module.exports = function(relativeRulesDir, cwd) { + const rulesDir = path.resolve(cwd, relativeRulesDir); + + // cache will help performance as IO operation are expensive + if (rulesDirCache[rulesDir]) { + return rulesDirCache[rulesDir]; + } + + const rules = Object.create(null); + + fs.readdirSync(rulesDir).forEach(file => { + if (path.extname(file) !== ".js") { + return; + } + rules[file.slice(0, -3)] = require(path.join(rulesDir, file)); + }); + rulesDirCache[rulesDir] = rules; + + return rules; +}; diff --git a/node_modules/eslint/lib/cli-engine/xml-escape.js b/node_modules/eslint/lib/cli-engine/xml-escape.js new file mode 100644 index 0000000..2e52dba --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/xml-escape.js @@ -0,0 +1,34 @@ +/** + * @fileoverview XML character escaper + * @author George Chung + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Returns the escaped value for a character + * @param {string} s string to examine + * @returns {string} severity level + * @private + */ +module.exports = function(s) { + return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/gu, c => { // eslint-disable-line no-control-regex -- Converting controls to entities + switch (c) { + case "<": + return "<"; + case ">": + return ">"; + case "&": + return "&"; + case "\"": + return """; + case "'": + return "'"; + default: + return `&#${c.charCodeAt(0)};`; + } + }); +}; diff --git a/node_modules/eslint/lib/cli.js b/node_modules/eslint/lib/cli.js new file mode 100644 index 0000000..a14930e --- /dev/null +++ b/node_modules/eslint/lib/cli.js @@ -0,0 +1,441 @@ +/** + * @fileoverview Main CLI object. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * NOTE: The CLI object should *not* call process.exit() directly. It should only return + * exit codes. This allows other programs to use the CLI object and still control + * when the program exits. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("fs"), + path = require("path"), + { promisify } = require("util"), + { ESLint } = require("./eslint"), + { FlatESLint, shouldUseFlatConfig } = require("./eslint/flat-eslint"), + createCLIOptions = require("./options"), + log = require("./shared/logging"), + RuntimeInfo = require("./shared/runtime-info"); +const { Legacy: { naming } } = require("@eslint/eslintrc"); +const { ModuleImporter } = require("@humanwhocodes/module-importer"); + +const debug = require("debug")("eslint:cli"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("./eslint/eslint").ESLintOptions} ESLintOptions */ +/** @typedef {import("./eslint/eslint").LintMessage} LintMessage */ +/** @typedef {import("./eslint/eslint").LintResult} LintResult */ +/** @typedef {import("./options").ParsedCLIOptions} ParsedCLIOptions */ +/** @typedef {import("./shared/types").ResultsMeta} ResultsMeta */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const mkdir = promisify(fs.mkdir); +const stat = promisify(fs.stat); +const writeFile = promisify(fs.writeFile); + +/** + * Predicate function for whether or not to apply fixes in quiet mode. + * If a message is a warning, do not apply a fix. + * @param {LintMessage} message The lint result. + * @returns {boolean} True if the lint message is an error (and thus should be + * autofixed), false otherwise. + */ +function quietFixPredicate(message) { + return message.severity === 2; +} + +/** + * Translates the CLI options into the options expected by the ESLint constructor. + * @param {ParsedCLIOptions} cliOptions The CLI options to translate. + * @param {"flat"|"eslintrc"} [configType="eslintrc"] The format of the + * config to generate. + * @returns {Promise} The options object for the ESLint constructor. + * @private + */ +async function translateOptions({ + cache, + cacheFile, + cacheLocation, + cacheStrategy, + config, + configLookup, + env, + errorOnUnmatchedPattern, + eslintrc, + ext, + fix, + fixDryRun, + fixType, + global, + ignore, + ignorePath, + ignorePattern, + inlineConfig, + parser, + parserOptions, + plugin, + quiet, + reportUnusedDisableDirectives, + resolvePluginsRelativeTo, + rule, + rulesdir +}, configType) { + + let overrideConfig, overrideConfigFile; + const importer = new ModuleImporter(); + + if (configType === "flat") { + overrideConfigFile = (typeof config === "string") ? config : !configLookup; + if (overrideConfigFile === false) { + overrideConfigFile = void 0; + } + + let globals = {}; + + if (global) { + globals = global.reduce((obj, name) => { + if (name.endsWith(":true")) { + obj[name.slice(0, -5)] = "writable"; + } else { + obj[name] = "readonly"; + } + return obj; + }, globals); + } + + overrideConfig = [{ + languageOptions: { + globals, + parserOptions: parserOptions || {} + }, + rules: rule ? rule : {} + }]; + + if (parser) { + overrideConfig[0].languageOptions.parser = await importer.import(parser); + } + + if (plugin) { + const plugins = {}; + + for (const pluginName of plugin) { + + const shortName = naming.getShorthandName(pluginName, "eslint-plugin"); + const longName = naming.normalizePackageName(pluginName, "eslint-plugin"); + + plugins[shortName] = await importer.import(longName); + } + + overrideConfig[0].plugins = plugins; + } + + } else { + overrideConfigFile = config; + + overrideConfig = { + env: env && env.reduce((obj, name) => { + obj[name] = true; + return obj; + }, {}), + globals: global && global.reduce((obj, name) => { + if (name.endsWith(":true")) { + obj[name.slice(0, -5)] = "writable"; + } else { + obj[name] = "readonly"; + } + return obj; + }, {}), + ignorePatterns: ignorePattern, + parser, + parserOptions, + plugins: plugin, + rules: rule + }; + } + + const options = { + allowInlineConfig: inlineConfig, + cache, + cacheLocation: cacheLocation || cacheFile, + cacheStrategy, + errorOnUnmatchedPattern, + fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true), + fixTypes: fixType, + ignore, + overrideConfig, + overrideConfigFile, + reportUnusedDisableDirectives: reportUnusedDisableDirectives ? "error" : void 0 + }; + + if (configType === "flat") { + options.ignorePatterns = ignorePattern; + } else { + options.resolvePluginsRelativeTo = resolvePluginsRelativeTo; + options.rulePaths = rulesdir; + options.useEslintrc = eslintrc; + options.extensions = ext; + options.ignorePath = ignorePath; + } + + return options; +} + +/** + * Count error messages. + * @param {LintResult[]} results The lint results. + * @returns {{errorCount:number;fatalErrorCount:number,warningCount:number}} The number of error messages. + */ +function countErrors(results) { + let errorCount = 0; + let fatalErrorCount = 0; + let warningCount = 0; + + for (const result of results) { + errorCount += result.errorCount; + fatalErrorCount += result.fatalErrorCount; + warningCount += result.warningCount; + } + + return { errorCount, fatalErrorCount, warningCount }; +} + +/** + * Check if a given file path is a directory or not. + * @param {string} filePath The path to a file to check. + * @returns {Promise} `true` if the given path is a directory. + */ +async function isDirectory(filePath) { + try { + return (await stat(filePath)).isDirectory(); + } catch (error) { + if (error.code === "ENOENT" || error.code === "ENOTDIR") { + return false; + } + throw error; + } +} + +/** + * Outputs the results of the linting. + * @param {ESLint} engine The ESLint instance to use. + * @param {LintResult[]} results The results to print. + * @param {string} format The name of the formatter to use or the path to the formatter. + * @param {string} outputFile The path for the output file. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {Promise} True if the printing succeeds, false if not. + * @private + */ +async function printResults(engine, results, format, outputFile, resultsMeta) { + let formatter; + + try { + formatter = await engine.loadFormatter(format); + } catch (e) { + log.error(e.message); + return false; + } + + const output = await formatter.format(results, resultsMeta); + + if (output) { + if (outputFile) { + const filePath = path.resolve(process.cwd(), outputFile); + + if (await isDirectory(filePath)) { + log.error("Cannot write to output file path, it is a directory: %s", outputFile); + return false; + } + + try { + await mkdir(path.dirname(filePath), { recursive: true }); + await writeFile(filePath, output); + } catch (ex) { + log.error("There was a problem writing the output file:\n%s", ex); + return false; + } + } else { + log.info(output); + } + } + + return true; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as + * for other Node.js programs to effectively run the CLI. + */ +const cli = { + + /** + * Executes the CLI based on an array of arguments that is passed in. + * @param {string|Array|Object} args The arguments to process. + * @param {string} [text] The text to lint (used for TTY). + * @param {boolean} [allowFlatConfig] Whether or not to allow flat config. + * @returns {Promise} The exit code for the operation. + */ + async execute(args, text, allowFlatConfig) { + if (Array.isArray(args)) { + debug("CLI args: %o", args.slice(2)); + } + + /* + * Before doing anything, we need to see if we are using a + * flat config file. If so, then we need to change the way command + * line args are parsed. This is temporary, and when we fully + * switch to flat config we can remove this logic. + */ + + const usingFlatConfig = allowFlatConfig && await shouldUseFlatConfig(); + + debug("Using flat config?", usingFlatConfig); + + const CLIOptions = createCLIOptions(usingFlatConfig); + + /** @type {ParsedCLIOptions} */ + let options; + + try { + options = CLIOptions.parse(args); + } catch (error) { + debug("Error parsing CLI options:", error.message); + log.error(error.message); + return 2; + } + + const files = options._; + const useStdin = typeof text === "string"; + + if (options.help) { + log.info(CLIOptions.generateHelp()); + return 0; + } + if (options.version) { + log.info(RuntimeInfo.version()); + return 0; + } + if (options.envInfo) { + try { + log.info(RuntimeInfo.environment()); + return 0; + } catch (err) { + debug("Error retrieving environment info"); + log.error(err.message); + return 2; + } + } + + if (options.printConfig) { + if (files.length) { + log.error("The --print-config option must be used with exactly one file name."); + return 2; + } + if (useStdin) { + log.error("The --print-config option is not available for piped-in code."); + return 2; + } + + const engine = usingFlatConfig + ? new FlatESLint(await translateOptions(options, "flat")) + : new ESLint(await translateOptions(options)); + const fileConfig = + await engine.calculateConfigForFile(options.printConfig); + + log.info(JSON.stringify(fileConfig, null, " ")); + return 0; + } + + debug(`Running on ${useStdin ? "text" : "files"}`); + + if (options.fix && options.fixDryRun) { + log.error("The --fix option and the --fix-dry-run option cannot be used together."); + return 2; + } + if (useStdin && options.fix) { + log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead."); + return 2; + } + if (options.fixType && !options.fix && !options.fixDryRun) { + log.error("The --fix-type option requires either --fix or --fix-dry-run."); + return 2; + } + + const ActiveESLint = usingFlatConfig ? FlatESLint : ESLint; + + const engine = new ActiveESLint(await translateOptions(options, usingFlatConfig ? "flat" : "eslintrc")); + let results; + + if (useStdin) { + results = await engine.lintText(text, { + filePath: options.stdinFilename, + warnIgnored: true + }); + } else { + results = await engine.lintFiles(files); + } + + if (options.fix) { + debug("Fix mode enabled - applying fixes"); + await ActiveESLint.outputFixes(results); + } + + let resultsToPrint = results; + + if (options.quiet) { + debug("Quiet mode enabled - filtering out warnings"); + resultsToPrint = ActiveESLint.getErrorResults(resultsToPrint); + } + + const resultCounts = countErrors(results); + const tooManyWarnings = options.maxWarnings >= 0 && resultCounts.warningCount > options.maxWarnings; + const resultsMeta = tooManyWarnings + ? { + maxWarningsExceeded: { + maxWarnings: options.maxWarnings, + foundWarnings: resultCounts.warningCount + } + } + : {}; + + if (await printResults(engine, resultsToPrint, options.format, options.outputFile, resultsMeta)) { + + // Errors and warnings from the original unfiltered results should determine the exit code + const shouldExitForFatalErrors = + options.exitOnFatalError && resultCounts.fatalErrorCount > 0; + + if (!resultCounts.errorCount && tooManyWarnings) { + log.error( + "ESLint found too many warnings (maximum: %s).", + options.maxWarnings + ); + } + + if (shouldExitForFatalErrors) { + return 2; + } + + return (resultCounts.errorCount || tooManyWarnings) ? 1 : 0; + } + + return 2; + } +}; + +module.exports = cli; diff --git a/node_modules/eslint/lib/config/default-config.js b/node_modules/eslint/lib/config/default-config.js new file mode 100644 index 0000000..8a6ff82 --- /dev/null +++ b/node_modules/eslint/lib/config/default-config.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Default configuration + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const Rules = require("../rules"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +exports.defaultConfig = [ + { + plugins: { + "@": { + + /* + * Because we try to delay loading rules until absolutely + * necessary, a proxy allows us to hook into the lazy-loading + * aspect of the rules map while still keeping all of the + * relevant configuration inside of the config array. + */ + rules: new Proxy({}, { + get(target, property) { + return Rules.get(property); + }, + + has(target, property) { + return Rules.has(property); + } + }) + } + }, + languageOptions: { + sourceType: "module", + ecmaVersion: "latest", + parser: require("espree"), + parserOptions: {} + } + }, + + // default ignores are listed here + { + ignores: [ + "**/node_modules/", + ".git/" + ] + }, + + // intentionally empty config to ensure these files are globbed by default + { + files: ["**/*.js", "**/*.mjs"] + }, + { + files: ["**/*.cjs"], + languageOptions: { + sourceType: "commonjs", + ecmaVersion: "latest" + } + } +]; diff --git a/node_modules/eslint/lib/config/flat-config-array.js b/node_modules/eslint/lib/config/flat-config-array.js new file mode 100644 index 0000000..689dc42 --- /dev/null +++ b/node_modules/eslint/lib/config/flat-config-array.js @@ -0,0 +1,274 @@ +/** + * @fileoverview Flat Config Array + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { ConfigArray, ConfigArraySymbol } = require("@humanwhocodes/config-array"); +const { flatConfigSchema } = require("./flat-config-schema"); +const { RuleValidator } = require("./rule-validator"); +const { defaultConfig } = require("./default-config"); +const jsPlugin = require("@eslint/js"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const ruleValidator = new RuleValidator(); + +/** + * Splits a plugin identifier in the form a/b/c into two parts: a/b and c. + * @param {string} identifier The identifier to parse. + * @returns {{objectName: string, pluginName: string}} The parts of the plugin + * name. + */ +function splitPluginIdentifier(identifier) { + const parts = identifier.split("/"); + + return { + objectName: parts.pop(), + pluginName: parts.join("/") + }; +} + +/** + * Returns the name of an object in the config by reading its `meta` key. + * @param {Object} object The object to check. + * @returns {string?} The name of the object if found or `null` if there + * is no name. + */ +function getObjectId(object) { + + // first check old-style name + let name = object.name; + + if (!name) { + + if (!object.meta) { + return null; + } + + name = object.meta.name; + + if (!name) { + return null; + } + } + + // now check for old-style version + let version = object.version; + + if (!version) { + version = object.meta && object.meta.version; + } + + // if there's a version then append that + if (version) { + return `${name}@${version}`; + } + + return name; +} + +const originalBaseConfig = Symbol("originalBaseConfig"); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Represents an array containing configuration information for ESLint. + */ +class FlatConfigArray extends ConfigArray { + + /** + * Creates a new instance. + * @param {*[]} configs An array of configuration information. + * @param {{basePath: string, shouldIgnore: boolean, baseConfig: FlatConfig}} options The options + * to use for the config array instance. + */ + constructor(configs, { + basePath, + shouldIgnore = true, + baseConfig = defaultConfig + } = {}) { + super(configs, { + basePath, + schema: flatConfigSchema + }); + + if (baseConfig[Symbol.iterator]) { + this.unshift(...baseConfig); + } else { + this.unshift(baseConfig); + } + + /** + * The base config used to build the config array. + * @type {Array} + */ + this[originalBaseConfig] = baseConfig; + Object.defineProperty(this, originalBaseConfig, { writable: false }); + + /** + * Determines if `ignores` fields should be honored. + * If true, then all `ignores` fields are honored. + * if false, then only `ignores` fields in the baseConfig are honored. + * @type {boolean} + */ + this.shouldIgnore = shouldIgnore; + Object.defineProperty(this, "shouldIgnore", { writable: false }); + } + + /* eslint-disable class-methods-use-this -- Desired as instance method */ + /** + * Replaces a config with another config to allow us to put strings + * in the config array that will be replaced by objects before + * normalization. + * @param {Object} config The config to preprocess. + * @returns {Object} The preprocessed config. + */ + [ConfigArraySymbol.preprocessConfig](config) { + if (config === "eslint:recommended") { + + // if we are in a Node.js environment warn the user + if (typeof process !== "undefined" && process.emitWarning) { + process.emitWarning("The 'eslint:recommended' string configuration is deprecated and will be replaced by the @eslint/js package's 'recommended' config."); + } + + return jsPlugin.configs.recommended; + } + + if (config === "eslint:all") { + + // if we are in a Node.js environment warn the user + if (typeof process !== "undefined" && process.emitWarning) { + process.emitWarning("The 'eslint:all' string configuration is deprecated and will be replaced by the @eslint/js package's 'all' config."); + } + + return jsPlugin.configs.all; + } + + /* + * If `shouldIgnore` is false, we remove any ignore patterns specified + * in the config so long as it's not a default config and it doesn't + * have a `files` entry. + */ + if ( + !this.shouldIgnore && + !this[originalBaseConfig].includes(config) && + config.ignores && + !config.files + ) { + /* eslint-disable-next-line no-unused-vars -- need to strip off other keys */ + const { ignores, ...otherKeys } = config; + + return otherKeys; + } + + return config; + } + + /** + * Finalizes the config by replacing plugin references with their objects + * and validating rule option schemas. + * @param {Object} config The config to finalize. + * @returns {Object} The finalized config. + * @throws {TypeError} If the config is invalid. + */ + [ConfigArraySymbol.finalizeConfig](config) { + + const { plugins, languageOptions, processor } = config; + let parserName, processorName; + let invalidParser = false, + invalidProcessor = false; + + // Check parser value + if (languageOptions && languageOptions.parser) { + const { parser } = languageOptions; + + if (typeof parser === "object") { + parserName = getObjectId(parser); + + if (!parserName) { + invalidParser = true; + } + + } else { + invalidParser = true; + } + } + + // Check processor value + if (processor) { + if (typeof processor === "string") { + const { pluginName, objectName: localProcessorName } = splitPluginIdentifier(processor); + + processorName = processor; + + if (!plugins || !plugins[pluginName] || !plugins[pluginName].processors || !plugins[pluginName].processors[localProcessorName]) { + throw new TypeError(`Key "processor": Could not find "${localProcessorName}" in plugin "${pluginName}".`); + } + + config.processor = plugins[pluginName].processors[localProcessorName]; + } else if (typeof processor === "object") { + processorName = getObjectId(processor); + + if (!processorName) { + invalidProcessor = true; + } + + } else { + invalidProcessor = true; + } + } + + ruleValidator.validate(config); + + // apply special logic for serialization into JSON + /* eslint-disable object-shorthand -- shorthand would change "this" value */ + Object.defineProperty(config, "toJSON", { + value: function() { + + if (invalidParser) { + throw new Error("Could not serialize parser object (missing 'meta' object)."); + } + + if (invalidProcessor) { + throw new Error("Could not serialize processor object (missing 'meta' object)."); + } + + return { + ...this, + plugins: Object.entries(plugins).map(([namespace, plugin]) => { + + const pluginId = getObjectId(plugin); + + if (!pluginId) { + return namespace; + } + + return `${namespace}:${pluginId}`; + }), + languageOptions: { + ...languageOptions, + parser: parserName + }, + processor: processorName + }; + } + }); + /* eslint-enable object-shorthand -- ok to enable now */ + + return config; + } + /* eslint-enable class-methods-use-this -- Desired as instance method */ + +} + +exports.FlatConfigArray = FlatConfigArray; diff --git a/node_modules/eslint/lib/config/flat-config-helpers.js b/node_modules/eslint/lib/config/flat-config-helpers.js new file mode 100644 index 0000000..e00c564 --- /dev/null +++ b/node_modules/eslint/lib/config/flat-config-helpers.js @@ -0,0 +1,111 @@ +/** + * @fileoverview Shared functions to work with configs. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Functions +//----------------------------------------------------------------------------- + +/** + * Parses a ruleId into its plugin and rule parts. + * @param {string} ruleId The rule ID to parse. + * @returns {{pluginName:string,ruleName:string}} The plugin and rule + * parts of the ruleId; + */ +function parseRuleId(ruleId) { + let pluginName, ruleName; + + // distinguish between core rules and plugin rules + if (ruleId.includes("/")) { + + // mimic scoped npm packages + if (ruleId.startsWith("@")) { + pluginName = ruleId.slice(0, ruleId.lastIndexOf("/")); + } else { + pluginName = ruleId.slice(0, ruleId.indexOf("/")); + } + + ruleName = ruleId.slice(pluginName.length + 1); + } else { + pluginName = "@"; + ruleName = ruleId; + } + + return { + pluginName, + ruleName + }; +} + +/** + * Retrieves a rule instance from a given config based on the ruleId. + * @param {string} ruleId The rule ID to look for. + * @param {FlatConfig} config The config to search. + * @returns {import("../shared/types").Rule|undefined} The rule if found + * or undefined if not. + */ +function getRuleFromConfig(ruleId, config) { + + const { pluginName, ruleName } = parseRuleId(ruleId); + + const plugin = config.plugins && config.plugins[pluginName]; + let rule = plugin && plugin.rules && plugin.rules[ruleName]; + + + // normalize function rules into objects + if (rule && typeof rule === "function") { + rule = { + create: rule + }; + } + + return rule; +} + +/** + * Gets a complete options schema for a rule. + * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object + * @returns {Object} JSON Schema for the rule's options. + */ +function getRuleOptionsSchema(rule) { + + if (!rule) { + return null; + } + + const schema = rule.schema || rule.meta && rule.meta.schema; + + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length + }; + } + return { + type: "array", + minItems: 0, + maxItems: 0 + }; + + } + + // Given a full schema, leave it alone + return schema || null; +} + + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + parseRuleId, + getRuleFromConfig, + getRuleOptionsSchema +}; diff --git a/node_modules/eslint/lib/config/flat-config-schema.js b/node_modules/eslint/lib/config/flat-config-schema.js new file mode 100644 index 0000000..3922e8a --- /dev/null +++ b/node_modules/eslint/lib/config/flat-config-schema.js @@ -0,0 +1,535 @@ +/** + * @fileoverview Flat config schema + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** + * @typedef ObjectPropertySchema + * @property {Function|string} merge The function or name of the function to call + * to merge multiple objects with this property. + * @property {Function|string} validate The function or name of the function to call + * to validate the value of this property. + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const ruleSeverities = new Map([ + [0, 0], ["off", 0], + [1, 1], ["warn", 1], + [2, 2], ["error", 2] +]); + +const globalVariablesValues = new Set([ + true, "true", "writable", "writeable", + false, "false", "readonly", "readable", null, + "off" +]); + +/** + * Check if a value is a non-null object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(value) { + return typeof value === "object" && value !== null; +} + +/** + * Check if a value is undefined. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is undefined. + */ +function isUndefined(value) { + return typeof value === "undefined"; +} + +/** + * Deeply merges two objects. + * @param {Object} first The base object. + * @param {Object} second The overrides object. + * @returns {Object} An object with properties from both first and second. + */ +function deepMerge(first = {}, second = {}) { + + /* + * If the second value is an array, just return it. We don't merge + * arrays because order matters and we can't know the correct order. + */ + if (Array.isArray(second)) { + return second; + } + + /* + * First create a result object where properties from the second object + * overwrite properties from the first. This sets up a baseline to use + * later rather than needing to inspect and change every property + * individually. + */ + const result = { + ...first, + ...second + }; + + for (const key of Object.keys(second)) { + + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + const firstValue = first[key]; + const secondValue = second[key]; + + if (isNonNullObject(firstValue)) { + result[key] = deepMerge(firstValue, secondValue); + } else if (isUndefined(firstValue)) { + if (isNonNullObject(secondValue)) { + result[key] = deepMerge( + Array.isArray(secondValue) ? [] : {}, + secondValue + ); + } else if (!isUndefined(secondValue)) { + result[key] = secondValue; + } + } + } + + return result; + +} + +/** + * Normalizes the rule options config for a given rule by ensuring that + * it is an array and that the first item is 0, 1, or 2. + * @param {Array|string|number} ruleOptions The rule options config. + * @returns {Array} An array of rule options. + */ +function normalizeRuleOptions(ruleOptions) { + + const finalOptions = Array.isArray(ruleOptions) + ? ruleOptions.slice(0) + : [ruleOptions]; + + finalOptions[0] = ruleSeverities.get(finalOptions[0]); + return finalOptions; +} + +//----------------------------------------------------------------------------- +// Assertions +//----------------------------------------------------------------------------- + +/** + * The error type when a rule's options are configured with an invalid type. + */ +class InvalidRuleOptionsError extends Error { + + /** + * @param {string} ruleId Rule name being configured. + * @param {any} value The invalid value. + */ + constructor(ruleId, value) { + super(`Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`); + this.messageTemplate = "invalid-rule-options"; + this.messageData = { ruleId, value }; + } +} + +/** + * Validates that a value is a valid rule options entry. + * @param {string} ruleId Rule name being configured. + * @param {any} value The value to check. + * @returns {void} + * @throws {InvalidRuleOptionsError} If the value isn't a valid rule options. + */ +function assertIsRuleOptions(ruleId, value) { + if (typeof value !== "string" && typeof value !== "number" && !Array.isArray(value)) { + throw new InvalidRuleOptionsError(ruleId, value); + } +} + +/** + * The error type when a rule's severity is invalid. + */ +class InvalidRuleSeverityError extends Error { + + /** + * @param {string} ruleId Rule name being configured. + * @param {any} value The invalid value. + */ + constructor(ruleId, value) { + super(`Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`); + this.messageTemplate = "invalid-rule-severity"; + this.messageData = { ruleId, value }; + } +} + +/** + * Validates that a value is valid rule severity. + * @param {string} ruleId Rule name being configured. + * @param {any} value The value to check. + * @returns {void} + * @throws {InvalidRuleSeverityError} If the value isn't a valid rule severity. + */ +function assertIsRuleSeverity(ruleId, value) { + const severity = typeof value === "string" + ? ruleSeverities.get(value.toLowerCase()) + : ruleSeverities.get(value); + + if (typeof severity === "undefined") { + throw new InvalidRuleSeverityError(ruleId, value); + } +} + +/** + * Validates that a given string is the form pluginName/objectName. + * @param {string} value The string to check. + * @returns {void} + * @throws {TypeError} If the string isn't in the correct format. + */ +function assertIsPluginMemberName(value) { + if (!/[@a-z0-9-_$]+(?:\/(?:[a-z0-9-_$]+))+$/iu.test(value)) { + throw new TypeError(`Expected string in the form "pluginName/objectName" but found "${value}".`); + } +} + +/** + * Validates that a value is an object. + * @param {any} value The value to check. + * @returns {void} + * @throws {TypeError} If the value isn't an object. + */ +function assertIsObject(value) { + if (!isNonNullObject(value)) { + throw new TypeError("Expected an object."); + } +} + +/** + * The error type when there's an eslintrc-style options in a flat config. + */ +class IncompatibleKeyError extends Error { + + /** + * @param {string} key The invalid key. + */ + constructor(key) { + super("This appears to be in eslintrc format rather than flat config format."); + this.messageTemplate = "eslintrc-incompat"; + this.messageData = { key }; + } +} + +/** + * The error type when there's an eslintrc-style plugins array found. + */ +class IncompatiblePluginsError extends Error { + + /** + * Creates a new instance. + * @param {Array} plugins The plugins array. + */ + constructor(plugins) { + super("This appears to be in eslintrc format (array of strings) rather than flat config format (object)."); + this.messageTemplate = "eslintrc-plugins"; + this.messageData = { plugins }; + } +} + + +//----------------------------------------------------------------------------- +// Low-Level Schemas +//----------------------------------------------------------------------------- + +/** @type {ObjectPropertySchema} */ +const booleanSchema = { + merge: "replace", + validate: "boolean" +}; + +/** @type {ObjectPropertySchema} */ +const deepObjectAssignSchema = { + merge(first = {}, second = {}) { + return deepMerge(first, second); + }, + validate: "object" +}; + +//----------------------------------------------------------------------------- +// High-Level Schemas +//----------------------------------------------------------------------------- + +/** @type {ObjectPropertySchema} */ +const globalsSchema = { + merge: "assign", + validate(value) { + + assertIsObject(value); + + for (const key of Object.keys(value)) { + + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (key !== key.trim()) { + throw new TypeError(`Global "${key}" has leading or trailing whitespace.`); + } + + if (!globalVariablesValues.has(value[key])) { + throw new TypeError(`Key "${key}": Expected "readonly", "writable", or "off".`); + } + } + } +}; + +/** @type {ObjectPropertySchema} */ +const parserSchema = { + merge: "replace", + validate(value) { + + if (!value || typeof value !== "object" || + (typeof value.parse !== "function" && typeof value.parseForESLint !== "function") + ) { + throw new TypeError("Expected object with parse() or parseForESLint() method."); + } + + } +}; + +/** @type {ObjectPropertySchema} */ +const pluginsSchema = { + merge(first = {}, second = {}) { + const keys = new Set([...Object.keys(first), ...Object.keys(second)]); + const result = {}; + + // manually validate that plugins are not redefined + for (const key of keys) { + + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (key in first && key in second && first[key] !== second[key]) { + throw new TypeError(`Cannot redefine plugin "${key}".`); + } + + result[key] = second[key] || first[key]; + } + + return result; + }, + validate(value) { + + // first check the value to be sure it's an object + if (value === null || typeof value !== "object") { + throw new TypeError("Expected an object."); + } + + // make sure it's not an array, which would mean eslintrc-style is used + if (Array.isArray(value)) { + throw new IncompatiblePluginsError(value); + } + + // second check the keys to make sure they are objects + for (const key of Object.keys(value)) { + + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (value[key] === null || typeof value[key] !== "object") { + throw new TypeError(`Key "${key}": Expected an object.`); + } + } + } +}; + +/** @type {ObjectPropertySchema} */ +const processorSchema = { + merge: "replace", + validate(value) { + if (typeof value === "string") { + assertIsPluginMemberName(value); + } else if (value && typeof value === "object") { + if (typeof value.preprocess !== "function" || typeof value.postprocess !== "function") { + throw new TypeError("Object must have a preprocess() and a postprocess() method."); + } + } else { + throw new TypeError("Expected an object or a string."); + } + } +}; + +/** @type {ObjectPropertySchema} */ +const rulesSchema = { + merge(first = {}, second = {}) { + + const result = { + ...first, + ...second + }; + + for (const ruleId of Object.keys(result)) { + + // avoid hairy edge case + if (ruleId === "__proto__") { + + /* eslint-disable-next-line no-proto -- Though deprecated, may still be present */ + delete result.__proto__; + continue; + } + + result[ruleId] = normalizeRuleOptions(result[ruleId]); + + /* + * If either rule config is missing, then the correct + * config is already present and we just need to normalize + * the severity. + */ + if (!(ruleId in first) || !(ruleId in second)) { + continue; + } + + const firstRuleOptions = normalizeRuleOptions(first[ruleId]); + const secondRuleOptions = normalizeRuleOptions(second[ruleId]); + + /* + * If the second rule config only has a severity (length of 1), + * then use that severity and keep the rest of the options from + * the first rule config. + */ + if (secondRuleOptions.length === 1) { + result[ruleId] = [secondRuleOptions[0], ...firstRuleOptions.slice(1)]; + continue; + } + + /* + * In any other situation, then the second rule config takes + * precedence. That means the value at `result[ruleId]` is + * already correct and no further work is necessary. + */ + } + + return result; + }, + + validate(value) { + assertIsObject(value); + + /* + * We are not checking the rule schema here because there is no + * guarantee that the rule definition is present at this point. Instead + * we wait and check the rule schema during the finalization step + * of calculating a config. + */ + for (const ruleId of Object.keys(value)) { + + // avoid hairy edge case + if (ruleId === "__proto__") { + continue; + } + + const ruleOptions = value[ruleId]; + + assertIsRuleOptions(ruleId, ruleOptions); + + if (Array.isArray(ruleOptions)) { + assertIsRuleSeverity(ruleId, ruleOptions[0]); + } else { + assertIsRuleSeverity(ruleId, ruleOptions); + } + } + } +}; + +/** @type {ObjectPropertySchema} */ +const ecmaVersionSchema = { + merge: "replace", + validate(value) { + if (typeof value === "number" || value === "latest") { + return; + } + + throw new TypeError("Expected a number or \"latest\"."); + } +}; + +/** @type {ObjectPropertySchema} */ +const sourceTypeSchema = { + merge: "replace", + validate(value) { + if (typeof value !== "string" || !/^(?:script|module|commonjs)$/u.test(value)) { + throw new TypeError("Expected \"script\", \"module\", or \"commonjs\"."); + } + } +}; + +/** + * Creates a schema that always throws an error. Useful for warning + * about eslintrc-style keys. + * @param {string} key The eslintrc key to create a schema for. + * @returns {ObjectPropertySchema} The schema. + */ +function createEslintrcErrorSchema(key) { + return { + merge: "replace", + validate() { + throw new IncompatibleKeyError(key); + } + }; +} + +const eslintrcKeys = [ + "env", + "extends", + "globals", + "ignorePatterns", + "noInlineConfig", + "overrides", + "parser", + "parserOptions", + "reportUnusedDisableDirectives", + "root" +]; + +//----------------------------------------------------------------------------- +// Full schema +//----------------------------------------------------------------------------- + +exports.flatConfigSchema = { + + // eslintrc-style keys that should always error + ...Object.fromEntries(eslintrcKeys.map(key => [key, createEslintrcErrorSchema(key)])), + + // flat config keys + settings: deepObjectAssignSchema, + linterOptions: { + schema: { + noInlineConfig: booleanSchema, + reportUnusedDisableDirectives: booleanSchema + } + }, + languageOptions: { + schema: { + ecmaVersion: ecmaVersionSchema, + sourceType: sourceTypeSchema, + globals: globalsSchema, + parser: parserSchema, + parserOptions: deepObjectAssignSchema + } + }, + processor: processorSchema, + plugins: pluginsSchema, + rules: rulesSchema +}; diff --git a/node_modules/eslint/lib/config/rule-validator.js b/node_modules/eslint/lib/config/rule-validator.js new file mode 100644 index 0000000..0b5858f --- /dev/null +++ b/node_modules/eslint/lib/config/rule-validator.js @@ -0,0 +1,157 @@ +/** + * @fileoverview Rule Validator + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const ajv = require("../shared/ajv")(); +const { + parseRuleId, + getRuleFromConfig, + getRuleOptionsSchema +} = require("./flat-config-helpers"); +const ruleReplacements = require("../../conf/replacements.json"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Throws a helpful error when a rule cannot be found. + * @param {Object} ruleId The rule identifier. + * @param {string} ruleId.pluginName The ID of the rule to find. + * @param {string} ruleId.ruleName The ID of the rule to find. + * @param {Object} config The config to search in. + * @throws {TypeError} For missing plugin or rule. + * @returns {void} + */ +function throwRuleNotFoundError({ pluginName, ruleName }, config) { + + const ruleId = pluginName === "@" ? ruleName : `${pluginName}/${ruleName}`; + + const errorMessageHeader = `Key "rules": Key "${ruleId}"`; + let errorMessage = `${errorMessageHeader}: Could not find plugin "${pluginName}".`; + + // if the plugin exists then we need to check if the rule exists + if (config.plugins && config.plugins[pluginName]) { + const replacementRuleName = ruleReplacements.rules[ruleName]; + + if (pluginName === "@" && replacementRuleName) { + + errorMessage = `${errorMessageHeader}: Rule "${ruleName}" was removed and replaced by "${replacementRuleName}".`; + + } else { + + errorMessage = `${errorMessageHeader}: Could not find "${ruleName}" in plugin "${pluginName}".`; + + // otherwise, let's see if we can find the rule name elsewhere + for (const [otherPluginName, otherPlugin] of Object.entries(config.plugins)) { + if (otherPlugin.rules && otherPlugin.rules[ruleName]) { + errorMessage += ` Did you mean "${otherPluginName}/${ruleName}"?`; + break; + } + } + + } + + // falls through to throw error + } + + throw new TypeError(errorMessage); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Implements validation functionality for the rules portion of a config. + */ +class RuleValidator { + + /** + * Creates a new instance. + */ + constructor() { + + /** + * A collection of compiled validators for rules that have already + * been validated. + * @type {WeakMap} + */ + this.validators = new WeakMap(); + } + + /** + * Validates all of the rule configurations in a config against each + * rule's schema. + * @param {Object} config The full config to validate. This object must + * contain both the rules section and the plugins section. + * @returns {void} + * @throws {Error} If a rule's configuration does not match its schema. + */ + validate(config) { + + if (!config.rules) { + return; + } + + for (const [ruleId, ruleOptions] of Object.entries(config.rules)) { + + // check for edge case + if (ruleId === "__proto__") { + continue; + } + + /* + * If a rule is disabled, we don't do any validation. This allows + * users to safely set any value to 0 or "off" without worrying + * that it will cause a validation error. + * + * Note: ruleOptions is always an array at this point because + * this validation occurs after FlatConfigArray has merged and + * normalized values. + */ + if (ruleOptions[0] === 0) { + continue; + } + + const rule = getRuleFromConfig(ruleId, config); + + if (!rule) { + throwRuleNotFoundError(parseRuleId(ruleId), config); + } + + // Precompile and cache validator the first time + if (!this.validators.has(rule)) { + const schema = getRuleOptionsSchema(rule); + + if (schema) { + this.validators.set(rule, ajv.compile(schema)); + } + } + + const validateRule = this.validators.get(rule); + + if (validateRule) { + + validateRule(ruleOptions.slice(1)); + + if (validateRule.errors) { + throw new Error(`Key "rules": Key "${ruleId}": ${ + validateRule.errors.map( + error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` + ).join("") + }`); + } + } + } + } +} + +exports.RuleValidator = RuleValidator; diff --git a/node_modules/eslint/lib/eslint/eslint-helpers.js b/node_modules/eslint/lib/eslint/eslint-helpers.js new file mode 100644 index 0000000..e25b10e --- /dev/null +++ b/node_modules/eslint/lib/eslint/eslint-helpers.js @@ -0,0 +1,904 @@ +/** + * @fileoverview Helper functions for ESLint class + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const path = require("path"); +const fs = require("fs"); +const fsp = fs.promises; +const isGlob = require("is-glob"); +const hash = require("../cli-engine/hash"); +const minimatch = require("minimatch"); +const util = require("util"); +const fswalk = require("@nodelib/fs.walk"); +const globParent = require("glob-parent"); +const isPathInside = require("is-path-inside"); + +//----------------------------------------------------------------------------- +// Fixup references +//----------------------------------------------------------------------------- + +const doFsWalk = util.promisify(fswalk.walk); +const Minimatch = minimatch.Minimatch; +const MINIMATCH_OPTIONS = { dot: true }; + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** + * @typedef {Object} GlobSearch + * @property {Array} patterns The normalized patterns to use for a search. + * @property {Array} rawPatterns The patterns as entered by the user + * before doing any normalization. + */ + +//----------------------------------------------------------------------------- +// Errors +//----------------------------------------------------------------------------- + +/** + * The error type when no files match a glob. + */ +class NoFilesFoundError extends Error { + + /** + * @param {string} pattern The glob pattern which was not found. + * @param {boolean} globEnabled If `false` then the pattern was a glob pattern, but glob was disabled. + */ + constructor(pattern, globEnabled) { + super(`No files matching '${pattern}' were found${!globEnabled ? " (glob was disabled)" : ""}.`); + this.messageTemplate = "file-not-found"; + this.messageData = { pattern, globDisabled: !globEnabled }; + } +} + +/** + * The error type when a search fails to match multiple patterns. + */ +class UnmatchedSearchPatternsError extends Error { + + /** + * @param {Object} options The options for the error. + * @param {string} options.basePath The directory that was searched. + * @param {Array} options.unmatchedPatterns The glob patterns + * which were not found. + * @param {Array} options.patterns The glob patterns that were + * searched. + * @param {Array} options.rawPatterns The raw glob patterns that + * were searched. + */ + constructor({ basePath, unmatchedPatterns, patterns, rawPatterns }) { + super(`No files matching '${rawPatterns}' in '${basePath}' were found.`); + this.basePath = basePath; + this.unmatchedPatterns = unmatchedPatterns; + this.patterns = patterns; + this.rawPatterns = rawPatterns; + } +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class AllFilesIgnoredError extends Error { + + /** + * @param {string} pattern The glob pattern which was not found. + */ + constructor(pattern) { + super(`All files matched by '${pattern}' are ignored.`); + this.messageTemplate = "all-files-ignored"; + this.messageData = { pattern }; + } +} + + +//----------------------------------------------------------------------------- +// General Helpers +//----------------------------------------------------------------------------- + +/** + * Check if a given value is a non-empty string or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is a non-empty string. + */ +function isNonEmptyString(x) { + return typeof x === "string" && x.trim() !== ""; +} + +/** + * Check if a given value is an array of non-empty strings or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is an array of non-empty strings. + */ +function isArrayOfNonEmptyString(x) { + return Array.isArray(x) && x.every(isNonEmptyString); +} + +//----------------------------------------------------------------------------- +// File-related Helpers +//----------------------------------------------------------------------------- + +/** + * Normalizes slashes in a file pattern to posix-style. + * @param {string} pattern The pattern to replace slashes in. + * @returns {string} The pattern with slashes normalized. + */ +function normalizeToPosix(pattern) { + return pattern.replace(/\\/gu, "/"); +} + +/** + * Check if a string is a glob pattern or not. + * @param {string} pattern A glob pattern. + * @returns {boolean} `true` if the string is a glob pattern. + */ +function isGlobPattern(pattern) { + return isGlob(path.sep === "\\" ? normalizeToPosix(pattern) : pattern); +} + + +/** + * Determines if a given glob pattern will return any results. + * Used primarily to help with useful error messages. + * @param {Object} options The options for the function. + * @param {string} options.basePath The directory to search. + * @param {string} options.pattern A glob pattern to match. + * @returns {Promise} True if there is a glob match, false if not. + */ +function globMatch({ basePath, pattern }) { + + let found = false; + const patternToUse = path.isAbsolute(pattern) + ? normalizeToPosix(path.relative(basePath, pattern)) + : pattern; + + const matcher = new Minimatch(patternToUse, MINIMATCH_OPTIONS); + + const fsWalkSettings = { + + deepFilter(entry) { + const relativePath = normalizeToPosix(path.relative(basePath, entry.path)); + + return !found && matcher.match(relativePath, true); + }, + + entryFilter(entry) { + if (found || entry.dirent.isDirectory()) { + return false; + } + + const relativePath = normalizeToPosix(path.relative(basePath, entry.path)); + + if (matcher.match(relativePath)) { + found = true; + return true; + } + + return false; + } + }; + + return new Promise(resolve => { + + // using a stream so we can exit early because we just need one match + const globStream = fswalk.walkStream(basePath, fsWalkSettings); + + globStream.on("data", () => { + globStream.destroy(); + resolve(true); + }); + + // swallow errors as they're not important here + globStream.on("error", () => { }); + + globStream.on("end", () => { + resolve(false); + }); + globStream.read(); + }); + +} + +/** + * Searches a directory looking for matching glob patterns. This uses + * the config array's logic to determine if a directory or file should + * be ignored, so it is consistent with how ignoring works throughout + * ESLint. + * @param {Object} options The options for this function. + * @param {string} options.basePath The directory to search. + * @param {Array} options.patterns An array of glob patterns + * to match. + * @param {Array} options.rawPatterns An array of glob patterns + * as the user inputted them. Used for errors. + * @param {FlatConfigArray} options.configs The config array to use for + * determining what to ignore. + * @param {boolean} options.errorOnUnmatchedPattern Determines if an error + * should be thrown when a pattern is unmatched. + * @returns {Promise>} An array of matching file paths + * or an empty array if there are no matches. + * @throws {UnmatchedSearchPatternsError} If there is a pattern that doesn't + * match any files. + */ +async function globSearch({ + basePath, + patterns, + rawPatterns, + configs, + errorOnUnmatchedPattern +}) { + + if (patterns.length === 0) { + return []; + } + + /* + * In this section we are converting the patterns into Minimatch + * instances for performance reasons. Because we are doing the same + * matches repeatedly, it's best to compile those patterns once and + * reuse them multiple times. + * + * To do that, we convert any patterns with an absolute path into a + * relative path and normalize it to Posix-style slashes. We also keep + * track of the relative patterns to map them back to the original + * patterns, which we need in order to throw an error if there are any + * unmatched patterns. + */ + const relativeToPatterns = new Map(); + const matchers = patterns.map((pattern, i) => { + const patternToUse = path.isAbsolute(pattern) + ? normalizeToPosix(path.relative(basePath, pattern)) + : pattern; + + relativeToPatterns.set(patternToUse, patterns[i]); + + return new Minimatch(patternToUse, MINIMATCH_OPTIONS); + }); + + /* + * We track unmatched patterns because we may want to throw an error when + * they occur. To start, this set is initialized with all of the patterns. + * Every time a match occurs, the pattern is removed from the set, making + * it easy to tell if we have any unmatched patterns left at the end of + * search. + */ + const unmatchedPatterns = new Set([...relativeToPatterns.keys()]); + + const filePaths = (await doFsWalk(basePath, { + + deepFilter(entry) { + const relativePath = normalizeToPosix(path.relative(basePath, entry.path)); + const matchesPattern = matchers.some(matcher => matcher.match(relativePath, true)); + + return matchesPattern && !configs.isDirectoryIgnored(entry.path); + }, + entryFilter(entry) { + const relativePath = normalizeToPosix(path.relative(basePath, entry.path)); + + // entries may be directories or files so filter out directories + if (entry.dirent.isDirectory()) { + return false; + } + + /* + * Optimization: We need to track when patterns are left unmatched + * and so we use `unmatchedPatterns` to do that. There is a bit of + * complexity here because the same file can be matched by more than + * one pattern. So, when we start, we actually need to test every + * pattern against every file. Once we know there are no remaining + * unmatched patterns, then we can switch to just looking for the + * first matching pattern for improved speed. + */ + const matchesPattern = unmatchedPatterns.size > 0 + ? matchers.reduce((previousValue, matcher) => { + const pathMatches = matcher.match(relativePath); + + /* + * We updated the unmatched patterns set only if the path + * matches and the file isn't ignored. If the file is + * ignored, that means there wasn't a match for the + * pattern so it should not be removed. + * + * Performance note: isFileIgnored() aggressively caches + * results so there is no performance penalty for calling + * it twice with the same argument. + */ + if (pathMatches && !configs.isFileIgnored(entry.path)) { + unmatchedPatterns.delete(matcher.pattern); + } + + return pathMatches || previousValue; + }, false) + : matchers.some(matcher => matcher.match(relativePath)); + + return matchesPattern && !configs.isFileIgnored(entry.path); + } + + })).map(entry => entry.path); + + // now check to see if we have any unmatched patterns + if (errorOnUnmatchedPattern && unmatchedPatterns.size > 0) { + throw new UnmatchedSearchPatternsError({ + basePath, + unmatchedPatterns: [...unmatchedPatterns].map( + pattern => relativeToPatterns.get(pattern) + ), + patterns, + rawPatterns + }); + } + + return filePaths; +} + +/** + * Throws an error for unmatched patterns. The error will only contain information about the first one. + * Checks to see if there are any ignored results for a given search. + * @param {Object} options The options for this function. + * @param {string} options.basePath The directory to search. + * @param {Array} options.patterns An array of glob patterns + * that were used in the original search. + * @param {Array} options.rawPatterns An array of glob patterns + * as the user inputted them. Used for errors. + * @param {Array} options.unmatchedPatterns A non-empty array of glob patterns + * that were unmatched in the original search. + * @returns {void} Always throws an error. + * @throws {NoFilesFoundError} If the first unmatched pattern + * doesn't match any files even when there are no ignores. + * @throws {AllFilesIgnoredError} If the first unmatched pattern + * matches some files when there are no ignores. + */ +async function throwErrorForUnmatchedPatterns({ + basePath, + patterns, + rawPatterns, + unmatchedPatterns +}) { + + const pattern = unmatchedPatterns[0]; + const rawPattern = rawPatterns[patterns.indexOf(pattern)]; + + const patternHasMatch = await globMatch({ + basePath, + pattern + }); + + if (patternHasMatch) { + throw new AllFilesIgnoredError(rawPattern); + } + + // if we get here there are truly no matches + throw new NoFilesFoundError(rawPattern, true); +} + +/** + * Performs multiple glob searches in parallel. + * @param {Object} options The options for this function. + * @param {Map} options.searches + * An array of glob patterns to match. + * @param {FlatConfigArray} options.configs The config array to use for + * determining what to ignore. + * @param {boolean} options.errorOnUnmatchedPattern Determines if an + * unmatched glob pattern should throw an error. + * @returns {Promise>} An array of matching file paths + * or an empty array if there are no matches. + */ +async function globMultiSearch({ searches, configs, errorOnUnmatchedPattern }) { + + /* + * For convenience, we normalized the search map into an array of objects. + * Next, we filter out all searches that have no patterns. This happens + * primarily for the cwd, which is prepopulated in the searches map as an + * optimization. However, if it has no patterns, it means all patterns + * occur outside of the cwd and we can safely filter out that search. + */ + const normalizedSearches = [...searches].map( + ([basePath, { patterns, rawPatterns }]) => ({ basePath, patterns, rawPatterns }) + ).filter(({ patterns }) => patterns.length > 0); + + const results = await Promise.allSettled( + normalizedSearches.map( + ({ basePath, patterns, rawPatterns }) => globSearch({ + basePath, + patterns, + rawPatterns, + configs, + errorOnUnmatchedPattern + }) + ) + ); + + const filePaths = []; + + for (let i = 0; i < results.length; i++) { + + const result = results[i]; + const currentSearch = normalizedSearches[i]; + + if (result.status === "fulfilled") { + + // if the search was successful just add the results + if (result.value.length > 0) { + filePaths.push(...result.value); + } + + continue; + } + + // if we make it here then there was an error + const error = result.reason; + + // unexpected errors should be re-thrown + if (!error.basePath) { + throw error; + } + + if (errorOnUnmatchedPattern) { + + await throwErrorForUnmatchedPatterns({ + ...currentSearch, + unmatchedPatterns: error.unmatchedPatterns + }); + + } + + } + + return [...new Set(filePaths)]; + +} + +/** + * Finds all files matching the options specified. + * @param {Object} args The arguments objects. + * @param {Array} args.patterns An array of glob patterns. + * @param {boolean} args.globInputPaths true to interpret glob patterns, + * false to not interpret glob patterns. + * @param {string} args.cwd The current working directory to find from. + * @param {FlatConfigArray} args.configs The configs for the current run. + * @param {boolean} args.errorOnUnmatchedPattern Determines if an unmatched pattern + * should throw an error. + * @returns {Promise>} The fully resolved file paths. + * @throws {AllFilesIgnoredError} If there are no results due to an ignore pattern. + * @throws {NoFilesFoundError} If no files matched the given patterns. + */ +async function findFiles({ + patterns, + globInputPaths, + cwd, + configs, + errorOnUnmatchedPattern +}) { + + const results = []; + const missingPatterns = []; + let globbyPatterns = []; + let rawPatterns = []; + const searches = new Map([[cwd, { patterns: globbyPatterns, rawPatterns: [] }]]); + + // check to see if we have explicit files and directories + const filePaths = patterns.map(filePath => path.resolve(cwd, filePath)); + const stats = await Promise.all( + filePaths.map( + filePath => fsp.stat(filePath).catch(() => { }) + ) + ); + + stats.forEach((stat, index) => { + + const filePath = filePaths[index]; + const pattern = normalizeToPosix(patterns[index]); + + if (stat) { + + // files are added directly to the list + if (stat.isFile()) { + results.push({ + filePath, + ignored: configs.isFileIgnored(filePath) + }); + } + + // directories need extensions attached + if (stat.isDirectory()) { + + // group everything in cwd together and split out others + if (isPathInside(filePath, cwd)) { + ({ patterns: globbyPatterns, rawPatterns } = searches.get(cwd)); + } else { + if (!searches.has(filePath)) { + searches.set(filePath, { patterns: [], rawPatterns: [] }); + } + ({ patterns: globbyPatterns, rawPatterns } = searches.get(filePath)); + } + + globbyPatterns.push(`${normalizeToPosix(filePath)}/**`); + rawPatterns.push(pattern); + } + + return; + } + + // save patterns for later use based on whether globs are enabled + if (globInputPaths && isGlobPattern(pattern)) { + + const basePath = path.resolve(cwd, globParent(pattern)); + + // group in cwd if possible and split out others + if (isPathInside(basePath, cwd)) { + ({ patterns: globbyPatterns, rawPatterns } = searches.get(cwd)); + } else { + if (!searches.has(basePath)) { + searches.set(basePath, { patterns: [], rawPatterns: [] }); + } + ({ patterns: globbyPatterns, rawPatterns } = searches.get(basePath)); + } + + globbyPatterns.push(filePath); + rawPatterns.push(pattern); + } else { + missingPatterns.push(pattern); + } + }); + + // there were patterns that didn't match anything, tell the user + if (errorOnUnmatchedPattern && missingPatterns.length) { + throw new NoFilesFoundError(missingPatterns[0], globInputPaths); + } + + // now we are safe to do the search + const globbyResults = await globMultiSearch({ + searches, + configs, + errorOnUnmatchedPattern + }); + + return [ + ...results, + ...globbyResults.map(filePath => ({ + filePath: path.resolve(filePath), + ignored: false + })) + ]; +} + +//----------------------------------------------------------------------------- +// Results-related Helpers +//----------------------------------------------------------------------------- + +/** + * Checks if the given message is an error message. + * @param {LintMessage} message The message to check. + * @returns {boolean} Whether or not the message is an error message. + * @private + */ +function isErrorMessage(message) { + return message.severity === 2; +} + +/** + * Returns result with warning by ignore settings + * @param {string} filePath File path of checked code + * @param {string} baseDir Absolute path of base directory + * @returns {LintResult} Result with single warning + * @private + */ +function createIgnoreResult(filePath, baseDir) { + let message; + const isInNodeModules = baseDir && path.dirname(path.relative(baseDir, filePath)).split(path.sep).includes("node_modules"); + + if (isInNodeModules) { + message = "File ignored by default because it is located under the node_modules directory. Use ignore pattern \"!**/node_modules/\" to override."; + } else { + message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override."; + } + + return { + filePath: path.resolve(filePath), + messages: [ + { + ruleId: null, + fatal: false, + severity: 1, + message, + nodeType: null + } + ], + suppressedMessages: [], + errorCount: 0, + warningCount: 1, + fatalErrorCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0 + }; +} + +//----------------------------------------------------------------------------- +// Options-related Helpers +//----------------------------------------------------------------------------- + + +/** + * Check if a given value is a valid fix type or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is valid fix type. + */ +function isFixType(x) { + return x === "directive" || x === "problem" || x === "suggestion" || x === "layout"; +} + +/** + * Check if a given value is an array of fix types or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is an array of fix types. + */ +function isFixTypeArray(x) { + return Array.isArray(x) && x.every(isFixType); +} + +/** + * The error for invalid options. + */ +class ESLintInvalidOptionsError extends Error { + constructor(messages) { + super(`Invalid Options:\n- ${messages.join("\n- ")}`); + this.code = "ESLINT_INVALID_OPTIONS"; + Error.captureStackTrace(this, ESLintInvalidOptionsError); + } +} + +/** + * Validates and normalizes options for the wrapped CLIEngine instance. + * @param {FlatESLintOptions} options The options to process. + * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors. + * @returns {FlatESLintOptions} The normalized options. + */ +function processOptions({ + allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored. + baseConfig = null, + cache = false, + cacheLocation = ".eslintcache", + cacheStrategy = "metadata", + cwd = process.cwd(), + errorOnUnmatchedPattern = true, + fix = false, + fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property. + globInputPaths = true, + ignore = true, + ignorePatterns = null, + overrideConfig = null, + overrideConfigFile = null, + plugins = {}, + reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that. + ...unknownOptions +}) { + const errors = []; + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length >= 1) { + errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`); + if (unknownOptionKeys.includes("cacheFile")) { + errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead."); + } + if (unknownOptionKeys.includes("configFile")) { + errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead."); + } + if (unknownOptionKeys.includes("envs")) { + errors.push("'envs' has been removed."); + } + if (unknownOptionKeys.includes("extensions")) { + errors.push("'extensions' has been removed."); + } + if (unknownOptionKeys.includes("resolvePluginsRelativeTo")) { + errors.push("'resolvePluginsRelativeTo' has been removed."); + } + if (unknownOptionKeys.includes("globals")) { + errors.push("'globals' has been removed. Please use the 'overrideConfig.languageOptions.globals' option instead."); + } + if (unknownOptionKeys.includes("ignorePath")) { + errors.push("'ignorePath' has been removed."); + } + if (unknownOptionKeys.includes("ignorePattern")) { + errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead."); + } + if (unknownOptionKeys.includes("parser")) { + errors.push("'parser' has been removed. Please use the 'overrideConfig.languageOptions.parser' option instead."); + } + if (unknownOptionKeys.includes("parserOptions")) { + errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.languageOptions.parserOptions' option instead."); + } + if (unknownOptionKeys.includes("rules")) { + errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead."); + } + if (unknownOptionKeys.includes("rulePaths")) { + errors.push("'rulePaths' has been removed. Please define your rules using plugins."); + } + } + if (typeof allowInlineConfig !== "boolean") { + errors.push("'allowInlineConfig' must be a boolean."); + } + if (typeof baseConfig !== "object") { + errors.push("'baseConfig' must be an object or null."); + } + if (typeof cache !== "boolean") { + errors.push("'cache' must be a boolean."); + } + if (!isNonEmptyString(cacheLocation)) { + errors.push("'cacheLocation' must be a non-empty string."); + } + if ( + cacheStrategy !== "metadata" && + cacheStrategy !== "content" + ) { + errors.push("'cacheStrategy' must be any of \"metadata\", \"content\"."); + } + if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) { + errors.push("'cwd' must be an absolute path."); + } + if (typeof errorOnUnmatchedPattern !== "boolean") { + errors.push("'errorOnUnmatchedPattern' must be a boolean."); + } + if (typeof fix !== "boolean" && typeof fix !== "function") { + errors.push("'fix' must be a boolean or a function."); + } + if (fixTypes !== null && !isFixTypeArray(fixTypes)) { + errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\"."); + } + if (typeof globInputPaths !== "boolean") { + errors.push("'globInputPaths' must be a boolean."); + } + if (typeof ignore !== "boolean") { + errors.push("'ignore' must be a boolean."); + } + if (!isArrayOfNonEmptyString(ignorePatterns) && ignorePatterns !== null) { + errors.push("'ignorePatterns' must be an array of non-empty strings or null."); + } + if (typeof overrideConfig !== "object") { + errors.push("'overrideConfig' must be an object or null."); + } + if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null && overrideConfigFile !== true) { + errors.push("'overrideConfigFile' must be a non-empty string, null, or true."); + } + if (typeof plugins !== "object") { + errors.push("'plugins' must be an object or null."); + } else if (plugins !== null && Object.keys(plugins).includes("")) { + errors.push("'plugins' must not include an empty string."); + } + if (Array.isArray(plugins)) { + errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead."); + } + if ( + reportUnusedDisableDirectives !== "error" && + reportUnusedDisableDirectives !== "warn" && + reportUnusedDisableDirectives !== "off" && + reportUnusedDisableDirectives !== null + ) { + errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null."); + } + if (errors.length > 0) { + throw new ESLintInvalidOptionsError(errors); + } + + return { + allowInlineConfig, + baseConfig, + cache, + cacheLocation, + cacheStrategy, + + // when overrideConfigFile is true that means don't do config file lookup + configFile: overrideConfigFile === true ? false : overrideConfigFile, + overrideConfig, + cwd: path.normalize(cwd), + errorOnUnmatchedPattern, + fix, + fixTypes, + globInputPaths, + ignore, + ignorePatterns, + reportUnusedDisableDirectives + }; +} + + +//----------------------------------------------------------------------------- +// Cache-related helpers +//----------------------------------------------------------------------------- + +/** + * return the cacheFile to be used by eslint, based on whether the provided parameter is + * a directory or looks like a directory (ends in `path.sep`), in which case the file + * name will be the `cacheFile/.cache_hashOfCWD` + * + * if cacheFile points to a file or looks like a file then in will just use that file + * @param {string} cacheFile The name of file to be used to store the cache + * @param {string} cwd Current working directory + * @returns {string} the resolved path to the cache file + */ +function getCacheFile(cacheFile, cwd) { + + /* + * make sure the path separators are normalized for the environment/os + * keeping the trailing path separator if present + */ + const normalizedCacheFile = path.normalize(cacheFile); + + const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile); + const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep; + + /** + * return the name for the cache file in case the provided parameter is a directory + * @returns {string} the resolved path to the cacheFile + */ + function getCacheFileForDirectory() { + return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`); + } + + let fileStats; + + try { + fileStats = fs.lstatSync(resolvedCacheFile); + } catch { + fileStats = null; + } + + + /* + * in case the file exists we need to verify if the provided path + * is a directory or a file. If it is a directory we want to create a file + * inside that directory + */ + if (fileStats) { + + /* + * is a directory or is a file, but the original file the user provided + * looks like a directory but `path.resolve` removed the `last path.sep` + * so we need to still treat this like a directory + */ + if (fileStats.isDirectory() || looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + // is file so just use that file + return resolvedCacheFile; + } + + /* + * here we known the file or directory doesn't exist, + * so we will try to infer if its a directory if it looks like a directory + * for the current operating system. + */ + + // if the last character passed is a path separator we assume is a directory + if (looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + return resolvedCacheFile; +} + + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + isGlobPattern, + findFiles, + + isNonEmptyString, + isArrayOfNonEmptyString, + + createIgnoreResult, + isErrorMessage, + + processOptions, + + getCacheFile +}; diff --git a/node_modules/eslint/lib/eslint/eslint.js b/node_modules/eslint/lib/eslint/eslint.js new file mode 100644 index 0000000..15e6b3d --- /dev/null +++ b/node_modules/eslint/lib/eslint/eslint.js @@ -0,0 +1,700 @@ +/** + * @fileoverview Main API Class + * @author Kai Cataldo + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("path"); +const fs = require("fs"); +const { promisify } = require("util"); +const { CLIEngine, getCLIEngineInternalSlots } = require("../cli-engine/cli-engine"); +const BuiltinRules = require("../rules"); +const { + Legacy: { + ConfigOps: { + getRuleSeverity + } + } +} = require("@eslint/eslintrc"); +const { version } = require("../../package.json"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */ +/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */ +/** @typedef {import("../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../shared/types").LintMessage} LintMessage */ +/** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */ +/** @typedef {import("../shared/types").Plugin} Plugin */ +/** @typedef {import("../shared/types").Rule} Rule */ +/** @typedef {import("../shared/types").LintResult} LintResult */ +/** @typedef {import("../shared/types").ResultsMeta} ResultsMeta */ + +/** + * The main formatter object. + * @typedef LoadedFormatter + * @property {(results: LintResult[], resultsMeta: ResultsMeta) => string | Promise} format format function. + */ + +/** + * The options with which to configure the ESLint instance. + * @typedef {Object} ESLintOptions + * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. + * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance + * @property {boolean} [cache] Enable result caching. + * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. + * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files. + * @property {string} [cwd] The value to use for the current working directory. + * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`. + * @property {string[]} [extensions] An array of file extensions to check. + * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. + * @property {string[]} [fixTypes] Array of rule types to apply fixes for. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] False disables use of .eslintignore. + * @property {string} [ignorePath] The ignore file to use instead of .eslintignore. + * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance + * @property {string} [overrideConfigFile] The configuration file to use. + * @property {Record|null} [plugins] Preloaded plugins. This is a map-like object, keys are plugin IDs and each value is implementation. + * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives. + * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD. + * @property {string[]} [rulePaths] An array of directories to load custom rules from. + * @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files. + */ + +/** + * A rules metadata object. + * @typedef {Object} RulesMeta + * @property {string} id The plugin ID. + * @property {Object} definition The plugin definition. + */ + +/** + * Private members for the `ESLint` instance. + * @typedef {Object} ESLintPrivateMembers + * @property {CLIEngine} cliEngine The wrapped CLIEngine instance. + * @property {ESLintOptions} options The options used to instantiate the ESLint instance. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const writeFile = promisify(fs.writeFile); + +/** + * The map with which to store private class members. + * @type {WeakMap} + */ +const privateMembersMap = new WeakMap(); + +/** + * Check if a given value is a non-empty string or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is a non-empty string. + */ +function isNonEmptyString(x) { + return typeof x === "string" && x.trim() !== ""; +} + +/** + * Check if a given value is an array of non-empty strings or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is an array of non-empty strings. + */ +function isArrayOfNonEmptyString(x) { + return Array.isArray(x) && x.every(isNonEmptyString); +} + +/** + * Check if a given value is a valid fix type or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is valid fix type. + */ +function isFixType(x) { + return x === "directive" || x === "problem" || x === "suggestion" || x === "layout"; +} + +/** + * Check if a given value is an array of fix types or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is an array of fix types. + */ +function isFixTypeArray(x) { + return Array.isArray(x) && x.every(isFixType); +} + +/** + * The error for invalid options. + */ +class ESLintInvalidOptionsError extends Error { + constructor(messages) { + super(`Invalid Options:\n- ${messages.join("\n- ")}`); + this.code = "ESLINT_INVALID_OPTIONS"; + Error.captureStackTrace(this, ESLintInvalidOptionsError); + } +} + +/** + * Validates and normalizes options for the wrapped CLIEngine instance. + * @param {ESLintOptions} options The options to process. + * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors. + * @returns {ESLintOptions} The normalized options. + */ +function processOptions({ + allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored. + baseConfig = null, + cache = false, + cacheLocation = ".eslintcache", + cacheStrategy = "metadata", + cwd = process.cwd(), + errorOnUnmatchedPattern = true, + extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature. + fix = false, + fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property. + globInputPaths = true, + ignore = true, + ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT. + overrideConfig = null, + overrideConfigFile = null, + plugins = {}, + reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that. + resolvePluginsRelativeTo = null, // ← should be null by default because if it's a string then it suppresses RFC47 feature. + rulePaths = [], + useEslintrc = true, + ...unknownOptions +}) { + const errors = []; + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length >= 1) { + errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`); + if (unknownOptionKeys.includes("cacheFile")) { + errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead."); + } + if (unknownOptionKeys.includes("configFile")) { + errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead."); + } + if (unknownOptionKeys.includes("envs")) { + errors.push("'envs' has been removed. Please use the 'overrideConfig.env' option instead."); + } + if (unknownOptionKeys.includes("globals")) { + errors.push("'globals' has been removed. Please use the 'overrideConfig.globals' option instead."); + } + if (unknownOptionKeys.includes("ignorePattern")) { + errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead."); + } + if (unknownOptionKeys.includes("parser")) { + errors.push("'parser' has been removed. Please use the 'overrideConfig.parser' option instead."); + } + if (unknownOptionKeys.includes("parserOptions")) { + errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead."); + } + if (unknownOptionKeys.includes("rules")) { + errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead."); + } + } + if (typeof allowInlineConfig !== "boolean") { + errors.push("'allowInlineConfig' must be a boolean."); + } + if (typeof baseConfig !== "object") { + errors.push("'baseConfig' must be an object or null."); + } + if (typeof cache !== "boolean") { + errors.push("'cache' must be a boolean."); + } + if (!isNonEmptyString(cacheLocation)) { + errors.push("'cacheLocation' must be a non-empty string."); + } + if ( + cacheStrategy !== "metadata" && + cacheStrategy !== "content" + ) { + errors.push("'cacheStrategy' must be any of \"metadata\", \"content\"."); + } + if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) { + errors.push("'cwd' must be an absolute path."); + } + if (typeof errorOnUnmatchedPattern !== "boolean") { + errors.push("'errorOnUnmatchedPattern' must be a boolean."); + } + if (!isArrayOfNonEmptyString(extensions) && extensions !== null) { + errors.push("'extensions' must be an array of non-empty strings or null."); + } + if (typeof fix !== "boolean" && typeof fix !== "function") { + errors.push("'fix' must be a boolean or a function."); + } + if (fixTypes !== null && !isFixTypeArray(fixTypes)) { + errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\"."); + } + if (typeof globInputPaths !== "boolean") { + errors.push("'globInputPaths' must be a boolean."); + } + if (typeof ignore !== "boolean") { + errors.push("'ignore' must be a boolean."); + } + if (!isNonEmptyString(ignorePath) && ignorePath !== null) { + errors.push("'ignorePath' must be a non-empty string or null."); + } + if (typeof overrideConfig !== "object") { + errors.push("'overrideConfig' must be an object or null."); + } + if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) { + errors.push("'overrideConfigFile' must be a non-empty string or null."); + } + if (typeof plugins !== "object") { + errors.push("'plugins' must be an object or null."); + } else if (plugins !== null && Object.keys(plugins).includes("")) { + errors.push("'plugins' must not include an empty string."); + } + if (Array.isArray(plugins)) { + errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead."); + } + if ( + reportUnusedDisableDirectives !== "error" && + reportUnusedDisableDirectives !== "warn" && + reportUnusedDisableDirectives !== "off" && + reportUnusedDisableDirectives !== null + ) { + errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null."); + } + if ( + !isNonEmptyString(resolvePluginsRelativeTo) && + resolvePluginsRelativeTo !== null + ) { + errors.push("'resolvePluginsRelativeTo' must be a non-empty string or null."); + } + if (!isArrayOfNonEmptyString(rulePaths)) { + errors.push("'rulePaths' must be an array of non-empty strings."); + } + if (typeof useEslintrc !== "boolean") { + errors.push("'useEslintrc' must be a boolean."); + } + + if (errors.length > 0) { + throw new ESLintInvalidOptionsError(errors); + } + + return { + allowInlineConfig, + baseConfig, + cache, + cacheLocation, + cacheStrategy, + configFile: overrideConfigFile, + cwd: path.normalize(cwd), + errorOnUnmatchedPattern, + extensions, + fix, + fixTypes, + globInputPaths, + ignore, + ignorePath, + reportUnusedDisableDirectives, + resolvePluginsRelativeTo, + rulePaths, + useEslintrc + }; +} + +/** + * Check if a value has one or more properties and that value is not undefined. + * @param {any} obj The value to check. + * @returns {boolean} `true` if `obj` has one or more properties that that value is not undefined. + */ +function hasDefinedProperty(obj) { + if (typeof obj === "object" && obj !== null) { + for (const key in obj) { + if (typeof obj[key] !== "undefined") { + return true; + } + } + } + return false; +} + +/** + * Create rulesMeta object. + * @param {Map} rules a map of rules from which to generate the object. + * @returns {Object} metadata for all enabled rules. + */ +function createRulesMeta(rules) { + return Array.from(rules).reduce((retVal, [id, rule]) => { + retVal[id] = rule.meta; + return retVal; + }, {}); +} + +/** @type {WeakMap} */ +const usedDeprecatedRulesCache = new WeakMap(); + +/** + * Create used deprecated rule list. + * @param {CLIEngine} cliEngine The CLIEngine instance. + * @param {string} maybeFilePath The absolute path to a lint target file or `""`. + * @returns {DeprecatedRuleInfo[]} The used deprecated rule list. + */ +function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) { + const { + configArrayFactory, + options: { cwd } + } = getCLIEngineInternalSlots(cliEngine); + const filePath = path.isAbsolute(maybeFilePath) + ? maybeFilePath + : path.join(cwd, "__placeholder__.js"); + const configArray = configArrayFactory.getConfigArrayForFile(filePath); + const config = configArray.extractConfig(filePath); + + // Most files use the same config, so cache it. + if (!usedDeprecatedRulesCache.has(config)) { + const pluginRules = configArray.pluginRules; + const retv = []; + + for (const [ruleId, ruleConf] of Object.entries(config.rules)) { + if (getRuleSeverity(ruleConf) === 0) { + continue; + } + const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId); + const meta = rule && rule.meta; + + if (meta && meta.deprecated) { + retv.push({ ruleId, replacedBy: meta.replacedBy || [] }); + } + } + + usedDeprecatedRulesCache.set(config, Object.freeze(retv)); + } + + return usedDeprecatedRulesCache.get(config); +} + +/** + * Processes the linting results generated by a CLIEngine linting report to + * match the ESLint class's API. + * @param {CLIEngine} cliEngine The CLIEngine instance. + * @param {CLIEngineLintReport} report The CLIEngine linting report to process. + * @returns {LintResult[]} The processed linting results. + */ +function processCLIEngineLintReport(cliEngine, { results }) { + const descriptor = { + configurable: true, + enumerable: true, + get() { + return getOrFindUsedDeprecatedRules(cliEngine, this.filePath); + } + }; + + for (const result of results) { + Object.defineProperty(result, "usedDeprecatedRules", descriptor); + } + + return results; +} + +/** + * An Array.prototype.sort() compatible compare function to order results by their file path. + * @param {LintResult} a The first lint result. + * @param {LintResult} b The second lint result. + * @returns {number} An integer representing the order in which the two results should occur. + */ +function compareResultsByFilePath(a, b) { + if (a.filePath < b.filePath) { + return -1; + } + + if (a.filePath > b.filePath) { + return 1; + } + + return 0; +} + +/** + * Main API. + */ +class ESLint { + + /** + * Creates a new instance of the main ESLint API. + * @param {ESLintOptions} options The options for this instance. + */ + constructor(options = {}) { + const processedOptions = processOptions(options); + const cliEngine = new CLIEngine(processedOptions, { preloadedPlugins: options.plugins }); + const { + configArrayFactory, + lastConfigArrays + } = getCLIEngineInternalSlots(cliEngine); + let updated = false; + + /* + * Address `overrideConfig` to set override config. + * Operate the `configArrayFactory` internal slot directly because this + * functionality doesn't exist as the public API of CLIEngine. + */ + if (hasDefinedProperty(options.overrideConfig)) { + configArrayFactory.setOverrideConfig(options.overrideConfig); + updated = true; + } + + // Update caches. + if (updated) { + configArrayFactory.clearCache(); + lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile(); + } + + // Initialize private properties. + privateMembersMap.set(this, { + cliEngine, + options: processedOptions + }); + } + + /** + * The version text. + * @type {string} + */ + static get version() { + return version; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintResult[]} results The lint results. + * @returns {Promise} Returns a promise that is used to track side effects. + */ + static async outputFixes(results) { + if (!Array.isArray(results)) { + throw new Error("'results' must be an array"); + } + + await Promise.all( + results + .filter(result => { + if (typeof result !== "object" || result === null) { + throw new Error("'results' must include only objects"); + } + return ( + typeof result.output === "string" && + path.isAbsolute(result.filePath) + ); + }) + .map(r => writeFile(r.filePath, r.output)) + ); + } + + /** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ + static getErrorResults(results) { + return CLIEngine.getErrorResults(results); + } + + /** + * Returns meta objects for each rule represented in the lint results. + * @param {LintResult[]} results The results to fetch rules meta for. + * @returns {Object} A mapping of ruleIds to rule meta objects. + */ + getRulesMetaForResults(results) { + + const resultRuleIds = new Set(); + + // first gather all ruleIds from all results + + for (const result of results) { + for (const { ruleId } of result.messages) { + resultRuleIds.add(ruleId); + } + for (const { ruleId } of result.suppressedMessages) { + resultRuleIds.add(ruleId); + } + } + + // create a map of all rules in the results + + const { cliEngine } = privateMembersMap.get(this); + const rules = cliEngine.getRules(); + const resultRules = new Map(); + + for (const [ruleId, rule] of rules) { + if (resultRuleIds.has(ruleId)) { + resultRules.set(ruleId, rule); + } + } + + return createRulesMeta(resultRules); + + } + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string[]} patterns An array of file and directory names. + * @returns {Promise} The results of linting the file patterns given. + */ + async lintFiles(patterns) { + if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) { + throw new Error("'patterns' must be a non-empty string or an array of non-empty strings"); + } + const { cliEngine } = privateMembersMap.get(this); + + return processCLIEngineLintReport( + cliEngine, + cliEngine.executeOnFiles(patterns) + ); + } + + /** + * Executes the current configuration on text. + * @param {string} code A string of JavaScript code to lint. + * @param {Object} [options] The options. + * @param {string} [options.filePath] The path to the file of the source code. + * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path. + * @returns {Promise} The results of linting the string of code given. + */ + async lintText(code, options = {}) { + if (typeof code !== "string") { + throw new Error("'code' must be a string"); + } + if (typeof options !== "object") { + throw new Error("'options' must be an object, null, or undefined"); + } + const { + filePath, + warnIgnored = false, + ...unknownOptions + } = options || {}; + + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length > 0) { + throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`); + } + + if (filePath !== void 0 && !isNonEmptyString(filePath)) { + throw new Error("'options.filePath' must be a non-empty string or undefined"); + } + if (typeof warnIgnored !== "boolean") { + throw new Error("'options.warnIgnored' must be a boolean or undefined"); + } + + const { cliEngine } = privateMembersMap.get(this); + + return processCLIEngineLintReport( + cliEngine, + cliEngine.executeOnText(code, filePath, warnIgnored) + ); + } + + /** + * Returns the formatter representing the given formatter name. + * @param {string} [name] The name of the formatter to load. + * The following values are allowed: + * - `undefined` ... Load `stylish` builtin formatter. + * - A builtin formatter name ... Load the builtin formatter. + * - A third-party formatter name: + * - `foo` → `eslint-formatter-foo` + * - `@foo` → `@foo/eslint-formatter` + * - `@foo/bar` → `@foo/eslint-formatter-bar` + * - A file path ... Load the file. + * @returns {Promise} A promise resolving to the formatter object. + * This promise will be rejected if the given formatter was not found or not + * a function. + */ + async loadFormatter(name = "stylish") { + if (typeof name !== "string") { + throw new Error("'name' must be a string"); + } + + const { cliEngine, options } = privateMembersMap.get(this); + const formatter = cliEngine.getFormatter(name); + + if (typeof formatter !== "function") { + throw new Error(`Formatter must be a function, but got a ${typeof formatter}.`); + } + + return { + + /** + * The main formatter method. + * @param {LintResult[]} results The lint results to format. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {string | Promise} The formatted lint results. + */ + format(results, resultsMeta) { + let rulesMeta = null; + + results.sort(compareResultsByFilePath); + + return formatter(results, { + ...resultsMeta, + get cwd() { + return options.cwd; + }, + get rulesMeta() { + if (!rulesMeta) { + rulesMeta = createRulesMeta(cliEngine.getRules()); + } + + return rulesMeta; + } + }); + } + }; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {Promise} A configuration object for the file. + */ + async calculateConfigForFile(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const { cliEngine } = privateMembersMap.get(this); + + return cliEngine.getConfigForFile(filePath); + } + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {Promise} Whether or not the given path is ignored. + */ + async isPathIgnored(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const { cliEngine } = privateMembersMap.get(this); + + return cliEngine.isPathIgnored(filePath); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + ESLint, + + /** + * Get the private class members of a given ESLint instance for tests. + * @param {ESLint} instance The ESLint instance to get. + * @returns {ESLintPrivateMembers} The instance's private class members. + */ + getESLintPrivateMembers(instance) { + return privateMembersMap.get(instance); + } +}; diff --git a/node_modules/eslint/lib/eslint/flat-eslint.js b/node_modules/eslint/lib/eslint/flat-eslint.js new file mode 100644 index 0000000..4ef3861 --- /dev/null +++ b/node_modules/eslint/lib/eslint/flat-eslint.js @@ -0,0 +1,1140 @@ +/** + * @fileoverview Main class using flat config + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// Note: Node.js 12 does not support fs/promises. +const fs = require("fs").promises; +const path = require("path"); +const findUp = require("find-up"); +const { version } = require("../../package.json"); +const { Linter } = require("../linter"); +const { getRuleFromConfig } = require("../config/flat-config-helpers"); +const { + Legacy: { + ConfigOps: { + getRuleSeverity + }, + ModuleResolver, + naming + } +} = require("@eslint/eslintrc"); + +const { + findFiles, + getCacheFile, + + isNonEmptyString, + isArrayOfNonEmptyString, + + createIgnoreResult, + isErrorMessage, + + processOptions +} = require("./eslint-helpers"); +const { pathToFileURL } = require("url"); +const { FlatConfigArray } = require("../config/flat-config-array"); +const LintResultCache = require("../cli-engine/lint-result-cache"); + +/* + * This is necessary to allow overwriting writeFile for testing purposes. + * We can just use fs/promises once we drop Node.js 12 support. + */ + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +// For VSCode IntelliSense +/** @typedef {import("../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */ +/** @typedef {import("../shared/types").LintMessage} LintMessage */ +/** @typedef {import("../shared/types").LintResult} LintResult */ +/** @typedef {import("../shared/types").ParserOptions} ParserOptions */ +/** @typedef {import("../shared/types").Plugin} Plugin */ +/** @typedef {import("../shared/types").ResultsMeta} ResultsMeta */ +/** @typedef {import("../shared/types").RuleConf} RuleConf */ +/** @typedef {import("../shared/types").Rule} Rule */ +/** @typedef {ReturnType} ExtractedConfig */ + +/** + * The options with which to configure the ESLint instance. + * @typedef {Object} FlatESLintOptions + * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. + * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance + * @property {boolean} [cache] Enable result caching. + * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. + * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files. + * @property {string} [cwd] The value to use for the current working directory. + * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`. + * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. + * @property {string[]} [fixTypes] Array of rule types to apply fixes for. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] False disables all ignore patterns except for the default ones. + * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to config ignores. These patterns are relative to `cwd`. + * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance + * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy; + * doesn't do any config file lookup when `true`; considered to be a config filename + * when a string. + * @property {Record} [plugins] An array of plugin implementations. + * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const FLAT_CONFIG_FILENAME = "eslint.config.js"; +const debug = require("debug")("eslint:flat-eslint"); +const removedFormatters = new Set(["table", "codeframe"]); +const privateMembers = new WeakMap(); +const importedConfigFileModificationTime = new Map(); + +/** + * It will calculate the error and warning count for collection of messages per file + * @param {LintMessage[]} messages Collection of messages + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerFile(messages) { + const stat = { + errorCount: 0, + fatalErrorCount: 0, + warningCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0 + }; + + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + + if (message.fatal || message.severity === 2) { + stat.errorCount++; + if (message.fatal) { + stat.fatalErrorCount++; + } + if (message.fix) { + stat.fixableErrorCount++; + } + } else { + stat.warningCount++; + if (message.fix) { + stat.fixableWarningCount++; + } + } + } + return stat; +} + +/** + * Create rulesMeta object. + * @param {Map} rules a map of rules from which to generate the object. + * @returns {Object} metadata for all enabled rules. + */ +function createRulesMeta(rules) { + return Array.from(rules).reduce((retVal, [id, rule]) => { + retVal[id] = rule.meta; + return retVal; + }, {}); +} + +/** + * Return the absolute path of a file named `"__placeholder__.js"` in a given directory. + * This is used as a replacement for a missing file path. + * @param {string} cwd An absolute directory path. + * @returns {string} The absolute path of a file named `"__placeholder__.js"` in the given directory. + */ +function getPlaceholderPath(cwd) { + return path.join(cwd, "__placeholder__.js"); +} + +/** @type {WeakMap} */ +const usedDeprecatedRulesCache = new WeakMap(); + +/** + * Create used deprecated rule list. + * @param {CLIEngine} eslint The CLIEngine instance. + * @param {string} maybeFilePath The absolute path to a lint target file or `""`. + * @returns {DeprecatedRuleInfo[]} The used deprecated rule list. + */ +function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) { + const { + configs, + options: { cwd } + } = privateMembers.get(eslint); + const filePath = path.isAbsolute(maybeFilePath) + ? maybeFilePath + : getPlaceholderPath(cwd); + const config = configs.getConfig(filePath); + + // Most files use the same config, so cache it. + if (config && !usedDeprecatedRulesCache.has(config)) { + const retv = []; + + if (config.rules) { + for (const [ruleId, ruleConf] of Object.entries(config.rules)) { + if (getRuleSeverity(ruleConf) === 0) { + continue; + } + const rule = getRuleFromConfig(ruleId, config); + const meta = rule && rule.meta; + + if (meta && meta.deprecated) { + retv.push({ ruleId, replacedBy: meta.replacedBy || [] }); + } + } + } + + + usedDeprecatedRulesCache.set(config, Object.freeze(retv)); + } + + return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]); +} + +/** + * Processes the linting results generated by a CLIEngine linting report to + * match the ESLint class's API. + * @param {CLIEngine} eslint The CLIEngine instance. + * @param {CLIEngineLintReport} report The CLIEngine linting report to process. + * @returns {LintResult[]} The processed linting results. + */ +function processLintReport(eslint, { results }) { + const descriptor = { + configurable: true, + enumerable: true, + get() { + return getOrFindUsedDeprecatedRules(eslint, this.filePath); + } + }; + + for (const result of results) { + Object.defineProperty(result, "usedDeprecatedRules", descriptor); + } + + return results; +} + +/** + * An Array.prototype.sort() compatible compare function to order results by their file path. + * @param {LintResult} a The first lint result. + * @param {LintResult} b The second lint result. + * @returns {number} An integer representing the order in which the two results should occur. + */ +function compareResultsByFilePath(a, b) { + if (a.filePath < b.filePath) { + return -1; + } + + if (a.filePath > b.filePath) { + return 1; + } + + return 0; +} + +/** + * Searches from the current working directory up until finding the + * given flat config filename. + * @param {string} cwd The current working directory to search from. + * @returns {Promise} The filename if found or `undefined` if not. + */ +function findFlatConfigFile(cwd) { + return findUp( + FLAT_CONFIG_FILENAME, + { cwd } + ); +} + +/** + * Load the config array from the given filename. + * @param {string} filePath The filename to load from. + * @returns {Promise} The config loaded from the config file. + */ +async function loadFlatConfigFile(filePath) { + debug(`Loading config from ${filePath}`); + + const fileURL = pathToFileURL(filePath); + + debug(`Config file URL is ${fileURL}`); + + const mtime = (await fs.stat(filePath)).mtime.getTime(); + + /* + * Append a query with the config file's modification time (`mtime`) in order + * to import the current version of the config file. Without the query, `import()` would + * cache the config file module by the pathname only, and then always return + * the same version (the one that was actual when the module was imported for the first time). + * + * This ensures that the config file module is loaded and executed again + * if it has been changed since the last time it was imported. + * If it hasn't been changed, `import()` will just return the cached version. + * + * Note that we should not overuse queries (e.g., by appending the current time + * to always reload the config file module) as that could cause memory leaks + * because entries are never removed from the import cache. + */ + fileURL.searchParams.append("mtime", mtime); + + /* + * With queries, we can bypass the import cache. However, when import-ing a CJS module, + * Node.js uses the require infrastructure under the hood. That includes the require cache, + * which caches the config file module by its file path (queries have no effect). + * Therefore, we also need to clear the require cache before importing the config file module. + * In order to get the same behavior with ESM and CJS config files, in particular - to reload + * the config file only if it has been changed, we track file modification times and clear + * the require cache only if the file has been changed. + */ + if (importedConfigFileModificationTime.get(filePath) !== mtime) { + delete require.cache[filePath]; + } + + const config = (await import(fileURL)).default; + + importedConfigFileModificationTime.set(filePath, mtime); + + return config; +} + +/** + * Determines which config file to use. This is determined by seeing if an + * override config file was passed, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from the cwd for a file named `eslint.config.js`. + * @param {import("./eslint").ESLintOptions} options The ESLint instance options. + * @returns {{configFilePath:string|undefined,basePath:string,error:Error|null}} Location information for + * the config file. + */ +async function locateConfigFileToUse({ configFile, cwd }) { + + // determine where to load config file from + let configFilePath; + let basePath = cwd; + let error = null; + + if (typeof configFile === "string") { + debug(`Override config file path is ${configFile}`); + configFilePath = path.resolve(cwd, configFile); + } else if (configFile !== false) { + debug("Searching for eslint.config.js"); + configFilePath = await findFlatConfigFile(cwd); + + if (configFilePath) { + basePath = path.resolve(path.dirname(configFilePath)); + } else { + error = new Error("Could not find config file."); + } + + } + + return { + configFilePath, + basePath, + error + }; + +} + +/** + * Calculates the config array for this run based on inputs. + * @param {FlatESLint} eslint The instance to create the config array for. + * @param {import("./eslint").ESLintOptions} options The ESLint instance options. + * @returns {FlatConfigArray} The config array for `eslint``. + */ +async function calculateConfigArray(eslint, { + cwd, + baseConfig, + overrideConfig, + configFile, + ignore: shouldIgnore, + ignorePatterns +}) { + + // check for cached instance + const slots = privateMembers.get(eslint); + + if (slots.configs) { + return slots.configs; + } + + const { configFilePath, basePath, error } = await locateConfigFileToUse({ configFile, cwd }); + + // config file is required to calculate config + if (error) { + throw error; + } + + const configs = new FlatConfigArray(baseConfig || [], { basePath, shouldIgnore }); + + // load config file + if (configFilePath) { + const fileConfig = await loadFlatConfigFile(configFilePath); + + if (Array.isArray(fileConfig)) { + configs.push(...fileConfig); + } else { + configs.push(fileConfig); + } + } + + // add in any configured defaults + configs.push(...slots.defaultConfigs); + + // append command line ignore patterns + if (ignorePatterns && ignorePatterns.length > 0) { + + let relativeIgnorePatterns; + + /* + * If the config file basePath is different than the cwd, then + * the ignore patterns won't work correctly. Here, we adjust the + * ignore pattern to include the correct relative path. Patterns + * passed as `ignorePatterns` are relative to the cwd, whereas + * the config file basePath can be an ancestor of the cwd. + */ + if (basePath === cwd) { + relativeIgnorePatterns = ignorePatterns; + } else { + + const relativeIgnorePath = path.relative(basePath, cwd); + + relativeIgnorePatterns = ignorePatterns.map(pattern => { + const negated = pattern.startsWith("!"); + const basePattern = negated ? pattern.slice(1) : pattern; + + return (negated ? "!" : "") + + path.posix.join(relativeIgnorePath, basePattern); + }); + } + + /* + * Ignore patterns are added to the end of the config array + * so they can override default ignores. + */ + configs.push({ + ignores: relativeIgnorePatterns + }); + } + + if (overrideConfig) { + if (Array.isArray(overrideConfig)) { + configs.push(...overrideConfig); + } else { + configs.push(overrideConfig); + } + } + + await configs.normalize(); + + // cache the config array for this instance + slots.configs = configs; + + return configs; +} + +/** + * Processes an source code using ESLint. + * @param {Object} config The config object. + * @param {string} config.text The source code to verify. + * @param {string} config.cwd The path to the current working directory. + * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses ``. + * @param {FlatConfigArray} config.configs The config. + * @param {boolean} config.fix If `true` then it does fix. + * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments. + * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments. + * @param {Linter} config.linter The linter instance to verify. + * @returns {LintResult} The result of linting. + * @private + */ +function verifyText({ + text, + cwd, + filePath: providedFilePath, + configs, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + linter +}) { + const filePath = providedFilePath || ""; + + debug(`Lint ${filePath}`); + + /* + * Verify. + * `config.extractConfig(filePath)` requires an absolute path, but `linter` + * doesn't know CWD, so it gives `linter` an absolute path always. + */ + const filePathToVerify = filePath === "" ? getPlaceholderPath(cwd) : filePath; + const { fixed, messages, output } = linter.verifyAndFix( + text, + configs, + { + allowInlineConfig, + filename: filePathToVerify, + fix, + reportUnusedDisableDirectives, + + /** + * Check if the linter should adopt a given code block or not. + * @param {string} blockFilename The virtual filename of a code block. + * @returns {boolean} `true` if the linter should adopt the code block. + */ + filterCodeBlock(blockFilename) { + return configs.isExplicitMatch(blockFilename); + } + } + ); + + // Tweak and return. + const result = { + filePath: filePath === "" ? filePath : path.resolve(filePath), + messages, + suppressedMessages: linter.getSuppressedMessages(), + ...calculateStatsPerFile(messages) + }; + + if (fixed) { + result.output = output; + } + + if ( + result.errorCount + result.warningCount > 0 && + typeof result.output === "undefined" + ) { + result.source = text; + } + + return result; +} + +/** + * Checks whether a message's rule type should be fixed. + * @param {LintMessage} message The message to check. + * @param {FlatConfig} config The config for the file that generated the message. + * @param {string[]} fixTypes An array of fix types to check. + * @returns {boolean} Whether the message should be fixed. + */ +function shouldMessageBeFixed(message, config, fixTypes) { + if (!message.ruleId) { + return fixTypes.has("directive"); + } + + const rule = message.ruleId && getRuleFromConfig(message.ruleId, config); + + return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type)); +} + +/** + * Creates an error to be thrown when an array of results passed to `getRulesMetaForResults` was not created by the current engine. + * @returns {TypeError} An error object. + */ +function createExtraneousResultsError() { + return new TypeError("Results object was not created from this ESLint instance."); +} + +//----------------------------------------------------------------------------- +// Main API +//----------------------------------------------------------------------------- + +/** + * Primary Node.js API for ESLint. + */ +class FlatESLint { + + /** + * Creates a new instance of the main ESLint API. + * @param {FlatESLintOptions} options The options for this instance. + */ + constructor(options = {}) { + + const defaultConfigs = []; + const processedOptions = processOptions(options); + const linter = new Linter({ + cwd: processedOptions.cwd, + configType: "flat" + }); + + const cacheFilePath = getCacheFile( + processedOptions.cacheLocation, + processedOptions.cwd + ); + + const lintResultCache = processedOptions.cache + ? new LintResultCache(cacheFilePath, processedOptions.cacheStrategy) + : null; + + privateMembers.set(this, { + options: processedOptions, + linter, + cacheFilePath, + lintResultCache, + defaultConfigs, + configs: null + }); + + /** + * If additional plugins are passed in, add that to the default + * configs for this instance. + */ + if (options.plugins) { + + const plugins = {}; + + for (const [pluginName, plugin] of Object.entries(options.plugins)) { + plugins[naming.getShorthandName(pluginName, "eslint-plugin")] = plugin; + } + + defaultConfigs.push({ + plugins + }); + } + + } + + /** + * The version text. + * @type {string} + */ + static get version() { + return version; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintResult[]} results The lint results. + * @returns {Promise} Returns a promise that is used to track side effects. + */ + static async outputFixes(results) { + if (!Array.isArray(results)) { + throw new Error("'results' must be an array"); + } + + await Promise.all( + results + .filter(result => { + if (typeof result !== "object" || result === null) { + throw new Error("'results' must include only objects"); + } + return ( + typeof result.output === "string" && + path.isAbsolute(result.filePath) + ); + }) + .map(r => fs.writeFile(r.filePath, r.output)) + ); + } + + /** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ + static getErrorResults(results) { + const filtered = []; + + results.forEach(result => { + const filteredMessages = result.messages.filter(isErrorMessage); + const filteredSuppressedMessages = result.suppressedMessages.filter(isErrorMessage); + + if (filteredMessages.length > 0) { + filtered.push({ + ...result, + messages: filteredMessages, + suppressedMessages: filteredSuppressedMessages, + errorCount: filteredMessages.length, + warningCount: 0, + fixableErrorCount: result.fixableErrorCount, + fixableWarningCount: 0 + }); + } + }); + + return filtered; + } + + /** + * Returns meta objects for each rule represented in the lint results. + * @param {LintResult[]} results The results to fetch rules meta for. + * @returns {Object} A mapping of ruleIds to rule meta objects. + * @throws {TypeError} When the results object wasn't created from this ESLint instance. + * @throws {TypeError} When a plugin or rule is missing. + */ + getRulesMetaForResults(results) { + + // short-circuit simple case + if (results.length === 0) { + return {}; + } + + const resultRules = new Map(); + const { + configs, + options: { cwd } + } = privateMembers.get(this); + + /* + * We can only accurately return rules meta information for linting results if the + * results were created by this instance. Otherwise, the necessary rules data is + * not available. So if the config array doesn't already exist, just throw an error + * to let the user know we can't do anything here. + */ + if (!configs) { + throw createExtraneousResultsError(); + } + + for (const result of results) { + + /* + * Normalize filename for . + */ + const filePath = result.filePath === "" + ? getPlaceholderPath(cwd) : result.filePath; + const allMessages = result.messages.concat(result.suppressedMessages); + + for (const { ruleId } of allMessages) { + if (!ruleId) { + continue; + } + + /* + * All of the plugin and rule information is contained within the + * calculated config for the given file. + */ + const config = configs.getConfig(filePath); + + if (!config) { + throw createExtraneousResultsError(); + } + const rule = getRuleFromConfig(ruleId, config); + + // ignore unknown rules + if (rule) { + resultRules.set(ruleId, rule); + } + } + } + + return createRulesMeta(resultRules); + } + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string|string[]} patterns An array of file and directory names. + * @returns {Promise} The results of linting the file patterns given. + */ + async lintFiles(patterns) { + if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) { + throw new Error("'patterns' must be a non-empty string or an array of non-empty strings"); + } + + const { + cacheFilePath, + lintResultCache, + linter, + options: eslintOptions + } = privateMembers.get(this); + const configs = await calculateConfigArray(this, eslintOptions); + const { + allowInlineConfig, + cache, + cwd, + fix, + fixTypes, + reportUnusedDisableDirectives, + globInputPaths, + errorOnUnmatchedPattern + } = eslintOptions; + const startTime = Date.now(); + const fixTypesSet = fixTypes ? new Set(fixTypes) : null; + + // Delete cache file; should this be done here? + if (!cache && cacheFilePath) { + debug(`Deleting cache file at ${cacheFilePath}`); + + try { + await fs.unlink(cacheFilePath); + } catch (error) { + const errorCode = error && error.code; + + // Ignore errors when no such file exists or file system is read only (and cache file does not exist) + if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !(await fs.exists(cacheFilePath)))) { + throw error; + } + } + } + + const filePaths = await findFiles({ + patterns: typeof patterns === "string" ? [patterns] : patterns, + cwd, + globInputPaths, + configs, + errorOnUnmatchedPattern + }); + + debug(`${filePaths.length} files found in: ${Date.now() - startTime}ms`); + + /* + * Because we need to process multiple files, including reading from disk, + * it is most efficient to start by reading each file via promises so that + * they can be done in parallel. Then, we can lint the returned text. This + * ensures we are waiting the minimum amount of time in between lints. + */ + const results = await Promise.all( + + filePaths.map(({ filePath, ignored }) => { + + /* + * If a filename was entered that matches an ignore + * pattern, then notify the user. + */ + if (ignored) { + return createIgnoreResult(filePath, cwd); + } + + const config = configs.getConfig(filePath); + + /* + * Sometimes a file found through a glob pattern will + * be ignored. In this case, `config` will be undefined + * and we just silently ignore the file. + */ + if (!config) { + return void 0; + } + + // Skip if there is cached result. + if (lintResultCache) { + const cachedResult = + lintResultCache.getCachedLintResults(filePath, config); + + if (cachedResult) { + const hadMessages = + cachedResult.messages && + cachedResult.messages.length > 0; + + if (hadMessages && fix) { + debug(`Reprocessing cached file to allow autofix: ${filePath}`); + } else { + debug(`Skipping file since it hasn't changed: ${filePath}`); + return cachedResult; + } + } + } + + + // set up fixer for fixTypes if necessary + let fixer = fix; + + if (fix && fixTypesSet) { + + // save original value of options.fix in case it's a function + const originalFix = (typeof fix === "function") + ? fix : () => true; + + fixer = message => shouldMessageBeFixed(message, config, fixTypesSet) && originalFix(message); + } + + return fs.readFile(filePath, "utf8") + .then(text => { + + // do the linting + const result = verifyText({ + text, + filePath, + configs, + cwd, + fix: fixer, + allowInlineConfig, + reportUnusedDisableDirectives, + linter + }); + + /* + * Store the lint result in the LintResultCache. + * NOTE: The LintResultCache will remove the file source and any + * other properties that are difficult to serialize, and will + * hydrate those properties back in on future lint runs. + */ + if (lintResultCache) { + lintResultCache.setCachedLintResults(filePath, config, result); + } + + return result; + }); + + }) + ); + + // Persist the cache to disk. + if (lintResultCache) { + lintResultCache.reconcile(); + } + + const finalResults = results.filter(result => !!result); + + return processLintReport(this, { + results: finalResults + }); + } + + /** + * Executes the current configuration on text. + * @param {string} code A string of JavaScript code to lint. + * @param {Object} [options] The options. + * @param {string} [options.filePath] The path to the file of the source code. + * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path. + * @returns {Promise} The results of linting the string of code given. + */ + async lintText(code, options = {}) { + + // Parameter validation + + if (typeof code !== "string") { + throw new Error("'code' must be a string"); + } + + if (typeof options !== "object") { + throw new Error("'options' must be an object, null, or undefined"); + } + + // Options validation + + const { + filePath, + warnIgnored = false, + ...unknownOptions + } = options || {}; + + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length > 0) { + throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`); + } + + if (filePath !== void 0 && !isNonEmptyString(filePath)) { + throw new Error("'options.filePath' must be a non-empty string or undefined"); + } + + if (typeof warnIgnored !== "boolean") { + throw new Error("'options.warnIgnored' must be a boolean or undefined"); + } + + // Now we can get down to linting + + const { + linter, + options: eslintOptions + } = privateMembers.get(this); + const configs = await calculateConfigArray(this, eslintOptions); + const { + allowInlineConfig, + cwd, + fix, + reportUnusedDisableDirectives + } = eslintOptions; + const results = []; + const startTime = Date.now(); + const resolvedFilename = path.resolve(cwd, filePath || "__placeholder__.js"); + + // Clear the last used config arrays. + if (resolvedFilename && await this.isPathIgnored(resolvedFilename)) { + if (warnIgnored) { + results.push(createIgnoreResult(resolvedFilename, cwd)); + } + } else { + + // Do lint. + results.push(verifyText({ + text: code, + filePath: resolvedFilename.endsWith("__placeholder__.js") ? "" : resolvedFilename, + configs, + cwd, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + linter + })); + } + + debug(`Linting complete in: ${Date.now() - startTime}ms`); + + return processLintReport(this, { + results + }); + + } + + /** + * Returns the formatter representing the given formatter name. + * @param {string} [name] The name of the formatter to load. + * The following values are allowed: + * - `undefined` ... Load `stylish` builtin formatter. + * - A builtin formatter name ... Load the builtin formatter. + * - A third-party formatter name: + * - `foo` → `eslint-formatter-foo` + * - `@foo` → `@foo/eslint-formatter` + * - `@foo/bar` → `@foo/eslint-formatter-bar` + * - A file path ... Load the file. + * @returns {Promise} A promise resolving to the formatter object. + * This promise will be rejected if the given formatter was not found or not + * a function. + */ + async loadFormatter(name = "stylish") { + if (typeof name !== "string") { + throw new Error("'name' must be a string"); + } + + // replace \ with / for Windows compatibility + const normalizedFormatName = name.replace(/\\/gu, "/"); + const namespace = naming.getNamespaceFromTerm(normalizedFormatName); + + // grab our options + const { cwd } = privateMembers.get(this).options; + + + let formatterPath; + + // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages) + if (!namespace && normalizedFormatName.includes("/")) { + formatterPath = path.resolve(cwd, normalizedFormatName); + } else { + try { + const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter"); + + // TODO: This is pretty dirty...would be nice to clean up at some point. + formatterPath = ModuleResolver.resolve(npmFormat, getPlaceholderPath(cwd)); + } catch { + formatterPath = path.resolve(__dirname, "../", "cli-engine", "formatters", `${normalizedFormatName}.js`); + } + } + + let formatter; + + try { + formatter = (await import(pathToFileURL(formatterPath))).default; + } catch (ex) { + + // check for formatters that have been removed + if (removedFormatters.has(name)) { + ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``; + } else { + ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`; + } + + throw ex; + } + + + if (typeof formatter !== "function") { + throw new TypeError(`Formatter must be a function, but got a ${typeof formatter}.`); + } + + const eslint = this; + + return { + + /** + * The main formatter method. + * @param {LintResults[]} results The lint results to format. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {string} The formatted lint results. + */ + format(results, resultsMeta) { + let rulesMeta = null; + + results.sort(compareResultsByFilePath); + + return formatter(results, { + ...resultsMeta, + cwd, + get rulesMeta() { + if (!rulesMeta) { + rulesMeta = eslint.getRulesMetaForResults(results); + } + + return rulesMeta; + } + }); + } + }; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {Promise} A configuration object for the file + * or `undefined` if there is no configuration data for the object. + */ + async calculateConfigForFile(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const options = privateMembers.get(this).options; + const absolutePath = path.resolve(options.cwd, filePath); + const configs = await calculateConfigArray(this, options); + + return configs.getConfig(absolutePath); + } + + /** + * Finds the config file being used by this instance based on the options + * passed to the constructor. + * @returns {string|undefined} The path to the config file being used or + * `undefined` if no config file is being used. + */ + async findConfigFile() { + const options = privateMembers.get(this).options; + const { configFilePath } = await locateConfigFileToUse(options); + + return configFilePath; + } + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {Promise} Whether or not the given path is ignored. + */ + async isPathIgnored(filePath) { + const config = await this.calculateConfigForFile(filePath); + + return config === void 0; + } +} + +/** + * Returns whether flat config should be used. + * @returns {Promise} Whether flat config should be used. + */ +async function shouldUseFlatConfig() { + switch (process.env.ESLINT_USE_FLAT_CONFIG) { + case "true": + return true; + case "false": + return false; + default: + + /* + * If neither explicitly enabled nor disabled, then use the presence + * of a flat config file to determine enablement. + */ + return !!(await findFlatConfigFile(process.cwd())); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + FlatESLint, + shouldUseFlatConfig +}; diff --git a/node_modules/eslint/lib/eslint/index.js b/node_modules/eslint/lib/eslint/index.js new file mode 100644 index 0000000..017b768 --- /dev/null +++ b/node_modules/eslint/lib/eslint/index.js @@ -0,0 +1,9 @@ +"use strict"; + +const { ESLint } = require("./eslint"); +const { FlatESLint } = require("./flat-eslint"); + +module.exports = { + ESLint, + FlatESLint +}; diff --git a/node_modules/eslint/lib/linter/apply-disable-directives.js b/node_modules/eslint/lib/linter/apply-disable-directives.js new file mode 100644 index 0000000..13ced99 --- /dev/null +++ b/node_modules/eslint/lib/linter/apply-disable-directives.js @@ -0,0 +1,351 @@ +/** + * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../shared/types").LintMessage} LintMessage */ + +//------------------------------------------------------------------------------ +// Module Definition +//------------------------------------------------------------------------------ + +const escapeRegExp = require("escape-string-regexp"); + +/** + * Compares the locations of two objects in a source file + * @param {{line: number, column: number}} itemA The first object + * @param {{line: number, column: number}} itemB The second object + * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if + * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location. + */ +function compareLocations(itemA, itemB) { + return itemA.line - itemB.line || itemA.column - itemB.column; +} + +/** + * Groups a set of directives into sub-arrays by their parent comment. + * @param {Directive[]} directives Unused directives to be removed. + * @returns {Directive[][]} Directives grouped by their parent comment. + */ +function groupByParentComment(directives) { + const groups = new Map(); + + for (const directive of directives) { + const { unprocessedDirective: { parentComment } } = directive; + + if (groups.has(parentComment)) { + groups.get(parentComment).push(directive); + } else { + groups.set(parentComment, [directive]); + } + } + + return [...groups.values()]; +} + +/** + * Creates removal details for a set of directives within the same comment. + * @param {Directive[]} directives Unused directives to be removed. + * @param {Token} commentToken The backing Comment token. + * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems. + */ +function createIndividualDirectivesRemoval(directives, commentToken) { + + /* + * `commentToken.value` starts right after `//` or `/*`. + * All calculated offsets will be relative to this index. + */ + const commentValueStart = commentToken.range[0] + "//".length; + + // Find where the list of rules starts. `\S+` matches with the directive name (e.g. `eslint-disable-line`) + const listStartOffset = /^\s*\S+\s+/u.exec(commentToken.value)[0].length; + + /* + * Get the list text without any surrounding whitespace. In order to preserve the original + * formatting, we don't want to change that whitespace. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + */ + const listText = commentToken.value + .slice(listStartOffset) // remove directive name and all whitespace before the list + .split(/\s-{2,}\s/u)[0] // remove `-- comment`, if it exists + .trimEnd(); // remove all whitespace after the list + + /* + * We can assume that `listText` contains multiple elements. + * Otherwise, this function wouldn't be called - if there is + * only one rule in the list, then the whole comment must be removed. + */ + + return directives.map(directive => { + const { ruleId } = directive; + + const regex = new RegExp(String.raw`(?:^|\s*,\s*)${escapeRegExp(ruleId)}(?:\s*,\s*|$)`, "u"); + const match = regex.exec(listText); + const matchedText = match[0]; + const matchStartOffset = listStartOffset + match.index; + const matchEndOffset = matchStartOffset + matchedText.length; + + const firstIndexOfComma = matchedText.indexOf(","); + const lastIndexOfComma = matchedText.lastIndexOf(","); + + let removalStartOffset, removalEndOffset; + + if (firstIndexOfComma !== lastIndexOfComma) { + + /* + * Since there are two commas, this must one of the elements in the middle of the list. + * Matched range starts where the previous rule name ends, and ends where the next rule name starts. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^^ + * + * We want to remove only the content between the two commas, and also one of the commas. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^ + */ + removalStartOffset = matchStartOffset + firstIndexOfComma; + removalEndOffset = matchStartOffset + lastIndexOfComma; + + } else { + + /* + * This is either the first element or the last element. + * + * If this is the first element, matched range starts where the first rule name starts + * and ends where the second rule name starts. This is exactly the range we want + * to remove so that the second rule name will start where the first one was starting + * and thus preserve the original formatting. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^ + * + * Similarly, if this is the last element, we've already matched the range we want to + * remove. The previous rule name will end where the last one was ending, relative + * to the content on the right side. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^ + */ + removalStartOffset = matchStartOffset; + removalEndOffset = matchEndOffset; + } + + return { + description: `'${ruleId}'`, + fix: { + range: [ + commentValueStart + removalStartOffset, + commentValueStart + removalEndOffset + ], + text: "" + }, + unprocessedDirective: directive.unprocessedDirective + }; + }); +} + +/** + * Creates a description of deleting an entire unused disable comment. + * @param {Directive[]} directives Unused directives to be removed. + * @param {Token} commentToken The backing Comment token. + * @returns {{ description, fix, unprocessedDirective }} Details for later creation of an output Problem. + */ +function createCommentRemoval(directives, commentToken) { + const { range } = commentToken; + const ruleIds = directives.filter(directive => directive.ruleId).map(directive => `'${directive.ruleId}'`); + + return { + description: ruleIds.length <= 2 + ? ruleIds.join(" or ") + : `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds[ruleIds.length - 1]}`, + fix: { + range, + text: " " + }, + unprocessedDirective: directives[0].unprocessedDirective + }; +} + +/** + * Parses details from directives to create output Problems. + * @param {Directive[]} allDirectives Unused directives to be removed. + * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems. + */ +function processUnusedDisableDirectives(allDirectives) { + const directiveGroups = groupByParentComment(allDirectives); + + return directiveGroups.flatMap( + directives => { + const { parentComment } = directives[0].unprocessedDirective; + const remainingRuleIds = new Set(parentComment.ruleIds); + + for (const directive of directives) { + remainingRuleIds.delete(directive.ruleId); + } + + return remainingRuleIds.size + ? createIndividualDirectivesRemoval(directives, parentComment.commentToken) + : [createCommentRemoval(directives, parentComment.commentToken)]; + } + ); +} + +/** + * This is the same as the exported function, except that it + * doesn't handle disable-line and disable-next-line directives, and it always reports unused + * disable directives. + * @param {Object} options options for applying directives. This is the same as the options + * for the exported function, except that `reportUnusedDisableDirectives` is not supported + * (this function always reports unused disable directives). + * @returns {{problems: LintMessage[], unusedDisableDirectives: LintMessage[]}} An object with a list + * of problems (including suppressed ones) and unused eslint-disable directives + */ +function applyDirectives(options) { + const problems = []; + const usedDisableDirectives = new Set(); + + for (const problem of options.problems) { + let disableDirectivesForProblem = []; + let nextDirectiveIndex = 0; + + while ( + nextDirectiveIndex < options.directives.length && + compareLocations(options.directives[nextDirectiveIndex], problem) <= 0 + ) { + const directive = options.directives[nextDirectiveIndex++]; + + if (directive.ruleId === null || directive.ruleId === problem.ruleId) { + switch (directive.type) { + case "disable": + disableDirectivesForProblem.push(directive); + break; + + case "enable": + disableDirectivesForProblem = []; + break; + + // no default + } + } + } + + if (disableDirectivesForProblem.length > 0) { + const suppressions = disableDirectivesForProblem.map(directive => ({ + kind: "directive", + justification: directive.unprocessedDirective.justification + })); + + if (problem.suppressions) { + problem.suppressions = problem.suppressions.concat(suppressions); + } else { + problem.suppressions = suppressions; + usedDisableDirectives.add(disableDirectivesForProblem[disableDirectivesForProblem.length - 1]); + } + } + + problems.push(problem); + } + + const unusedDisableDirectivesToReport = options.directives + .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive)); + + const processed = processUnusedDisableDirectives(unusedDisableDirectivesToReport); + + const unusedDisableDirectives = processed + .map(({ description, fix, unprocessedDirective }) => { + const { parentComment, type, line, column } = unprocessedDirective; + + return { + ruleId: null, + message: description + ? `Unused eslint-disable directive (no problems were reported from ${description}).` + : "Unused eslint-disable directive (no problems were reported).", + line: type === "disable-next-line" ? parentComment.commentToken.loc.start.line : line, + column: type === "disable-next-line" ? parentComment.commentToken.loc.start.column + 1 : column, + severity: options.reportUnusedDisableDirectives === "warn" ? 1 : 2, + nodeType: null, + ...options.disableFixes ? {} : { fix } + }; + }); + + return { problems, unusedDisableDirectives }; +} + +/** + * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list + * of reported problems, adds the suppression information to the problems. + * @param {Object} options Information about directives and problems + * @param {{ + * type: ("disable"|"enable"|"disable-line"|"disable-next-line"), + * ruleId: (string|null), + * line: number, + * column: number, + * justification: string + * }} options.directives Directive comments found in the file, with one-based columns. + * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable + * comment for two different rules is represented as two directives). + * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems + * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns. + * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives + * @param {boolean} options.disableFixes If true, it doesn't make `fix` properties. + * @returns {{ruleId: (string|null), line: number, column: number, suppressions?: {kind: string, justification: string}}[]} + * An object with a list of reported problems, the suppressed of which contain the suppression information. + */ +module.exports = ({ directives, disableFixes, problems, reportUnusedDisableDirectives = "off" }) => { + const blockDirectives = directives + .filter(directive => directive.type === "disable" || directive.type === "enable") + .map(directive => Object.assign({}, directive, { unprocessedDirective: directive })) + .sort(compareLocations); + + const lineDirectives = directives.flatMap(directive => { + switch (directive.type) { + case "disable": + case "enable": + return []; + + case "disable-line": + return [ + { type: "disable", line: directive.line, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive }, + { type: "enable", line: directive.line + 1, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive } + ]; + + case "disable-next-line": + return [ + { type: "disable", line: directive.line + 1, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive }, + { type: "enable", line: directive.line + 2, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive } + ]; + + default: + throw new TypeError(`Unrecognized directive type '${directive.type}'`); + } + }).sort(compareLocations); + + const blockDirectivesResult = applyDirectives({ + problems, + directives: blockDirectives, + disableFixes, + reportUnusedDisableDirectives + }); + const lineDirectivesResult = applyDirectives({ + problems: blockDirectivesResult.problems, + directives: lineDirectives, + disableFixes, + reportUnusedDisableDirectives + }); + + return reportUnusedDisableDirectives !== "off" + ? lineDirectivesResult.problems + .concat(blockDirectivesResult.unusedDisableDirectives) + .concat(lineDirectivesResult.unusedDisableDirectives) + .sort(compareLocations) + : lineDirectivesResult.problems; +}; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js b/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js new file mode 100644 index 0000000..2dcc273 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js @@ -0,0 +1,844 @@ +/** + * @fileoverview A class of the code path analyzer. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("assert"), + { breakableTypePattern } = require("../../shared/ast-utils"), + CodePath = require("./code-path"), + CodePathSegment = require("./code-path-segment"), + IdGenerator = require("./id-generator"), + debug = require("./debug-helpers"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a `case` node (not `default` node). + * @param {ASTNode} node A `SwitchCase` node to check. + * @returns {boolean} `true` if the node is a `case` node (not `default` node). + */ +function isCaseNode(node) { + return Boolean(node.test); +} + +/** + * Checks if a given node appears as the value of a PropertyDefinition node. + * @param {ASTNode} node THe node to check. + * @returns {boolean} `true` if the node is a PropertyDefinition value, + * false if not. + */ +function isPropertyDefinitionValue(node) { + const parent = node.parent; + + return parent && parent.type === "PropertyDefinition" && parent.value === node; +} + +/** + * Checks whether the given logical operator is taken into account for the code + * path analysis. + * @param {string} operator The operator found in the LogicalExpression node + * @returns {boolean} `true` if the operator is "&&" or "||" or "??" + */ +function isHandledLogicalOperator(operator) { + return operator === "&&" || operator === "||" || operator === "??"; +} + +/** + * Checks whether the given assignment operator is a logical assignment operator. + * Logical assignments are taken into account for the code path analysis + * because of their short-circuiting semantics. + * @param {string} operator The operator found in the AssignmentExpression node + * @returns {boolean} `true` if the operator is "&&=" or "||=" or "??=" + */ +function isLogicalAssignmentOperator(operator) { + return operator === "&&=" || operator === "||=" || operator === "??="; +} + +/** + * Gets the label if the parent node of a given node is a LabeledStatement. + * @param {ASTNode} node A node to get. + * @returns {string|null} The label or `null`. + */ +function getLabel(node) { + if (node.parent.type === "LabeledStatement") { + return node.parent.label.name; + } + return null; +} + +/** + * Checks whether or not a given logical expression node goes different path + * between the `true` case and the `false` case. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a test of a choice statement. + */ +function isForkingByTrueOrFalse(node) { + const parent = node.parent; + + switch (parent.type) { + case "ConditionalExpression": + case "IfStatement": + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + return parent.test === node; + + case "LogicalExpression": + return isHandledLogicalOperator(parent.operator); + + case "AssignmentExpression": + return isLogicalAssignmentOperator(parent.operator); + + default: + return false; + } +} + +/** + * Gets the boolean value of a given literal node. + * + * This is used to detect infinity loops (e.g. `while (true) {}`). + * Statements preceded by an infinity loop are unreachable if the loop didn't + * have any `break` statement. + * @param {ASTNode} node A node to get. + * @returns {boolean|undefined} a boolean value if the node is a Literal node, + * otherwise `undefined`. + */ +function getBooleanValueIfSimpleConstant(node) { + if (node.type === "Literal") { + return Boolean(node.value); + } + return void 0; +} + +/** + * Checks that a given identifier node is a reference or not. + * + * This is used to detect the first throwable node in a `try` block. + * @param {ASTNode} node An Identifier node to check. + * @returns {boolean} `true` if the node is a reference. + */ +function isIdentifierReference(node) { + const parent = node.parent; + + switch (parent.type) { + case "LabeledStatement": + case "BreakStatement": + case "ContinueStatement": + case "ArrayPattern": + case "RestElement": + case "ImportSpecifier": + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "CatchClause": + return false; + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ClassDeclaration": + case "ClassExpression": + case "VariableDeclarator": + return parent.id !== node; + + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return ( + parent.key !== node || + parent.computed || + parent.shorthand + ); + + case "AssignmentPattern": + return parent.key !== node; + + default: + return true; + } +} + +/** + * Updates the current segment with the head segment. + * This is similar to local branches and tracking branches of git. + * + * To separate the current and the head is in order to not make useless segments. + * + * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd" + * events are fired. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function forwardCurrentToHead(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + const currentSegments = state.currentSegments; + const headSegments = state.headSegments; + const end = Math.max(currentSegments.length, headSegments.length); + let i, currentSegment, headSegment; + + // Fires leaving events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + + if (currentSegment !== headSegment && currentSegment) { + debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`); + + if (currentSegment.reachable) { + analyzer.emitter.emit( + "onCodePathSegmentEnd", + currentSegment, + node + ); + } + } + } + + // Update state. + state.currentSegments = headSegments; + + // Fires entering events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + + if (currentSegment !== headSegment && headSegment) { + debug.dump(`onCodePathSegmentStart ${headSegment.id}`); + + CodePathSegment.markUsed(headSegment); + if (headSegment.reachable) { + analyzer.emitter.emit( + "onCodePathSegmentStart", + headSegment, + node + ); + } + } + } + +} + +/** + * Updates the current segment with empty. + * This is called at the last of functions or the program. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function leaveFromCurrentSegment(analyzer, node) { + const state = CodePath.getState(analyzer.codePath); + const currentSegments = state.currentSegments; + + for (let i = 0; i < currentSegments.length; ++i) { + const currentSegment = currentSegments[i]; + + debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`); + if (currentSegment.reachable) { + analyzer.emitter.emit( + "onCodePathSegmentEnd", + currentSegment, + node + ); + } + } + + state.currentSegments = []; +} + +/** + * Updates the code path due to the position of a given node in the parent node + * thereof. + * + * For example, if the node is `parent.consequent`, this creates a fork from the + * current path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function preprocess(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + const parent = node.parent; + + switch (parent.type) { + + // The `arguments.length == 0` case is in `postprocess` function. + case "CallExpression": + if (parent.optional === true && parent.arguments.length >= 1 && parent.arguments[0] === node) { + state.makeOptionalRight(); + } + break; + case "MemberExpression": + if (parent.optional === true && parent.property === node) { + state.makeOptionalRight(); + } + break; + + case "LogicalExpression": + if ( + parent.right === node && + isHandledLogicalOperator(parent.operator) + ) { + state.makeLogicalRight(); + } + break; + + case "AssignmentExpression": + if ( + parent.right === node && + isLogicalAssignmentOperator(parent.operator) + ) { + state.makeLogicalRight(); + } + break; + + case "ConditionalExpression": + case "IfStatement": + + /* + * Fork if this node is at `consequent`/`alternate`. + * `popForkContext()` exists at `IfStatement:exit` and + * `ConditionalExpression:exit`. + */ + if (parent.consequent === node) { + state.makeIfConsequent(); + } else if (parent.alternate === node) { + state.makeIfAlternate(); + } + break; + + case "SwitchCase": + if (parent.consequent[0] === node) { + state.makeSwitchCaseBody(false, !parent.test); + } + break; + + case "TryStatement": + if (parent.handler === node) { + state.makeCatchBlock(); + } else if (parent.finalizer === node) { + state.makeFinallyBlock(); + } + break; + + case "WhileStatement": + if (parent.test === node) { + state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); + } else { + assert(parent.body === node); + state.makeWhileBody(); + } + break; + + case "DoWhileStatement": + if (parent.body === node) { + state.makeDoWhileBody(); + } else { + assert(parent.test === node); + state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); + } + break; + + case "ForStatement": + if (parent.test === node) { + state.makeForTest(getBooleanValueIfSimpleConstant(node)); + } else if (parent.update === node) { + state.makeForUpdate(); + } else if (parent.body === node) { + state.makeForBody(); + } + break; + + case "ForInStatement": + case "ForOfStatement": + if (parent.left === node) { + state.makeForInOfLeft(); + } else if (parent.right === node) { + state.makeForInOfRight(); + } else { + assert(parent.body === node); + state.makeForInOfBody(); + } + break; + + case "AssignmentPattern": + + /* + * Fork if this node is at `right`. + * `left` is executed always, so it uses the current path. + * `popForkContext()` exists at `AssignmentPattern:exit`. + */ + if (parent.right === node) { + state.pushForkContext(); + state.forkBypassPath(); + state.forkPath(); + } + break; + + default: + break; + } +} + +/** + * Updates the code path due to the type of a given node in entering. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function processCodePathToEnter(analyzer, node) { + let codePath = analyzer.codePath; + let state = codePath && CodePath.getState(codePath); + const parent = node.parent; + + /** + * Creates a new code path and trigger the onCodePathStart event + * based on the currently selected node. + * @param {string} origin The reason the code path was started. + * @returns {void} + */ + function startCodePath(origin) { + if (codePath) { + + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + debug.dumpState(node, state, false); + } + + // Create the code path of this scope. + codePath = analyzer.codePath = new CodePath({ + id: analyzer.idGenerator.next(), + origin, + upper: codePath, + onLooped: analyzer.onLooped + }); + state = CodePath.getState(codePath); + + // Emits onCodePathStart events. + debug.dump(`onCodePathStart ${codePath.id}`); + analyzer.emitter.emit("onCodePathStart", codePath, node); + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to start a new code path in this + * case. + */ + if (isPropertyDefinitionValue(node)) { + startCodePath("class-field-initializer"); + + /* + * Intentional fall through because `node` needs to also be + * processed by the code below. For example, if we have: + * + * class Foo { + * a = () => {} + * } + * + * In this case, we also need start a second code path. + */ + + } + + switch (node.type) { + case "Program": + startCodePath("program"); + break; + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + startCodePath("function"); + break; + + case "StaticBlock": + startCodePath("class-static-block"); + break; + + case "ChainExpression": + state.pushChainContext(); + break; + case "CallExpression": + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + case "MemberExpression": + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + + case "LogicalExpression": + if (isHandledLogicalOperator(node.operator)) { + state.pushChoiceContext( + node.operator, + isForkingByTrueOrFalse(node) + ); + } + break; + + case "AssignmentExpression": + if (isLogicalAssignmentOperator(node.operator)) { + state.pushChoiceContext( + node.operator.slice(0, -1), // removes `=` from the end + isForkingByTrueOrFalse(node) + ); + } + break; + + case "ConditionalExpression": + case "IfStatement": + state.pushChoiceContext("test", false); + break; + + case "SwitchStatement": + state.pushSwitchContext( + node.cases.some(isCaseNode), + getLabel(node) + ); + break; + + case "TryStatement": + state.pushTryContext(Boolean(node.finalizer)); + break; + + case "SwitchCase": + + /* + * Fork if this node is after the 2st node in `cases`. + * It's similar to `else` blocks. + * The next `test` node is processed in this path. + */ + if (parent.discriminant !== node && parent.cases[0] !== node) { + state.forkPath(); + } + break; + + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + state.pushLoopContext(node.type, getLabel(node)); + break; + + case "LabeledStatement": + if (!breakableTypePattern.test(node.body.type)) { + state.pushBreakContext(false, node.label.name); + } + break; + + default: + break; + } + + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + debug.dumpState(node, state, false); +} + +/** + * Updates the code path due to the type of a given node in leaving. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function processCodePathToExit(analyzer, node) { + + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + let dontForward = false; + + switch (node.type) { + case "ChainExpression": + state.popChainContext(); + break; + + case "IfStatement": + case "ConditionalExpression": + state.popChoiceContext(); + break; + + case "LogicalExpression": + if (isHandledLogicalOperator(node.operator)) { + state.popChoiceContext(); + } + break; + + case "AssignmentExpression": + if (isLogicalAssignmentOperator(node.operator)) { + state.popChoiceContext(); + } + break; + + case "SwitchStatement": + state.popSwitchContext(); + break; + + case "SwitchCase": + + /* + * This is the same as the process at the 1st `consequent` node in + * `preprocess` function. + * Must do if this `consequent` is empty. + */ + if (node.consequent.length === 0) { + state.makeSwitchCaseBody(true, !node.test); + } + if (state.forkContext.reachable) { + dontForward = true; + } + break; + + case "TryStatement": + state.popTryContext(); + break; + + case "BreakStatement": + forwardCurrentToHead(analyzer, node); + state.makeBreak(node.label && node.label.name); + dontForward = true; + break; + + case "ContinueStatement": + forwardCurrentToHead(analyzer, node); + state.makeContinue(node.label && node.label.name); + dontForward = true; + break; + + case "ReturnStatement": + forwardCurrentToHead(analyzer, node); + state.makeReturn(); + dontForward = true; + break; + + case "ThrowStatement": + forwardCurrentToHead(analyzer, node); + state.makeThrow(); + dontForward = true; + break; + + case "Identifier": + if (isIdentifierReference(node)) { + state.makeFirstThrowablePathInTryBlock(); + dontForward = true; + } + break; + + case "CallExpression": + case "ImportExpression": + case "MemberExpression": + case "NewExpression": + case "YieldExpression": + state.makeFirstThrowablePathInTryBlock(); + break; + + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + state.popLoopContext(); + break; + + case "AssignmentPattern": + state.popForkContext(); + break; + + case "LabeledStatement": + if (!breakableTypePattern.test(node.body.type)) { + state.popBreakContext(); + } + break; + + default: + break; + } + + // Emits onCodePathSegmentStart events if updated. + if (!dontForward) { + forwardCurrentToHead(analyzer, node); + } + debug.dumpState(node, state, true); +} + +/** + * Updates the code path to finalize the current code path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function postprocess(analyzer, node) { + + /** + * Ends the code path for the current node. + * @returns {void} + */ + function endCodePath() { + let codePath = analyzer.codePath; + + // Mark the current path as the final node. + CodePath.getState(codePath).makeFinal(); + + // Emits onCodePathSegmentEnd event of the current segments. + leaveFromCurrentSegment(analyzer, node); + + // Emits onCodePathEnd event of this code path. + debug.dump(`onCodePathEnd ${codePath.id}`); + analyzer.emitter.emit("onCodePathEnd", codePath, node); + debug.dumpDot(codePath); + + codePath = analyzer.codePath = analyzer.codePath.upper; + if (codePath) { + debug.dumpState(node, CodePath.getState(codePath), true); + } + + } + + switch (node.type) { + case "Program": + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "StaticBlock": { + endCodePath(); + break; + } + + // The `arguments.length >= 1` case is in `preprocess` function. + case "CallExpression": + if (node.optional === true && node.arguments.length === 0) { + CodePath.getState(analyzer.codePath).makeOptionalRight(); + } + break; + + default: + break; + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to end a code path in this + * case. + * + * We need to check after the other checks in order to close the + * code paths in the correct order for code like this: + * + * + * class Foo { + * a = () => {} + * } + * + * In this case, The ArrowFunctionExpression code path is closed first + * and then we need to close the code path for the PropertyDefinition + * value. + */ + if (isPropertyDefinitionValue(node)) { + endCodePath(); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The class to analyze code paths. + * This class implements the EventGenerator interface. + */ +class CodePathAnalyzer { + + /** + * @param {EventGenerator} eventGenerator An event generator to wrap. + */ + constructor(eventGenerator) { + this.original = eventGenerator; + this.emitter = eventGenerator.emitter; + this.codePath = null; + this.idGenerator = new IdGenerator("s"); + this.currentNode = null; + this.onLooped = this.onLooped.bind(this); + } + + /** + * Does the process to enter a given AST node. + * This updates state of analysis and calls `enterNode` of the wrapped. + * @param {ASTNode} node A node which is entering. + * @returns {void} + */ + enterNode(node) { + this.currentNode = node; + + // Updates the code path due to node's position in its parent node. + if (node.parent) { + preprocess(this, node); + } + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToEnter(this, node); + + // Emits node events. + this.original.enterNode(node); + + this.currentNode = null; + } + + /** + * Does the process to leave a given AST node. + * This updates state of analysis and calls `leaveNode` of the wrapped. + * @param {ASTNode} node A node which is leaving. + * @returns {void} + */ + leaveNode(node) { + this.currentNode = node; + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToExit(this, node); + + // Emits node events. + this.original.leaveNode(node); + + // Emits the last onCodePathStart/onCodePathSegmentStart events. + postprocess(this, node); + + this.currentNode = null; + } + + /** + * This is called on a code path looped. + * Then this raises a looped event. + * @param {CodePathSegment} fromSegment A segment of prev. + * @param {CodePathSegment} toSegment A segment of next. + * @returns {void} + */ + onLooped(fromSegment, toSegment) { + if (fromSegment.reachable && toSegment.reachable) { + debug.dump(`onCodePathSegmentLoop ${fromSegment.id} -> ${toSegment.id}`); + this.emitter.emit( + "onCodePathSegmentLoop", + fromSegment, + toSegment, + this.currentNode + ); + } + } +} + +module.exports = CodePathAnalyzer; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js b/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js new file mode 100644 index 0000000..fd2726a --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js @@ -0,0 +1,235 @@ +/** + * @fileoverview A class of the code path segment. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("./debug-helpers"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given segment is reachable. + * @param {CodePathSegment} segment A segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A code path segment. + */ +class CodePathSegment { + + /** + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * This array includes unreachable segments. + * @param {boolean} reachable A flag which shows this is reachable. + */ + constructor(id, allPrevSegments, reachable) { + + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * An array of the next segments. + * @type {CodePathSegment[]} + */ + this.nextSegments = []; + + /** + * An array of the previous segments. + * @type {CodePathSegment[]} + */ + this.prevSegments = allPrevSegments.filter(isReachable); + + /** + * An array of the next segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allNextSegments = []; + + /** + * An array of the previous segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allPrevSegments = allPrevSegments; + + /** + * A flag which shows this is reachable. + * @type {boolean} + */ + this.reachable = reachable; + + // Internal data. + Object.defineProperty(this, "internal", { + value: { + used: false, + loopedPrevSegments: [] + } + }); + + /* c8 ignore start */ + if (debug.enabled) { + this.internal.nodes = []; + }/* c8 ignore stop */ + } + + /** + * Checks a given previous segment is coming from the end of a loop. + * @param {CodePathSegment} segment A previous segment to check. + * @returns {boolean} `true` if the segment is coming from the end of a loop. + */ + isLoopedPrevSegment(segment) { + return this.internal.loopedPrevSegments.includes(segment); + } + + /** + * Creates the root segment. + * @param {string} id An identifier. + * @returns {CodePathSegment} The created segment. + */ + static newRoot(id) { + return new CodePathSegment(id, [], true); + } + + /** + * Creates a segment that follows given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newNext(id, allPrevSegments) { + return new CodePathSegment( + id, + CodePathSegment.flattenUnusedSegments(allPrevSegments), + allPrevSegments.some(isReachable) + ); + } + + /** + * Creates an unreachable segment that follows given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newUnreachable(id, allPrevSegments) { + const segment = new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), false); + + /* + * In `if (a) return a; foo();` case, the unreachable segment preceded by + * the return statement is not used but must not be remove. + */ + CodePathSegment.markUsed(segment); + + return segment; + } + + /** + * Creates a segment that follows given segments. + * This factory method does not connect with `allPrevSegments`. + * But this inherits `reachable` flag. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newDisconnected(id, allPrevSegments) { + return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); + } + + /** + * Makes a given segment being used. + * + * And this function registers the segment into the previous segments as a next. + * @param {CodePathSegment} segment A segment to mark. + * @returns {void} + */ + static markUsed(segment) { + if (segment.internal.used) { + return; + } + segment.internal.used = true; + + let i; + + if (segment.reachable) { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + const prevSegment = segment.allPrevSegments[i]; + + prevSegment.allNextSegments.push(segment); + prevSegment.nextSegments.push(segment); + } + } else { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + segment.allPrevSegments[i].allNextSegments.push(segment); + } + } + } + + /** + * Marks a previous segment as looped. + * @param {CodePathSegment} segment A segment. + * @param {CodePathSegment} prevSegment A previous segment to mark. + * @returns {void} + */ + static markPrevSegmentAsLooped(segment, prevSegment) { + segment.internal.loopedPrevSegments.push(prevSegment); + } + + /** + * Replaces unused segments with the previous segments of each unused segment. + * @param {CodePathSegment[]} segments An array of segments to replace. + * @returns {CodePathSegment[]} The replaced array. + */ + static flattenUnusedSegments(segments) { + const done = Object.create(null); + const retv = []; + + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + // Ignores duplicated. + if (done[segment.id]) { + continue; + } + + // Use previous segments if unused. + if (!segment.internal.used) { + for (let j = 0; j < segment.allPrevSegments.length; ++j) { + const prevSegment = segment.allPrevSegments[j]; + + if (!done[prevSegment.id]) { + done[prevSegment.id] = true; + retv.push(prevSegment); + } + } + } else { + done[segment.id] = true; + retv.push(segment); + } + } + + return retv; + } +} + +module.exports = CodePathSegment; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js b/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js new file mode 100644 index 0000000..d187297 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js @@ -0,0 +1,1483 @@ +/** + * @fileoverview A class to manage state of generating a code path. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const CodePathSegment = require("./code-path-segment"), + ForkContext = require("./fork-context"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Adds given segments into the `dest` array. + * If the `others` array does not includes the given segments, adds to the `all` + * array as well. + * + * This adds only reachable and used segments. + * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} all The unified destination array (`finalSegments`). + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ +function addToReturnedOrThrown(dest, others, all, segments) { + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + dest.push(segment); + if (!others.includes(segment)) { + all.push(segment); + } + } +} + +/** + * Gets a loop-context for a `continue` statement. + * @param {CodePathState} state A state to get. + * @param {string} label The label of a `continue` statement. + * @returns {LoopContext} A loop-context for a `continue` statement. + */ +function getContinueContext(state, label) { + if (!label) { + return state.loopContext; + } + + let context = state.loopContext; + + while (context) { + if (context.label === label) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; +} + +/** + * Gets a context for a `break` statement. + * @param {CodePathState} state A state to get. + * @param {string} label The label of a `break` statement. + * @returns {LoopContext|SwitchContext} A context for a `break` statement. + */ +function getBreakContext(state, label) { + let context = state.breakContext; + + while (context) { + if (label ? context.label === label : context.breakable) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; +} + +/** + * Gets a context for a `return` statement. + * @param {CodePathState} state A state to get. + * @returns {TryContext|CodePathState} A context for a `return` statement. + */ +function getReturnContext(state) { + let context = state.tryContext; + + while (context) { + if (context.hasFinalizer && context.position !== "finally") { + return context; + } + context = context.upper; + } + + return state; +} + +/** + * Gets a context for a `throw` statement. + * @param {CodePathState} state A state to get. + * @returns {TryContext|CodePathState} A context for a `throw` statement. + */ +function getThrowContext(state) { + let context = state.tryContext; + + while (context) { + if (context.position === "try" || + (context.hasFinalizer && context.position === "catch") + ) { + return context; + } + context = context.upper; + } + + return state; +} + +/** + * Removes a given element from a given array. + * @param {any[]} xs An array to remove the specific element. + * @param {any} x An element to be removed. + * @returns {void} + */ +function remove(xs, x) { + xs.splice(xs.indexOf(x), 1); +} + +/** + * Disconnect given segments. + * + * This is used in a process for switch statements. + * If there is the "default" chunk before other cases, the order is different + * between node's and running's. + * @param {CodePathSegment[]} prevSegments Forward segments to disconnect. + * @param {CodePathSegment[]} nextSegments Backward segments to disconnect. + * @returns {void} + */ +function removeConnection(prevSegments, nextSegments) { + for (let i = 0; i < prevSegments.length; ++i) { + const prevSegment = prevSegments[i]; + const nextSegment = nextSegments[i]; + + remove(prevSegment.nextSegments, nextSegment); + remove(prevSegment.allNextSegments, nextSegment); + remove(nextSegment.prevSegments, prevSegment); + remove(nextSegment.allPrevSegments, prevSegment); + } +} + +/** + * Creates looping path. + * @param {CodePathState} state The instance. + * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source. + * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination. + * @returns {void} + */ +function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) { + const fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments); + const toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments); + + const end = Math.min(fromSegments.length, toSegments.length); + + for (let i = 0; i < end; ++i) { + const fromSegment = fromSegments[i]; + const toSegment = toSegments[i]; + + if (toSegment.reachable) { + fromSegment.nextSegments.push(toSegment); + } + if (fromSegment.reachable) { + toSegment.prevSegments.push(fromSegment); + } + fromSegment.allNextSegments.push(toSegment); + toSegment.allPrevSegments.push(fromSegment); + + if (toSegment.allPrevSegments.length >= 2) { + CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment); + } + + state.notifyLooped(fromSegment, toSegment); + } +} + +/** + * Finalizes segments of `test` chunk of a ForStatement. + * + * - Adds `false` paths to paths which are leaving from the loop. + * - Sets `true` paths to paths which go to the body. + * @param {LoopContext} context A loop context to modify. + * @param {ChoiceContext} choiceContext A choice context of this loop. + * @param {CodePathSegment[]} head The current head paths. + * @returns {void} + */ +function finalizeTestSegmentsOfFor(context, choiceContext, head) { + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(head); + choiceContext.falseForkContext.add(head); + choiceContext.qqForkContext.add(head); + } + + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A class which manages state to analyze code paths. + */ +class CodePathState { + + /** + * @param {IdGenerator} idGenerator An id generator to generate id for code + * path segments. + * @param {Function} onLooped A callback function to notify looping. + */ + constructor(idGenerator, onLooped) { + this.idGenerator = idGenerator; + this.notifyLooped = onLooped; + this.forkContext = ForkContext.newRoot(idGenerator); + this.choiceContext = null; + this.switchContext = null; + this.tryContext = null; + this.loopContext = null; + this.breakContext = null; + this.chainContext = null; + + this.currentSegments = []; + this.initialSegment = this.forkContext.head[0]; + + // returnedSegments and thrownSegments push elements into finalSegments also. + const final = this.finalSegments = []; + const returned = this.returnedForkContext = []; + const thrown = this.thrownForkContext = []; + + returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); + thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); + } + + /** + * The head segments. + * @type {CodePathSegment[]} + */ + get headSegments() { + return this.forkContext.head; + } + + /** + * The parent forking context. + * This is used for the root of new forks. + * @type {ForkContext} + */ + get parentForkContext() { + const current = this.forkContext; + + return current && current.upper; + } + + /** + * Creates and stacks new forking context. + * @param {boolean} forkLeavingPath A flag which shows being in a + * "finally" block. + * @returns {ForkContext} The created context. + */ + pushForkContext(forkLeavingPath) { + this.forkContext = ForkContext.newEmpty( + this.forkContext, + forkLeavingPath + ); + + return this.forkContext; + } + + /** + * Pops and merges the last forking context. + * @returns {ForkContext} The last context. + */ + popForkContext() { + const lastContext = this.forkContext; + + this.forkContext = lastContext.upper; + this.forkContext.replaceHead(lastContext.makeNext(0, -1)); + + return lastContext; + } + + /** + * Creates a new path. + * @returns {void} + */ + forkPath() { + this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); + } + + /** + * Creates a bypass path. + * This is used for such as IfStatement which does not have "else" chunk. + * @returns {void} + */ + forkBypassPath() { + this.forkContext.add(this.parentForkContext.head); + } + + //-------------------------------------------------------------------------- + // ConditionalExpression, LogicalExpression, IfStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context for ConditionalExpression, LogicalExpression, AssignmentExpression (logical assignments only), + * IfStatement, WhileStatement, DoWhileStatement, or ForStatement. + * + * LogicalExpressions have cases that it goes different paths between the + * `true` case and the `false` case. + * + * For Example: + * + * if (a || b) { + * foo(); + * } else { + * bar(); + * } + * + * In this case, `b` is evaluated always in the code path of the `else` + * block, but it's not so in the code path of the `if` block. + * So there are 3 paths. + * + * a -> foo(); + * a -> b -> foo(); + * a -> b -> bar(); + * @param {string} kind A kind string. + * If the new context is LogicalExpression's or AssignmentExpression's, this is `"&&"` or `"||"` or `"??"`. + * If it's IfStatement's or ConditionalExpression's, this is `"test"`. + * Otherwise, this is `"loop"`. + * @param {boolean} isForkingAsResult A flag that shows that goes different + * paths between `true` and `false`. + * @returns {void} + */ + pushChoiceContext(kind, isForkingAsResult) { + this.choiceContext = { + upper: this.choiceContext, + kind, + isForkingAsResult, + trueForkContext: ForkContext.newEmpty(this.forkContext), + falseForkContext: ForkContext.newEmpty(this.forkContext), + qqForkContext: ForkContext.newEmpty(this.forkContext), + processed: false + }; + } + + /** + * Pops the last choice context and finalizes it. + * @throws {Error} (Unreachable.) + * @returns {ChoiceContext} The popped context. + */ + popChoiceContext() { + const context = this.choiceContext; + + this.choiceContext = context.upper; + + const forkContext = this.forkContext; + const headSegments = forkContext.head; + + switch (context.kind) { + case "&&": + case "||": + case "??": + + /* + * If any result were not transferred from child contexts, + * this sets the head segments to both cases. + * The head segments are the path of the right-hand operand. + */ + if (!context.processed) { + context.trueForkContext.add(headSegments); + context.falseForkContext.add(headSegments); + context.qqForkContext.add(headSegments); + } + + /* + * Transfers results to upper context if this context is in + * test chunk. + */ + if (context.isForkingAsResult) { + const parentContext = this.choiceContext; + + parentContext.trueForkContext.addAll(context.trueForkContext); + parentContext.falseForkContext.addAll(context.falseForkContext); + parentContext.qqForkContext.addAll(context.qqForkContext); + parentContext.processed = true; + + return context; + } + + break; + + case "test": + if (!context.processed) { + + /* + * The head segments are the path of the `if` block here. + * Updates the `true` path with the end of the `if` block. + */ + context.trueForkContext.clear(); + context.trueForkContext.add(headSegments); + } else { + + /* + * The head segments are the path of the `else` block here. + * Updates the `false` path with the end of the `else` + * block. + */ + context.falseForkContext.clear(); + context.falseForkContext.add(headSegments); + } + + break; + + case "loop": + + /* + * Loops are addressed in popLoopContext(). + * This is called from popLoopContext(). + */ + return context; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + + // Merges all paths. + const prevForkContext = context.trueForkContext; + + prevForkContext.addAll(context.falseForkContext); + forkContext.replaceHead(prevForkContext.makeNext(0, -1)); + + return context; + } + + /** + * Makes a code path segment of the right-hand operand of a logical + * expression. + * @throws {Error} (Unreachable.) + * @returns {void} + */ + makeLogicalRight() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + if (context.processed) { + + /* + * This got segments already from the child choice context. + * Creates the next path from own true/false fork context. + */ + let prevForkContext; + + switch (context.kind) { + case "&&": // if true then go to the right-hand side. + prevForkContext = context.trueForkContext; + break; + case "||": // if false then go to the right-hand side. + prevForkContext = context.falseForkContext; + break; + case "??": // Both true/false can short-circuit, so needs the third path to go to the right-hand side. That's qqForkContext. + prevForkContext = context.qqForkContext; + break; + default: + throw new Error("unreachable"); + } + + forkContext.replaceHead(prevForkContext.makeNext(0, -1)); + prevForkContext.clear(); + context.processed = false; + } else { + + /* + * This did not get segments from the child choice context. + * So addresses the head segments. + * The head segments are the path of the left-hand operand. + */ + switch (context.kind) { + case "&&": // the false path can short-circuit. + context.falseForkContext.add(forkContext.head); + break; + case "||": // the true path can short-circuit. + context.trueForkContext.add(forkContext.head); + break; + case "??": // both can short-circuit. + context.trueForkContext.add(forkContext.head); + context.falseForkContext.add(forkContext.head); + break; + default: + throw new Error("unreachable"); + } + + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + } + + /** + * Makes a code path segment of the `if` block. + * @returns {void} + */ + makeIfConsequent() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + /* + * If any result were not transferred from child contexts, + * this sets the head segments to both cases. + * The head segments are the path of the test expression. + */ + if (!context.processed) { + context.trueForkContext.add(forkContext.head); + context.falseForkContext.add(forkContext.head); + context.qqForkContext.add(forkContext.head); + } + + context.processed = false; + + // Creates new path from the `true` case. + forkContext.replaceHead( + context.trueForkContext.makeNext(0, -1) + ); + } + + /** + * Makes a code path segment of the `else` block. + * @returns {void} + */ + makeIfAlternate() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + /* + * The head segments are the path of the `if` block. + * Updates the `true` path with the end of the `if` block. + */ + context.trueForkContext.clear(); + context.trueForkContext.add(forkContext.head); + context.processed = true; + + // Creates new path from the `false` case. + forkContext.replaceHead( + context.falseForkContext.makeNext(0, -1) + ); + } + + //-------------------------------------------------------------------------- + // ChainExpression + //-------------------------------------------------------------------------- + + /** + * Push a new `ChainExpression` context to the stack. + * This method is called on entering to each `ChainExpression` node. + * This context is used to count forking in the optional chain then merge them on the exiting from the `ChainExpression` node. + * @returns {void} + */ + pushChainContext() { + this.chainContext = { + upper: this.chainContext, + countChoiceContexts: 0 + }; + } + + /** + * Pop a `ChainExpression` context from the stack. + * This method is called on exiting from each `ChainExpression` node. + * This merges all forks of the last optional chaining. + * @returns {void} + */ + popChainContext() { + const context = this.chainContext; + + this.chainContext = context.upper; + + // pop all choice contexts of this. + for (let i = context.countChoiceContexts; i > 0; --i) { + this.popChoiceContext(); + } + } + + /** + * Create a choice context for optional access. + * This method is called on entering to each `(Call|Member)Expression[optional=true]` node. + * This creates a choice context as similar to `LogicalExpression[operator="??"]` node. + * @returns {void} + */ + makeOptionalNode() { + if (this.chainContext) { + this.chainContext.countChoiceContexts += 1; + this.pushChoiceContext("??", false); + } + } + + /** + * Create a fork. + * This method is called on entering to the `arguments|property` property of each `(Call|Member)Expression` node. + * @returns {void} + */ + makeOptionalRight() { + if (this.chainContext) { + this.makeLogicalRight(); + } + } + + //-------------------------------------------------------------------------- + // SwitchStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of SwitchStatement and stacks it. + * @param {boolean} hasCase `true` if the switch statement has one or more + * case parts. + * @param {string|null} label The label text. + * @returns {void} + */ + pushSwitchContext(hasCase, label) { + this.switchContext = { + upper: this.switchContext, + hasCase, + defaultSegments: null, + defaultBodySegments: null, + foundDefault: false, + lastIsDefault: false, + countForks: 0 + }; + + this.pushBreakContext(true, label); + } + + /** + * Pops the last context of SwitchStatement and finalizes it. + * + * - Disposes all forking stack for `case` and `default`. + * - Creates the next code path segment from `context.brokenForkContext`. + * - If the last `SwitchCase` node is not a `default` part, creates a path + * to the `default` body. + * @returns {void} + */ + popSwitchContext() { + const context = this.switchContext; + + this.switchContext = context.upper; + + const forkContext = this.forkContext; + const brokenForkContext = this.popBreakContext().brokenForkContext; + + if (context.countForks === 0) { + + /* + * When there is only one `default` chunk and there is one or more + * `break` statements, even if forks are nothing, it needs to merge + * those. + */ + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.makeNext(-1, -1)); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + + return; + } + + const lastSegments = forkContext.head; + + this.forkBypassPath(); + const lastCaseSegments = forkContext.head; + + /* + * `brokenForkContext` is used to make the next segment. + * It must add the last segment into `brokenForkContext`. + */ + brokenForkContext.add(lastSegments); + + /* + * A path which is failed in all case test should be connected to path + * of `default` chunk. + */ + if (!context.lastIsDefault) { + if (context.defaultBodySegments) { + + /* + * Remove a link from `default` label to its chunk. + * It's false route. + */ + removeConnection(context.defaultSegments, context.defaultBodySegments); + makeLooped(this, lastCaseSegments, context.defaultBodySegments); + } else { + + /* + * It handles the last case body as broken if `default` chunk + * does not exist. + */ + brokenForkContext.add(lastCaseSegments); + } + } + + // Pops the segment context stack until the entry segment. + for (let i = 0; i < context.countForks; ++i) { + this.forkContext = this.forkContext.upper; + } + + /* + * Creates a path from all brokenForkContext paths. + * This is a path after switch statement. + */ + this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for a `SwitchCase` node. + * @param {boolean} isEmpty `true` if the body is empty. + * @param {boolean} isDefault `true` if the body is the default case. + * @returns {void} + */ + makeSwitchCaseBody(isEmpty, isDefault) { + const context = this.switchContext; + + if (!context.hasCase) { + return; + } + + /* + * Merge forks. + * The parent fork context has two segments. + * Those are from the current case and the body of the previous case. + */ + const parentForkContext = this.forkContext; + const forkContext = this.pushForkContext(); + + forkContext.add(parentForkContext.makeNext(0, -1)); + + /* + * Save `default` chunk info. + * If the `default` label is not at the last, we must make a path from + * the last `case` to the `default` chunk. + */ + if (isDefault) { + context.defaultSegments = parentForkContext.head; + if (isEmpty) { + context.foundDefault = true; + } else { + context.defaultBodySegments = forkContext.head; + } + } else { + if (!isEmpty && context.foundDefault) { + context.foundDefault = false; + context.defaultBodySegments = forkContext.head; + } + } + + context.lastIsDefault = isDefault; + context.countForks += 1; + } + + //-------------------------------------------------------------------------- + // TryStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of TryStatement and stacks it. + * @param {boolean} hasFinalizer `true` if the try statement has a + * `finally` block. + * @returns {void} + */ + pushTryContext(hasFinalizer) { + this.tryContext = { + upper: this.tryContext, + position: "try", + hasFinalizer, + + returnedForkContext: hasFinalizer + ? ForkContext.newEmpty(this.forkContext) + : null, + + thrownForkContext: ForkContext.newEmpty(this.forkContext), + lastOfTryIsReachable: false, + lastOfCatchIsReachable: false + }; + } + + /** + * Pops the last context of TryStatement and finalizes it. + * @returns {void} + */ + popTryContext() { + const context = this.tryContext; + + this.tryContext = context.upper; + + if (context.position === "catch") { + + // Merges two paths from the `try` block and `catch` block merely. + this.popForkContext(); + return; + } + + /* + * The following process is executed only when there is the `finally` + * block. + */ + + const returned = context.returnedForkContext; + const thrown = context.thrownForkContext; + + if (returned.empty && thrown.empty) { + return; + } + + // Separate head to normal paths and leaving paths. + const headSegments = this.forkContext.head; + + this.forkContext = this.forkContext.upper; + const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0); + const leavingSegments = headSegments.slice(headSegments.length / 2 | 0); + + // Forwards the leaving path to upper contexts. + if (!returned.empty) { + getReturnContext(this).returnedForkContext.add(leavingSegments); + } + if (!thrown.empty) { + getThrowContext(this).thrownForkContext.add(leavingSegments); + } + + // Sets the normal path as the next. + this.forkContext.replaceHead(normalSegments); + + /* + * If both paths of the `try` block and the `catch` block are + * unreachable, the next path becomes unreachable as well. + */ + if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { + this.forkContext.makeUnreachable(); + } + } + + /** + * Makes a code path segment for a `catch` block. + * @returns {void} + */ + makeCatchBlock() { + const context = this.tryContext; + const forkContext = this.forkContext; + const thrown = context.thrownForkContext; + + // Update state. + context.position = "catch"; + context.thrownForkContext = ForkContext.newEmpty(forkContext); + context.lastOfTryIsReachable = forkContext.reachable; + + // Merge thrown paths. + thrown.add(forkContext.head); + const thrownSegments = thrown.makeNext(0, -1); + + // Fork to a bypass and the merged thrown path. + this.pushForkContext(); + this.forkBypassPath(); + this.forkContext.add(thrownSegments); + } + + /** + * Makes a code path segment for a `finally` block. + * + * In the `finally` block, parallel paths are created. The parallel paths + * are used as leaving-paths. The leaving-paths are paths from `return` + * statements and `throw` statements in a `try` block or a `catch` block. + * @returns {void} + */ + makeFinallyBlock() { + const context = this.tryContext; + let forkContext = this.forkContext; + const returned = context.returnedForkContext; + const thrown = context.thrownForkContext; + const headOfLeavingSegments = forkContext.head; + + // Update state. + if (context.position === "catch") { + + // Merges two paths from the `try` block and `catch` block. + this.popForkContext(); + forkContext = this.forkContext; + + context.lastOfCatchIsReachable = forkContext.reachable; + } else { + context.lastOfTryIsReachable = forkContext.reachable; + } + context.position = "finally"; + + if (returned.empty && thrown.empty) { + + // This path does not leave. + return; + } + + /* + * Create a parallel segment from merging returned and thrown. + * This segment will leave at the end of this finally block. + */ + const segments = forkContext.makeNext(-1, -1); + + for (let i = 0; i < forkContext.count; ++i) { + const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]]; + + for (let j = 0; j < returned.segmentsList.length; ++j) { + prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]); + } + for (let j = 0; j < thrown.segmentsList.length; ++j) { + prevSegsOfLeavingSegment.push(thrown.segmentsList[j][i]); + } + + segments.push( + CodePathSegment.newNext( + this.idGenerator.next(), + prevSegsOfLeavingSegment + ) + ); + } + + this.pushForkContext(true); + this.forkContext.add(segments); + } + + /** + * Makes a code path segment from the first throwable node to the `catch` + * block or the `finally` block. + * @returns {void} + */ + makeFirstThrowablePathInTryBlock() { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getThrowContext(this); + + if (context === this || + context.position !== "try" || + !context.thrownForkContext.empty + ) { + return; + } + + context.thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + + //-------------------------------------------------------------------------- + // Loop Statements + //-------------------------------------------------------------------------- + + /** + * Creates a context object of a loop statement and stacks it. + * @param {string} type The type of the node which was triggered. One of + * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`, + * and `ForStatement`. + * @param {string|null} label A label of the node which was triggered. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + pushLoopContext(type, label) { + const forkContext = this.forkContext; + const breakContext = this.pushBreakContext(true, label); + + switch (type) { + case "WhileStatement": + this.pushChoiceContext("loop", false); + this.loopContext = { + upper: this.loopContext, + type, + label, + test: void 0, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + + case "DoWhileStatement": + this.pushChoiceContext("loop", false); + this.loopContext = { + upper: this.loopContext, + type, + label, + test: void 0, + entrySegments: null, + continueForkContext: ForkContext.newEmpty(forkContext), + brokenForkContext: breakContext.brokenForkContext + }; + break; + + case "ForStatement": + this.pushChoiceContext("loop", false); + this.loopContext = { + upper: this.loopContext, + type, + label, + test: void 0, + endOfInitSegments: null, + testSegments: null, + endOfTestSegments: null, + updateSegments: null, + endOfUpdateSegments: null, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + + case "ForInStatement": + case "ForOfStatement": + this.loopContext = { + upper: this.loopContext, + type, + label, + prevSegments: null, + leftSegments: null, + endOfLeftSegments: null, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + + /* c8 ignore next */ + default: + throw new Error(`unknown type: "${type}"`); + } + } + + /** + * Pops the last context of a loop statement and finalizes it. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + popLoopContext() { + const context = this.loopContext; + + this.loopContext = context.upper; + + const forkContext = this.forkContext; + const brokenForkContext = this.popBreakContext().brokenForkContext; + + // Creates a looped path. + switch (context.type) { + case "WhileStatement": + case "ForStatement": + this.popChoiceContext(); + makeLooped( + this, + forkContext.head, + context.continueDestSegments + ); + break; + + case "DoWhileStatement": { + const choiceContext = this.popChoiceContext(); + + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + if (context.test !== true) { + brokenForkContext.addAll(choiceContext.falseForkContext); + } + + // `true` paths go to looping. + const segmentsList = choiceContext.trueForkContext.segmentsList; + + for (let i = 0; i < segmentsList.length; ++i) { + makeLooped( + this, + segmentsList[i], + context.entrySegments + ); + } + break; + } + + case "ForInStatement": + case "ForOfStatement": + brokenForkContext.add(forkContext.head); + makeLooped( + this, + forkContext.head, + context.leftSegments + ); + break; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + + // Go next. + if (brokenForkContext.empty) { + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } else { + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + + /** + * Makes a code path segment for the test part of a WhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeWhileTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + const testSegments = forkContext.makeNext(0, -1); + + // Update state. + context.test = test; + context.continueDestSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the body part of a WhileStatement. + * @returns {void} + */ + makeWhileBody() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + + // Update state. + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for the body part of a DoWhileStatement. + * @returns {void} + */ + makeDoWhileBody() { + const context = this.loopContext; + const forkContext = this.forkContext; + const bodySegments = forkContext.makeNext(-1, -1); + + // Update state. + context.entrySegments = bodySegments; + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the test part of a DoWhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeDoWhileTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + + context.test = test; + + // Creates paths of `continue` statements. + if (!context.continueForkContext.empty) { + context.continueForkContext.add(forkContext.head); + const testSegments = context.continueForkContext.makeNext(0, -1); + + forkContext.replaceHead(testSegments); + } + } + + /** + * Makes a code path segment for the test part of a ForStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeForTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + const endOfInitSegments = forkContext.head; + const testSegments = forkContext.makeNext(-1, -1); + + // Update state. + context.test = test; + context.endOfInitSegments = endOfInitSegments; + context.continueDestSegments = context.testSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the update part of a ForStatement. + * @returns {void} + */ + makeForUpdate() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + // Make the next paths of the test. + if (context.testSegments) { + finalizeTestSegmentsOfFor( + context, + choiceContext, + forkContext.head + ); + } else { + context.endOfInitSegments = forkContext.head; + } + + // Update state. + const updateSegments = forkContext.makeDisconnected(-1, -1); + + context.continueDestSegments = context.updateSegments = updateSegments; + forkContext.replaceHead(updateSegments); + } + + /** + * Makes a code path segment for the body part of a ForStatement. + * @returns {void} + */ + makeForBody() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + // Update state. + if (context.updateSegments) { + context.endOfUpdateSegments = forkContext.head; + + // `update` -> `test` + if (context.testSegments) { + makeLooped( + this, + context.endOfUpdateSegments, + context.testSegments + ); + } + } else if (context.testSegments) { + finalizeTestSegmentsOfFor( + context, + choiceContext, + forkContext.head + ); + } else { + context.endOfInitSegments = forkContext.head; + } + + let bodySegments = context.endOfTestSegments; + + if (!bodySegments) { + + /* + * If there is not the `test` part, the `body` path comes from the + * `init` part and the `update` part. + */ + const prevForkContext = ForkContext.newEmpty(forkContext); + + prevForkContext.add(context.endOfInitSegments); + if (context.endOfUpdateSegments) { + prevForkContext.add(context.endOfUpdateSegments); + } + + bodySegments = prevForkContext.makeNext(0, -1); + } + context.continueDestSegments = context.continueDestSegments || bodySegments; + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the left part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfLeft() { + const context = this.loopContext; + const forkContext = this.forkContext; + const leftSegments = forkContext.makeDisconnected(-1, -1); + + // Update state. + context.prevSegments = forkContext.head; + context.leftSegments = context.continueDestSegments = leftSegments; + forkContext.replaceHead(leftSegments); + } + + /** + * Makes a code path segment for the right part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfRight() { + const context = this.loopContext; + const forkContext = this.forkContext; + const temp = ForkContext.newEmpty(forkContext); + + temp.add(context.prevSegments); + const rightSegments = temp.makeNext(-1, -1); + + // Update state. + context.endOfLeftSegments = forkContext.head; + forkContext.replaceHead(rightSegments); + } + + /** + * Makes a code path segment for the body part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfBody() { + const context = this.loopContext; + const forkContext = this.forkContext; + const temp = ForkContext.newEmpty(forkContext); + + temp.add(context.endOfLeftSegments); + const bodySegments = temp.makeNext(-1, -1); + + // Make a path: `right` -> `left`. + makeLooped(this, forkContext.head, context.leftSegments); + + // Update state. + context.brokenForkContext.add(forkContext.head); + forkContext.replaceHead(bodySegments); + } + + //-------------------------------------------------------------------------- + // Control Statements + //-------------------------------------------------------------------------- + + /** + * Creates new context for BreakStatement. + * @param {boolean} breakable The flag to indicate it can break by + * an unlabeled BreakStatement. + * @param {string|null} label The label of this context. + * @returns {Object} The new context. + */ + pushBreakContext(breakable, label) { + this.breakContext = { + upper: this.breakContext, + breakable, + label, + brokenForkContext: ForkContext.newEmpty(this.forkContext) + }; + return this.breakContext; + } + + /** + * Removes the top item of the break context stack. + * @returns {Object} The removed context. + */ + popBreakContext() { + const context = this.breakContext; + const forkContext = this.forkContext; + + this.breakContext = context.upper; + + // Process this context here for other than switches and loops. + if (!context.breakable) { + const brokenForkContext = context.brokenForkContext; + + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.head); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + + return context; + } + + /** + * Makes a path for a `break` statement. + * + * It registers the head segment to a context of `break`. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string} label A label of the break statement. + * @returns {void} + */ + makeBreak(label) { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getBreakContext(this, label); + + + if (context) { + context.brokenForkContext.add(forkContext.head); + } + + /* c8 ignore next */ + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `continue` statement. + * + * It makes a looping path. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string} label A label of the continue statement. + * @returns {void} + */ + makeContinue(label) { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getContinueContext(this, label); + + if (context) { + if (context.continueDestSegments) { + makeLooped(this, forkContext.head, context.continueDestSegments); + + // If the context is a for-in/of loop, this effects a break also. + if (context.type === "ForInStatement" || + context.type === "ForOfStatement" + ) { + context.brokenForkContext.add(forkContext.head); + } + } else { + context.continueForkContext.add(forkContext.head); + } + } + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `return` statement. + * + * It registers the head segment to a context of `return`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeReturn() { + const forkContext = this.forkContext; + + if (forkContext.reachable) { + getReturnContext(this).returnedForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes a path for a `throw` statement. + * + * It registers the head segment to a context of `throw`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeThrow() { + const forkContext = this.forkContext; + + if (forkContext.reachable) { + getThrowContext(this).thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes the final path. + * @returns {void} + */ + makeFinal() { + const segments = this.currentSegments; + + if (segments.length > 0 && segments[0].reachable) { + this.returnedForkContext.add(segments); + } + } +} + +module.exports = CodePathState; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/code-path.js b/node_modules/eslint/lib/linter/code-path-analysis/code-path.js new file mode 100644 index 0000000..a028ca6 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/code-path.js @@ -0,0 +1,247 @@ +/** + * @fileoverview A class of the code path. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const CodePathState = require("./code-path-state"); +const IdGenerator = require("./id-generator"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A code path. + */ +class CodePath { + + /** + * Creates a new instance. + * @param {Object} options Options for the function (see below). + * @param {string} options.id An identifier. + * @param {string} options.origin The type of code path origin. + * @param {CodePath|null} options.upper The code path of the upper function scope. + * @param {Function} options.onLooped A callback function to notify looping. + */ + constructor({ id, origin, upper, onLooped }) { + + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * The reason that this code path was started. May be "program", + * "function", "class-field-initializer", or "class-static-block". + * @type {string} + */ + this.origin = origin; + + /** + * The code path of the upper function scope. + * @type {CodePath|null} + */ + this.upper = upper; + + /** + * The code paths of nested function scopes. + * @type {CodePath[]} + */ + this.childCodePaths = []; + + // Initializes internal state. + Object.defineProperty( + this, + "internal", + { value: new CodePathState(new IdGenerator(`${id}_`), onLooped) } + ); + + // Adds this into `childCodePaths` of `upper`. + if (upper) { + upper.childCodePaths.push(this); + } + } + + /** + * Gets the state of a given code path. + * @param {CodePath} codePath A code path to get. + * @returns {CodePathState} The state of the code path. + */ + static getState(codePath) { + return codePath.internal; + } + + /** + * The initial code path segment. + * @type {CodePathSegment} + */ + get initialSegment() { + return this.internal.initialSegment; + } + + /** + * Final code path segments. + * This array is a mix of `returnedSegments` and `thrownSegments`. + * @type {CodePathSegment[]} + */ + get finalSegments() { + return this.internal.finalSegments; + } + + /** + * Final code path segments which is with `return` statements. + * This array contains the last path segment if it's reachable. + * Since the reachable last path returns `undefined`. + * @type {CodePathSegment[]} + */ + get returnedSegments() { + return this.internal.returnedForkContext; + } + + /** + * Final code path segments which is with `throw` statements. + * @type {CodePathSegment[]} + */ + get thrownSegments() { + return this.internal.thrownForkContext; + } + + /** + * Current code path segments. + * @type {CodePathSegment[]} + */ + get currentSegments() { + return this.internal.currentSegments; + } + + /** + * Traverses all segments in this code path. + * + * codePath.traverseSegments(function(segment, controller) { + * // do something. + * }); + * + * This method enumerates segments in order from the head. + * + * The `controller` object has two methods. + * + * - `controller.skip()` - Skip the following segments in this branch. + * - `controller.break()` - Skip all following segments. + * @param {Object} [options] Omittable. + * @param {CodePathSegment} [options.first] The first segment to traverse. + * @param {CodePathSegment} [options.last] The last segment to traverse. + * @param {Function} callback A callback function. + * @returns {void} + */ + traverseSegments(options, callback) { + let resolvedOptions; + let resolvedCallback; + + if (typeof options === "function") { + resolvedCallback = options; + resolvedOptions = {}; + } else { + resolvedOptions = options || {}; + resolvedCallback = callback; + } + + const startSegment = resolvedOptions.first || this.internal.initialSegment; + const lastSegment = resolvedOptions.last; + + let item = null; + let index = 0; + let end = 0; + let segment = null; + const visited = Object.create(null); + const stack = [[startSegment, 0]]; + let skippedSegment = null; + let broken = false; + const controller = { + skip() { + if (stack.length <= 1) { + broken = true; + } else { + skippedSegment = stack[stack.length - 2][0]; + } + }, + break() { + broken = true; + } + }; + + /** + * Checks a given previous segment has been visited. + * @param {CodePathSegment} prevSegment A previous segment to check. + * @returns {boolean} `true` if the segment has been visited. + */ + function isVisited(prevSegment) { + return ( + visited[prevSegment.id] || + segment.isLoopedPrevSegment(prevSegment) + ); + } + + while (stack.length > 0) { + item = stack[stack.length - 1]; + segment = item[0]; + index = item[1]; + + if (index === 0) { + + // Skip if this segment has been visited already. + if (visited[segment.id]) { + stack.pop(); + continue; + } + + // Skip if all previous segments have not been visited. + if (segment !== startSegment && + segment.prevSegments.length > 0 && + !segment.prevSegments.every(isVisited) + ) { + stack.pop(); + continue; + } + + // Reset the flag of skipping if all branches have been skipped. + if (skippedSegment && segment.prevSegments.includes(skippedSegment)) { + skippedSegment = null; + } + visited[segment.id] = true; + + // Call the callback when the first time. + if (!skippedSegment) { + resolvedCallback.call(this, segment, controller); + if (segment === lastSegment) { + controller.skip(); + } + if (broken) { + break; + } + } + } + + // Update the stack. + end = segment.nextSegments.length - 1; + if (index < end) { + item[1] += 1; + stack.push([segment.nextSegments[index], 0]); + } else if (index === end) { + item[0] = segment.nextSegments[index]; + item[1] = 0; + } else { + stack.pop(); + } + } + } +} + +module.exports = CodePath; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js b/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js new file mode 100644 index 0000000..c0e01a8 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js @@ -0,0 +1,203 @@ +/** + * @fileoverview Helpers to debug for code path analysis. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("debug")("eslint:code-path"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets id of a given segment. + * @param {CodePathSegment} segment A segment to get. + * @returns {string} Id of the segment. + */ +/* c8 ignore next */ +function getId(segment) { // eslint-disable-line jsdoc/require-jsdoc -- Ignoring + return segment.id + (segment.reachable ? "" : "!"); +} + +/** + * Get string for the given node and operation. + * @param {ASTNode} node The node to convert. + * @param {"enter" | "exit" | undefined} label The operation label. + * @returns {string} The string representation. + */ +function nodeToString(node, label) { + const suffix = label ? `:${label}` : ""; + + switch (node.type) { + case "Identifier": return `${node.type}${suffix} (${node.name})`; + case "Literal": return `${node.type}${suffix} (${node.value})`; + default: return `${node.type}${suffix}`; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + + /** + * A flag that debug dumping is enabled or not. + * @type {boolean} + */ + enabled: debug.enabled, + + /** + * Dumps given objects. + * @param {...any} args objects to dump. + * @returns {void} + */ + dump: debug, + + /** + * Dumps the current analyzing state. + * @param {ASTNode} node A node to dump. + * @param {CodePathState} state A state to dump. + * @param {boolean} leaving A flag whether or not it's leaving + * @returns {void} + */ + dumpState: !debug.enabled ? debug : /* c8 ignore next */ function(node, state, leaving) { + for (let i = 0; i < state.currentSegments.length; ++i) { + const segInternal = state.currentSegments[i].internal; + + if (leaving) { + const last = segInternal.nodes.length - 1; + + if (last >= 0 && segInternal.nodes[last] === nodeToString(node, "enter")) { + segInternal.nodes[last] = nodeToString(node, void 0); + } else { + segInternal.nodes.push(nodeToString(node, "exit")); + } + } else { + segInternal.nodes.push(nodeToString(node, "enter")); + } + } + + debug([ + `${state.currentSegments.map(getId).join(",")})`, + `${node.type}${leaving ? ":exit" : ""}` + ].join(" ")); + }, + + /** + * Dumps a DOT code of a given code path. + * The DOT code can be visualized with Graphvis. + * @param {CodePath} codePath A code path to dump. + * @returns {void} + * @see http://www.graphviz.org + * @see http://www.webgraphviz.com + */ + dumpDot: !debug.enabled ? debug : /* c8 ignore next */ function(codePath) { + let text = + "\n" + + "digraph {\n" + + "node[shape=box,style=\"rounded,filled\",fillcolor=white];\n" + + "initial[label=\"\",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25];\n"; + + if (codePath.returnedSegments.length > 0) { + text += "final[label=\"\",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25];\n"; + } + if (codePath.thrownSegments.length > 0) { + text += "thrown[label=\"✘\",shape=circle,width=0.3,height=0.3,fixedsize=true];\n"; + } + + const traceMap = Object.create(null); + const arrows = this.makeDotArrows(codePath, traceMap); + + for (const id in traceMap) { // eslint-disable-line guard-for-in -- Want ability to traverse prototype + const segment = traceMap[id]; + + text += `${id}[`; + + if (segment.reachable) { + text += "label=\""; + } else { + text += "style=\"rounded,dashed,filled\",fillcolor=\"#FF9800\",label=\"<>\\n"; + } + + if (segment.internal.nodes.length > 0) { + text += segment.internal.nodes.join("\\n"); + } else { + text += "????"; + } + + text += "\"];\n"; + } + + text += `${arrows}\n`; + text += "}"; + debug("DOT", text); + }, + + /** + * Makes a DOT code of a given code path. + * The DOT code can be visualized with Graphvis. + * @param {CodePath} codePath A code path to make DOT. + * @param {Object} traceMap Optional. A map to check whether or not segments had been done. + * @returns {string} A DOT code of the code path. + */ + makeDotArrows(codePath, traceMap) { + const stack = [[codePath.initialSegment, 0]]; + const done = traceMap || Object.create(null); + let lastId = codePath.initialSegment.id; + let text = `initial->${codePath.initialSegment.id}`; + + while (stack.length > 0) { + const item = stack.pop(); + const segment = item[0]; + const index = item[1]; + + if (done[segment.id] && index === 0) { + continue; + } + done[segment.id] = segment; + + const nextSegment = segment.allNextSegments[index]; + + if (!nextSegment) { + continue; + } + + if (lastId === segment.id) { + text += `->${nextSegment.id}`; + } else { + text += `;\n${segment.id}->${nextSegment.id}`; + } + lastId = nextSegment.id; + + stack.unshift([segment, 1 + index]); + stack.push([nextSegment, 0]); + } + + codePath.returnedSegments.forEach(finalSegment => { + if (lastId === finalSegment.id) { + text += "->final"; + } else { + text += `;\n${finalSegment.id}->final`; + } + lastId = null; + }); + + codePath.thrownSegments.forEach(finalSegment => { + if (lastId === finalSegment.id) { + text += "->thrown"; + } else { + text += `;\n${finalSegment.id}->thrown`; + } + lastId = null; + }); + + return `${text};`; + } +}; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js b/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js new file mode 100644 index 0000000..04c59b5 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js @@ -0,0 +1,248 @@ +/** + * @fileoverview A class to operate forking. + * + * This is state of forking. + * This has a fork list and manages it. + * + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("assert"), + CodePathSegment = require("./code-path-segment"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets whether or not a given segment is reachable. + * @param {CodePathSegment} segment A segment to get. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +/** + * Creates new segments from the specific range of `context.segmentsList`. + * + * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and + * `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`. + * This `h` is from `b`, `d`, and `f`. + * @param {ForkContext} context An instance. + * @param {number} begin The first index of the previous segments. + * @param {number} end The last index of the previous segments. + * @param {Function} create A factory function of new segments. + * @returns {CodePathSegment[]} New segments. + */ +function makeSegments(context, begin, end, create) { + const list = context.segmentsList; + + const normalizedBegin = begin >= 0 ? begin : list.length + begin; + const normalizedEnd = end >= 0 ? end : list.length + end; + + const segments = []; + + for (let i = 0; i < context.count; ++i) { + const allPrevSegments = []; + + for (let j = normalizedBegin; j <= normalizedEnd; ++j) { + allPrevSegments.push(list[j][i]); + } + + segments.push(create(context.idGenerator.next(), allPrevSegments)); + } + + return segments; +} + +/** + * `segments` becomes doubly in a `finally` block. Then if a code path exits by a + * control statement (such as `break`, `continue`) from the `finally` block, the + * destination's segments may be half of the source segments. In that case, this + * merges segments. + * @param {ForkContext} context An instance. + * @param {CodePathSegment[]} segments Segments to merge. + * @returns {CodePathSegment[]} The merged segments. + */ +function mergeExtraSegments(context, segments) { + let currentSegments = segments; + + while (currentSegments.length > context.count) { + const merged = []; + + for (let i = 0, length = currentSegments.length / 2 | 0; i < length; ++i) { + merged.push(CodePathSegment.newNext( + context.idGenerator.next(), + [currentSegments[i], currentSegments[i + length]] + )); + } + currentSegments = merged; + } + return currentSegments; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A class to manage forking. + */ +class ForkContext { + + /** + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @param {ForkContext|null} upper An upper fork context. + * @param {number} count A number of parallel segments. + */ + constructor(idGenerator, upper, count) { + this.idGenerator = idGenerator; + this.upper = upper; + this.count = count; + this.segmentsList = []; + } + + /** + * The head segments. + * @type {CodePathSegment[]} + */ + get head() { + const list = this.segmentsList; + + return list.length === 0 ? [] : list[list.length - 1]; + } + + /** + * A flag which shows empty. + * @type {boolean} + */ + get empty() { + return this.segmentsList.length === 0; + } + + /** + * A flag which shows reachable. + * @type {boolean} + */ + get reachable() { + const segments = this.head; + + return segments.length > 0 && segments.some(isReachable); + } + + /** + * Creates new segments from this context. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeNext(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newNext); + } + + /** + * Creates new segments from this context. + * The new segments is always unreachable. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeUnreachable(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newUnreachable); + } + + /** + * Creates new segments from this context. + * The new segments don't have connections for previous segments. + * But these inherit the reachable flag from this context. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeDisconnected(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newDisconnected); + } + + /** + * Adds segments into this context. + * The added segments become the head. + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ + add(segments) { + assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); + + this.segmentsList.push(mergeExtraSegments(this, segments)); + } + + /** + * Replaces the head segments with given segments. + * The current head segments are removed. + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ + replaceHead(segments) { + assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); + + this.segmentsList.splice(-1, 1, mergeExtraSegments(this, segments)); + } + + /** + * Adds all segments of a given fork context into this context. + * @param {ForkContext} context A fork context to add. + * @returns {void} + */ + addAll(context) { + assert(context.count === this.count); + + const source = context.segmentsList; + + for (let i = 0; i < source.length; ++i) { + this.segmentsList.push(source[i]); + } + } + + /** + * Clears all segments in this context. + * @returns {void} + */ + clear() { + this.segmentsList = []; + } + + /** + * Creates the root fork context. + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @returns {ForkContext} New fork context. + */ + static newRoot(idGenerator) { + const context = new ForkContext(idGenerator, null, 1); + + context.add([CodePathSegment.newRoot(idGenerator.next())]); + + return context; + } + + /** + * Creates an empty fork context preceded by a given context. + * @param {ForkContext} parentContext The parent fork context. + * @param {boolean} forkLeavingPath A flag which shows inside of `finally` block. + * @returns {ForkContext} New fork context. + */ + static newEmpty(parentContext, forkLeavingPath) { + return new ForkContext( + parentContext.idGenerator, + parentContext, + (forkLeavingPath ? 2 : 1) * parentContext.count + ); + } +} + +module.exports = ForkContext; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js b/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js new file mode 100644 index 0000000..b580104 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js @@ -0,0 +1,45 @@ +/** + * @fileoverview A class of identifiers generator for code path segments. + * + * Each rule uses the identifier of code path segments to store additional + * information of the code path. + * + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A generator for unique ids. + */ +class IdGenerator { + + /** + * @param {string} prefix Optional. A prefix of generated ids. + */ + constructor(prefix) { + this.prefix = String(prefix); + this.n = 0; + } + + /** + * Generates id. + * @returns {string} A generated id. + */ + next() { + this.n = 1 + this.n | 0; + + /* c8 ignore start */ + if (this.n < 0) { + this.n = 1; + }/* c8 ignore stop */ + + return this.prefix + this.n; + } +} + +module.exports = IdGenerator; diff --git a/node_modules/eslint/lib/linter/config-comment-parser.js b/node_modules/eslint/lib/linter/config-comment-parser.js new file mode 100644 index 0000000..9aab3c4 --- /dev/null +++ b/node_modules/eslint/lib/linter/config-comment-parser.js @@ -0,0 +1,151 @@ +/** + * @fileoverview Config Comment Parser + * @author Nicholas C. Zakas + */ + +/* eslint class-methods-use-this: off -- Methods desired on instance */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const levn = require("levn"), + { + Legacy: { + ConfigOps + } + } = require("@eslint/eslintrc/universal"); + +const debug = require("debug")("eslint:config-comment-parser"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../shared/types").LintMessage} LintMessage */ + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object to parse ESLint configuration comments inside JavaScript files. + * @name ConfigCommentParser + */ +module.exports = class ConfigCommentParser { + + /** + * Parses a list of "name:string_value" or/and "name" options divided by comma or + * whitespace. Used for "global" and "exported" comments. + * @param {string} string The string to parse. + * @param {Comment} comment The comment node which has the string. + * @returns {Object} Result map object of names and string values, or null values if no value was provided + */ + parseStringConfig(string, comment) { + debug("Parsing String config"); + + const items = {}; + + // Collapse whitespace around `:` and `,` to make parsing easier + const trimmedString = string.replace(/\s*([:,])\s*/gu, "$1"); + + trimmedString.split(/\s|,+/u).forEach(name => { + if (!name) { + return; + } + + // value defaults to null (if not provided), e.g: "foo" => ["foo", null] + const [key, value = null] = name.split(":"); + + items[key] = { value, comment }; + }); + return items; + } + + /** + * Parses a JSON-like config. + * @param {string} string The string to parse. + * @param {Object} location Start line and column of comments for potential error message. + * @returns {({success: true, config: Object}|{success: false, error: LintMessage})} Result map object + */ + parseJsonConfig(string, location) { + debug("Parsing JSON config"); + + let items = {}; + + // Parses a JSON-like comment by the same way as parsing CLI option. + try { + items = levn.parse("Object", string) || {}; + + // Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`. + // Also, commaless notations have invalid severity: + // "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"} + // Should ignore that case as well. + if (ConfigOps.isEverySeverityValid(items)) { + return { + success: true, + config: items + }; + } + } catch { + + debug("Levn parsing failed; falling back to manual parsing."); + + // ignore to parse the string by a fallback. + } + + /* + * Optionator cannot parse commaless notations. + * But we are supporting that. So this is a fallback for that. + */ + items = {}; + const normalizedString = string.replace(/([-a-zA-Z0-9/]+):/gu, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/u, "$1,"); + + try { + items = JSON.parse(`{${normalizedString}}`); + } catch (ex) { + debug("Manual parsing failed."); + + return { + success: false, + error: { + ruleId: null, + fatal: true, + severity: 2, + message: `Failed to parse JSON from '${normalizedString}': ${ex.message}`, + line: location.start.line, + column: location.start.column + 1, + nodeType: null + } + }; + + } + + return { + success: true, + config: items + }; + } + + /** + * Parses a config of values separated by comma. + * @param {string} string The string to parse. + * @returns {Object} Result map of values and true values + */ + parseListConfig(string) { + debug("Parsing list config"); + + const items = {}; + + string.split(",").forEach(name => { + const trimmedName = name.trim(); + + if (trimmedName) { + items[trimmedName] = true; + } + }); + return items; + } + +}; diff --git a/node_modules/eslint/lib/linter/index.js b/node_modules/eslint/lib/linter/index.js new file mode 100644 index 0000000..25fd769 --- /dev/null +++ b/node_modules/eslint/lib/linter/index.js @@ -0,0 +1,13 @@ +"use strict"; + +const { Linter } = require("./linter"); +const interpolate = require("./interpolate"); +const SourceCodeFixer = require("./source-code-fixer"); + +module.exports = { + Linter, + + // For testers. + SourceCodeFixer, + interpolate +}; diff --git a/node_modules/eslint/lib/linter/interpolate.js b/node_modules/eslint/lib/linter/interpolate.js new file mode 100644 index 0000000..87e06a0 --- /dev/null +++ b/node_modules/eslint/lib/linter/interpolate.js @@ -0,0 +1,28 @@ +/** + * @fileoverview Interpolate keys from an object into a string with {{ }} markers. + * @author Jed Fox + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = (text, data) => { + if (!data) { + return text; + } + + // Substitution content for any {{ }} markers. + return text.replace(/\{\{([^{}]+?)\}\}/gu, (fullMatch, termWithWhitespace) => { + const term = termWithWhitespace.trim(); + + if (term in data) { + return data[term]; + } + + // Preserve old behavior: If parameter name not provided, don't replace it. + return fullMatch; + }); +}; diff --git a/node_modules/eslint/lib/linter/linter.js b/node_modules/eslint/lib/linter/linter.js new file mode 100644 index 0000000..233cbed --- /dev/null +++ b/node_modules/eslint/lib/linter/linter.js @@ -0,0 +1,2018 @@ +/** + * @fileoverview Main Linter Class + * @author Gyandeep Singh + * @author aladdin-add + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const + path = require("path"), + eslintScope = require("eslint-scope"), + evk = require("eslint-visitor-keys"), + espree = require("espree"), + merge = require("lodash.merge"), + pkg = require("../../package.json"), + astUtils = require("../shared/ast-utils"), + { + directivesPattern + } = require("../shared/directives"), + { + Legacy: { + ConfigOps, + ConfigValidator, + environments: BuiltInEnvironments + } + } = require("@eslint/eslintrc/universal"), + Traverser = require("../shared/traverser"), + { SourceCode } = require("../source-code"), + CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"), + applyDisableDirectives = require("./apply-disable-directives"), + ConfigCommentParser = require("./config-comment-parser"), + NodeEventGenerator = require("./node-event-generator"), + createReportTranslator = require("./report-translator"), + Rules = require("./rules"), + createEmitter = require("./safe-emitter"), + SourceCodeFixer = require("./source-code-fixer"), + timing = require("./timing"), + ruleReplacements = require("../../conf/replacements.json"); +const { getRuleFromConfig } = require("../config/flat-config-helpers"); +const { FlatConfigArray } = require("../config/flat-config-array"); + +const debug = require("debug")("eslint:linter"); +const MAX_AUTOFIX_PASSES = 10; +const DEFAULT_PARSER_NAME = "espree"; +const DEFAULT_ECMA_VERSION = 5; +const commentParser = new ConfigCommentParser(); +const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } }; +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); +const globals = require("../../conf/globals"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {InstanceType} ConfigArray */ +/** @typedef {InstanceType} ExtractedConfig */ +/** @typedef {import("../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../shared/types").Environment} Environment */ +/** @typedef {import("../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../shared/types").LintMessage} LintMessage */ +/** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */ +/** @typedef {import("../shared/types").ParserOptions} ParserOptions */ +/** @typedef {import("../shared/types").LanguageOptions} LanguageOptions */ +/** @typedef {import("../shared/types").Processor} Processor */ +/** @typedef {import("../shared/types").Rule} Rule */ + +/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */ +/** + * @template T + * @typedef {{ [P in keyof T]-?: T[P] }} Required + */ +/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */ + +/** + * @typedef {Object} DisableDirective + * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type Type of directive + * @property {number} line The line number + * @property {number} column The column number + * @property {(string|null)} ruleId The rule ID + * @property {string} justification The justification of directive + */ + +/** + * The private data for `Linter` instance. + * @typedef {Object} LinterInternalSlots + * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used. + * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used. + * @property {SuppressedLintMessage[]} lastSuppressedMessages The `SuppressedLintMessage[]` instance that the last `verify()` call produced. + * @property {Map} parserMap The loaded parsers. + * @property {Rules} ruleMap The loaded rules. + */ + +/** + * @typedef {Object} VerifyOptions + * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability + * to change config once it is set. Defaults to true if not supplied. + * Useful if you want to validate JS without comments overriding rules. + * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix` + * properties into the lint result. + * @property {string} [filename] the filename of the source code. + * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for + * unused `eslint-disable` directives. + */ + +/** + * @typedef {Object} ProcessorOptions + * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the + * predicate function that selects adopt code blocks. + * @property {Processor.postprocess} [postprocess] postprocessor for report + * messages. If provided, this should accept an array of the message lists + * for each code block returned from the preprocessor, apply a mapping to + * the messages as appropriate, and return a one-dimensional array of + * messages. + * @property {Processor.preprocess} [preprocess] preprocessor for source text. + * If provided, this should accept a string of source text, and return an + * array of code blocks to lint. + */ + +/** + * @typedef {Object} FixOptions + * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines + * whether fixes should be applied. + */ + +/** + * @typedef {Object} InternalOptions + * @property {string | null} warnInlineConfig The config name what `noInlineConfig` setting came from. If `noInlineConfig` setting didn't exist, this is null. If this is a config name, then the linter warns directive comments. + * @property {"off" | "warn" | "error"} reportUnusedDisableDirectives (boolean values were normalized) + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if a given object is Espree. + * @param {Object} parser The parser to check. + * @returns {boolean} True if the parser is Espree or false if not. + */ +function isEspree(parser) { + return !!(parser === espree || parser[parserSymbol] === espree); +} + +/** + * Retrieves globals for the given ecmaVersion. + * @param {number} ecmaVersion The version to retrieve globals for. + * @returns {Object} The globals for the given ecmaVersion. + */ +function getGlobalsForEcmaVersion(ecmaVersion) { + + switch (ecmaVersion) { + case 3: + return globals.es3; + + case 5: + return globals.es5; + + default: + if (ecmaVersion < 2015) { + return globals[`es${ecmaVersion + 2009}`]; + } + + return globals[`es${ecmaVersion}`]; + } +} + +/** + * Ensures that variables representing built-in properties of the Global Object, + * and any globals declared by special block comments, are present in the global + * scope. + * @param {Scope} globalScope The global scope. + * @param {Object} configGlobals The globals declared in configuration + * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration + * @returns {void} + */ +function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) { + + // Define configured global variables. + for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) { + + /* + * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would + * typically be caught when validating a config anyway (validity for inline global comments is checked separately). + */ + const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]); + const commentValue = enabledGlobals[id] && enabledGlobals[id].value; + const value = commentValue || configValue; + const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments; + + if (value === "off") { + continue; + } + + let variable = globalScope.set.get(id); + + if (!variable) { + variable = new eslintScope.Variable(id, globalScope); + + globalScope.variables.push(variable); + globalScope.set.set(id, variable); + } + + variable.eslintImplicitGlobalSetting = configValue; + variable.eslintExplicitGlobal = sourceComments !== void 0; + variable.eslintExplicitGlobalComments = sourceComments; + variable.writeable = (value === "writable"); + } + + // mark all exported variables as such + Object.keys(exportedVariables).forEach(name => { + const variable = globalScope.set.get(name); + + if (variable) { + variable.eslintUsed = true; + variable.eslintExported = true; + } + }); + + /* + * "through" contains all references which definitions cannot be found. + * Since we augment the global scope using configuration, we need to update + * references and remove the ones that were added by configuration. + */ + globalScope.through = globalScope.through.filter(reference => { + const name = reference.identifier.name; + const variable = globalScope.set.get(name); + + if (variable) { + + /* + * Links the variable and the reference. + * And this reference is removed from `Scope#through`. + */ + reference.resolved = variable; + variable.references.push(reference); + + return false; + } + + return true; + }); +} + +/** + * creates a missing-rule message. + * @param {string} ruleId the ruleId to create + * @returns {string} created error message + * @private + */ +function createMissingRuleMessage(ruleId) { + return Object.prototype.hasOwnProperty.call(ruleReplacements.rules, ruleId) + ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}` + : `Definition for rule '${ruleId}' was not found.`; +} + +/** + * creates a linting problem + * @param {Object} options to create linting error + * @param {string} [options.ruleId] the ruleId to report + * @param {Object} [options.loc] the loc to report + * @param {string} [options.message] the error message to report + * @param {string} [options.severity] the error message to report + * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId. + * @private + */ +function createLintingProblem(options) { + const { + ruleId = null, + loc = DEFAULT_ERROR_LOC, + message = createMissingRuleMessage(options.ruleId), + severity = 2 + } = options; + + return { + ruleId, + message, + line: loc.start.line, + column: loc.start.column + 1, + endLine: loc.end.line, + endColumn: loc.end.column + 1, + severity, + nodeType: null + }; +} + +/** + * Creates a collection of disable directives from a comment + * @param {Object} options to create disable directives + * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment + * @param {token} options.commentToken The Comment token + * @param {string} options.value The value after the directive in the comment + * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`) + * @param {string} options.justification The justification of the directive + * @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules + * @returns {Object} Directives and problems from the comment + */ +function createDisableDirectives(options) { + const { commentToken, type, value, justification, ruleMapper } = options; + const ruleIds = Object.keys(commentParser.parseListConfig(value)); + const directiveRules = ruleIds.length ? ruleIds : [null]; + const result = { + directives: [], // valid disable directives + directiveProblems: [] // problems in directives + }; + + const parentComment = { commentToken, ruleIds }; + + for (const ruleId of directiveRules) { + + // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/) + if (ruleId === null || !!ruleMapper(ruleId)) { + if (type === "disable-next-line") { + result.directives.push({ + parentComment, + type, + line: commentToken.loc.end.line, + column: commentToken.loc.end.column + 1, + ruleId, + justification + }); + } else { + result.directives.push({ + parentComment, + type, + line: commentToken.loc.start.line, + column: commentToken.loc.start.column + 1, + ruleId, + justification + }); + } + } else { + result.directiveProblems.push(createLintingProblem({ ruleId, loc: commentToken.loc })); + } + } + return result; +} + +/** + * Extract the directive and the justification from a given directive comment and trim them. + * @param {string} value The comment text to extract. + * @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification. + */ +function extractDirectiveComment(value) { + const match = /\s-{2,}\s/u.exec(value); + + if (!match) { + return { directivePart: value.trim(), justificationPart: "" }; + } + + const directive = value.slice(0, match.index).trim(); + const justification = value.slice(match.index + match[0].length).trim(); + + return { directivePart: directive, justificationPart: justification }; +} + +/** + * Parses comments in file to extract file-specific config of rules, globals + * and environments and merges them with global config; also code blocks + * where reporting is disabled or enabled and merges them with reporting config. + * @param {ASTNode} ast The top node of the AST. + * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules + * @param {string|null} warnInlineConfig If a string then it should warn directive comments as disabled. The string value is the config name what the setting came from. + * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, problems: LintMessage[], disableDirectives: DisableDirective[]}} + * A collection of the directive comments that were found, along with any problems that occurred when parsing + */ +function getDirectiveComments(ast, ruleMapper, warnInlineConfig) { + const configuredRules = {}; + const enabledGlobals = Object.create(null); + const exportedVariables = {}; + const problems = []; + const disableDirectives = []; + const validator = new ConfigValidator({ + builtInRules: Rules + }); + + ast.comments.filter(token => token.type !== "Shebang").forEach(comment => { + const { directivePart, justificationPart } = extractDirectiveComment(comment.value); + + const match = directivesPattern.exec(directivePart); + + if (!match) { + return; + } + const directiveText = match[1]; + const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText); + + if (comment.type === "Line" && !lineCommentSupported) { + return; + } + + if (warnInlineConfig) { + const kind = comment.type === "Block" ? `/*${directiveText}*/` : `//${directiveText}`; + + problems.push(createLintingProblem({ + ruleId: null, + message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`, + loc: comment.loc, + severity: 1 + })); + return; + } + + if (directiveText === "eslint-disable-line" && comment.loc.start.line !== comment.loc.end.line) { + const message = `${directiveText} comment should not span multiple lines.`; + + problems.push(createLintingProblem({ + ruleId: null, + message, + loc: comment.loc + })); + return; + } + + const directiveValue = directivePart.slice(match.index + directiveText.length); + + switch (directiveText) { + case "eslint-disable": + case "eslint-enable": + case "eslint-disable-next-line": + case "eslint-disable-line": { + const directiveType = directiveText.slice("eslint-".length); + const options = { commentToken: comment, type: directiveType, value: directiveValue, justification: justificationPart, ruleMapper }; + const { directives, directiveProblems } = createDisableDirectives(options); + + disableDirectives.push(...directives); + problems.push(...directiveProblems); + break; + } + + case "exported": + Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment)); + break; + + case "globals": + case "global": + for (const [id, { value }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) { + let normalizedValue; + + try { + normalizedValue = ConfigOps.normalizeConfigGlobal(value); + } catch (err) { + problems.push(createLintingProblem({ + ruleId: null, + loc: comment.loc, + message: err.message + })); + continue; + } + + if (enabledGlobals[id]) { + enabledGlobals[id].comments.push(comment); + enabledGlobals[id].value = normalizedValue; + } else { + enabledGlobals[id] = { + comments: [comment], + value: normalizedValue + }; + } + } + break; + + case "eslint": { + const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc); + + if (parseResult.success) { + Object.keys(parseResult.config).forEach(name => { + const rule = ruleMapper(name); + const ruleValue = parseResult.config[name]; + + if (!rule) { + problems.push(createLintingProblem({ ruleId: name, loc: comment.loc })); + return; + } + + try { + validator.validateRuleOptions(rule, name, ruleValue); + } catch (err) { + problems.push(createLintingProblem({ + ruleId: name, + message: err.message, + loc: comment.loc + })); + + // do not apply the config, if found invalid options. + return; + } + + configuredRules[name] = ruleValue; + }); + } else { + problems.push(parseResult.error); + } + + break; + } + + // no default + } + }); + + return { + configuredRules, + enabledGlobals, + exportedVariables, + problems, + disableDirectives + }; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {Parser} parser The parser which uses this options. + * @param {number} ecmaVersion ECMAScript version from the initial config + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(parser, ecmaVersion) { + + if (isEspree(parser)) { + if (ecmaVersion === "latest") { + return espree.latestEcmaVersion; + } + } + + /* + * Calculate ECMAScript edition number from official year version starting with + * ES2015, which corresponds with ES6 (or a difference of 2009). + */ + return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion; +} + +/** + * Normalize ECMAScript version from the initial config into languageOptions (year) + * format. + * @param {any} [ecmaVersion] ECMAScript version from the initial config + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersionForLanguageOptions(ecmaVersion) { + + switch (ecmaVersion) { + case 3: + return 3; + + // void 0 = no ecmaVersion specified so use the default + case 5: + case void 0: + return 5; + + default: + if (typeof ecmaVersion === "number") { + return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009; + } + } + + /* + * We default to the latest supported ecmaVersion for everything else. + * Remember, this is for languageOptions.ecmaVersion, which sets the version + * that is used for a number of processes inside of ESLint. It's normally + * safe to assume people want the latest unless otherwise specified. + */ + return espree.latestEcmaVersion + 2009; +} + +const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)(?:\*\/|$)/gsu; + +/** + * Checks whether or not there is a comment which has "eslint-env *" in a given text. + * @param {string} text A source code text to check. + * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment. + */ +function findEslintEnv(text) { + let match, retv; + + eslintEnvPattern.lastIndex = 0; + + while ((match = eslintEnvPattern.exec(text)) !== null) { + if (match[0].endsWith("*/")) { + retv = Object.assign( + retv || {}, + commentParser.parseListConfig(extractDirectiveComment(match[1]).directivePart) + ); + } + } + + return retv; +} + +/** + * Convert "/path/to/" to "". + * `CLIEngine#executeOnText()` method gives "/path/to/" if the filename + * was omitted because `configArray.extractConfig()` requires an absolute path. + * But the linter should pass `` to `RuleContext#filename` in that + * case. + * Also, code blocks can have their virtual filename. If the parent filename was + * ``, the virtual filename is `/0_foo.js` or something like (i.e., + * it's not an absolute path). + * @param {string} filename The filename to normalize. + * @returns {string} The normalized filename. + */ +function normalizeFilename(filename) { + const parts = filename.split(path.sep); + const index = parts.lastIndexOf(""); + + return index === -1 ? filename : parts.slice(index).join(path.sep); +} + +/** + * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a + * consistent shape. + * @param {VerifyOptions} providedOptions Options + * @param {ConfigData} config Config. + * @returns {Required & InternalOptions} Normalized options + */ +function normalizeVerifyOptions(providedOptions, config) { + + const linterOptions = config.linterOptions || config; + + // .noInlineConfig for eslintrc, .linterOptions.noInlineConfig for flat + const disableInlineConfig = linterOptions.noInlineConfig === true; + const ignoreInlineConfig = providedOptions.allowInlineConfig === false; + const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig + ? ` (${config.configNameOfNoInlineConfig})` + : ""; + + let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives; + + if (typeof reportUnusedDisableDirectives === "boolean") { + reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off"; + } + if (typeof reportUnusedDisableDirectives !== "string") { + reportUnusedDisableDirectives = + linterOptions.reportUnusedDisableDirectives + ? "warn" : "off"; + } + + return { + filename: normalizeFilename(providedOptions.filename || ""), + allowInlineConfig: !ignoreInlineConfig, + warnInlineConfig: disableInlineConfig && !ignoreInlineConfig + ? `your config${configNameOfNoInlineConfig}` + : null, + reportUnusedDisableDirectives, + disableFixes: Boolean(providedOptions.disableFixes) + }; +} + +/** + * Combines the provided parserOptions with the options from environments + * @param {Parser} parser The parser which uses this options. + * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config + * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments + * @returns {ParserOptions} Resulting parser options after merge + */ +function resolveParserOptions(parser, providedOptions, enabledEnvironments) { + + const parserOptionsFromEnv = enabledEnvironments + .filter(env => env.parserOptions) + .reduce((parserOptions, env) => merge(parserOptions, env.parserOptions), {}); + const mergedParserOptions = merge(parserOptionsFromEnv, providedOptions || {}); + const isModule = mergedParserOptions.sourceType === "module"; + + if (isModule) { + + /* + * can't have global return inside of modules + * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add) + */ + mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false }); + } + + mergedParserOptions.ecmaVersion = normalizeEcmaVersion(parser, mergedParserOptions.ecmaVersion); + + return mergedParserOptions; +} + +/** + * Converts parserOptions to languageOptions for backwards compatibility with eslintrc. + * @param {ConfigData} config Config object. + * @param {Object} config.globals Global variable definitions. + * @param {Parser} config.parser The parser to use. + * @param {ParserOptions} config.parserOptions The parserOptions to use. + * @returns {LanguageOptions} The languageOptions equivalent. + */ +function createLanguageOptions({ globals: configuredGlobals, parser, parserOptions }) { + + const { + ecmaVersion, + sourceType + } = parserOptions; + + return { + globals: configuredGlobals, + ecmaVersion: normalizeEcmaVersionForLanguageOptions(ecmaVersion), + sourceType, + parser, + parserOptions + }; +} + +/** + * Combines the provided globals object with the globals from environments + * @param {Record} providedGlobals The 'globals' key in a config + * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments + * @returns {Record} The resolved globals object + */ +function resolveGlobals(providedGlobals, enabledEnvironments) { + return Object.assign( + {}, + ...enabledEnvironments.filter(env => env.globals).map(env => env.globals), + providedGlobals + ); +} + +/** + * Strips Unicode BOM from a given text. + * @param {string} text A text to strip. + * @returns {string} The stripped text. + */ +function stripUnicodeBOM(text) { + + /* + * Check Unicode BOM. + * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF. + * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters + */ + if (text.charCodeAt(0) === 0xFEFF) { + return text.slice(1); + } + return text; +} + +/** + * Get the options for a rule (not including severity), if any + * @param {Array|number} ruleConfig rule configuration + * @returns {Array} of rule options, empty Array if none + */ +function getRuleOptions(ruleConfig) { + if (Array.isArray(ruleConfig)) { + return ruleConfig.slice(1); + } + return []; + +} + +/** + * Analyze scope of the given AST. + * @param {ASTNode} ast The `Program` node to analyze. + * @param {LanguageOptions} languageOptions The parser options. + * @param {Record} visitorKeys The visitor keys. + * @returns {ScopeManager} The analysis result. + */ +function analyzeScope(ast, languageOptions, visitorKeys) { + const parserOptions = languageOptions.parserOptions; + const ecmaFeatures = parserOptions.ecmaFeatures || {}; + const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION; + + return eslintScope.analyze(ast, { + ignoreEval: true, + nodejsScope: ecmaFeatures.globalReturn, + impliedStrict: ecmaFeatures.impliedStrict, + ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6, + sourceType: languageOptions.sourceType || "script", + childVisitorKeys: visitorKeys || evk.KEYS, + fallback: Traverser.getKeys + }); +} + +/** + * Parses text into an AST. Moved out here because the try-catch prevents + * optimization of functions, so it's best to keep the try-catch as isolated + * as possible + * @param {string} text The text to parse. + * @param {LanguageOptions} languageOptions Options to pass to the parser + * @param {string} filePath The path to the file being parsed. + * @returns {{success: false, error: LintMessage}|{success: true, sourceCode: SourceCode}} + * An object containing the AST and parser services if parsing was successful, or the error if parsing failed + * @private + */ +function parse(text, languageOptions, filePath) { + const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => `//${captured}`); + const { ecmaVersion, sourceType, parser } = languageOptions; + const parserOptions = Object.assign( + { ecmaVersion, sourceType }, + languageOptions.parserOptions, + { + loc: true, + range: true, + raw: true, + tokens: true, + comment: true, + eslintVisitorKeys: true, + eslintScopeManager: true, + filePath + } + ); + + /* + * Check for parsing errors first. If there's a parsing error, nothing + * else can happen. However, a parsing error does not throw an error + * from this method - it's just considered a fatal error message, a + * problem that ESLint identified just like any other. + */ + try { + debug("Parsing:", filePath); + const parseResult = (typeof parser.parseForESLint === "function") + ? parser.parseForESLint(textToParse, parserOptions) + : { ast: parser.parse(textToParse, parserOptions) }; + + debug("Parsing successful:", filePath); + const ast = parseResult.ast; + const parserServices = parseResult.services || {}; + const visitorKeys = parseResult.visitorKeys || evk.KEYS; + + debug("Scope analysis:", filePath); + const scopeManager = parseResult.scopeManager || analyzeScope(ast, languageOptions, visitorKeys); + + debug("Scope analysis successful:", filePath); + + return { + success: true, + + /* + * Save all values that `parseForESLint()` returned. + * If a `SourceCode` object is given as the first parameter instead of source code text, + * linter skips the parsing process and reuses the source code object. + * In that case, linter needs all the values that `parseForESLint()` returned. + */ + sourceCode: new SourceCode({ + text, + ast, + parserServices, + scopeManager, + visitorKeys + }) + }; + } catch (ex) { + + // If the message includes a leading line number, strip it: + const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`; + + debug("%s\n%s", message, ex.stack); + + return { + success: false, + error: { + ruleId: null, + fatal: true, + severity: 2, + message, + line: ex.lineNumber, + column: ex.column, + nodeType: null + } + }; + } +} + +/** + * Runs a rule, and gets its listeners + * @param {Rule} rule A normalized rule with a `create` method + * @param {Context} ruleContext The context that should be passed to the rule + * @throws {any} Any error during the rule's `create` + * @returns {Object} A map of selector listeners provided by the rule + */ +function createRuleListeners(rule, ruleContext) { + try { + return rule.create(ruleContext); + } catch (ex) { + ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`; + throw ex; + } +} + +// methods that exist on SourceCode object +const DEPRECATED_SOURCECODE_PASSTHROUGHS = { + getSource: "getText", + getSourceLines: "getLines", + getAllComments: "getAllComments", + getNodeByRangeIndex: "getNodeByRangeIndex", + getComments: "getComments", + getCommentsBefore: "getCommentsBefore", + getCommentsAfter: "getCommentsAfter", + getCommentsInside: "getCommentsInside", + getJSDocComment: "getJSDocComment", + getFirstToken: "getFirstToken", + getFirstTokens: "getFirstTokens", + getLastToken: "getLastToken", + getLastTokens: "getLastTokens", + getTokenAfter: "getTokenAfter", + getTokenBefore: "getTokenBefore", + getTokenByRangeStart: "getTokenByRangeStart", + getTokens: "getTokens", + getTokensAfter: "getTokensAfter", + getTokensBefore: "getTokensBefore", + getTokensBetween: "getTokensBetween" +}; + +const BASE_TRAVERSAL_CONTEXT = Object.freeze( + Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce( + (contextInfo, methodName) => + Object.assign(contextInfo, { + [methodName](...args) { + return this.sourceCode[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args); + } + }), + {} + ) +); + +/** + * Runs the given rules on the given SourceCode object + * @param {SourceCode} sourceCode A SourceCode object for the given text + * @param {Object} configuredRules The rules configuration + * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules + * @param {string | undefined} parserName The name of the parser in the config + * @param {LanguageOptions} languageOptions The options for parsing the code. + * @param {Object} settings The settings that were enabled in the config + * @param {string} filename The reported filename of the code + * @param {boolean} disableFixes If true, it doesn't make `fix` properties. + * @param {string | undefined} cwd cwd of the cli + * @param {string} physicalFilename The full path of the file on disk without any code block information + * @returns {LintMessage[]} An array of reported problems + */ +function runRules(sourceCode, configuredRules, ruleMapper, parserName, languageOptions, settings, filename, disableFixes, cwd, physicalFilename) { + const emitter = createEmitter(); + const nodeQueue = []; + let currentNode = sourceCode.ast; + + Traverser.traverse(sourceCode.ast, { + enter(node, parent) { + node.parent = parent; + nodeQueue.push({ isEntering: true, node }); + }, + leave(node) { + nodeQueue.push({ isEntering: false, node }); + }, + visitorKeys: sourceCode.visitorKeys + }); + + /* + * Create a frozen object with the ruleContext properties and methods that are shared by all rules. + * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the + * properties once for each rule. + */ + const sharedTraversalContext = Object.freeze( + Object.assign( + Object.create(BASE_TRAVERSAL_CONTEXT), + { + getAncestors: () => sourceCode.getAncestors(currentNode), + getDeclaredVariables: node => sourceCode.getDeclaredVariables(node), + getCwd: () => cwd, + cwd, + getFilename: () => filename, + filename, + getPhysicalFilename: () => physicalFilename || filename, + physicalFilename: physicalFilename || filename, + getScope: () => sourceCode.getScope(currentNode), + getSourceCode: () => sourceCode, + sourceCode, + markVariableAsUsed: name => sourceCode.markVariableAsUsed(name, currentNode), + parserOptions: { + ...languageOptions.parserOptions + }, + parserPath: parserName, + languageOptions, + parserServices: sourceCode.parserServices, + settings + } + ) + ); + + const lintingProblems = []; + + Object.keys(configuredRules).forEach(ruleId => { + const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]); + + // not load disabled rules + if (severity === 0) { + return; + } + + const rule = ruleMapper(ruleId); + + if (!rule) { + lintingProblems.push(createLintingProblem({ ruleId })); + return; + } + + const messageIds = rule.meta && rule.meta.messages; + let reportTranslator = null; + const ruleContext = Object.freeze( + Object.assign( + Object.create(sharedTraversalContext), + { + id: ruleId, + options: getRuleOptions(configuredRules[ruleId]), + report(...args) { + + /* + * Create a report translator lazily. + * In a vast majority of cases, any given rule reports zero errors on a given + * piece of code. Creating a translator lazily avoids the performance cost of + * creating a new translator function for each rule that usually doesn't get + * called. + * + * Using lazy report translators improves end-to-end performance by about 3% + * with Node 8.4.0. + */ + if (reportTranslator === null) { + reportTranslator = createReportTranslator({ + ruleId, + severity, + sourceCode, + messageIds, + disableFixes + }); + } + const problem = reportTranslator(...args); + + if (problem.fix && !(rule.meta && rule.meta.fixable)) { + throw new Error("Fixable rules must set the `meta.fixable` property to \"code\" or \"whitespace\"."); + } + if (problem.suggestions && !(rule.meta && rule.meta.hasSuggestions === true)) { + if (rule.meta && rule.meta.docs && typeof rule.meta.docs.suggestion !== "undefined") { + + // Encourage migration from the former property name. + throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint."); + } + throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`."); + } + lintingProblems.push(problem); + } + } + ) + ); + + const ruleListeners = timing.enabled ? timing.time(ruleId, createRuleListeners)(rule, ruleContext) : createRuleListeners(rule, ruleContext); + + /** + * Include `ruleId` in error logs + * @param {Function} ruleListener A rule method that listens for a node. + * @returns {Function} ruleListener wrapped in error handler + */ + function addRuleErrorHandler(ruleListener) { + return function ruleErrorHandler(...listenerArgs) { + try { + return ruleListener(...listenerArgs); + } catch (e) { + e.ruleId = ruleId; + throw e; + } + }; + } + + if (typeof ruleListeners === "undefined" || ruleListeners === null) { + throw new Error(`The create() function for rule '${ruleId}' did not return an object.`); + } + + // add all the selectors from the rule as listeners + Object.keys(ruleListeners).forEach(selector => { + const ruleListener = timing.enabled + ? timing.time(ruleId, ruleListeners[selector]) + : ruleListeners[selector]; + + emitter.on( + selector, + addRuleErrorHandler(ruleListener) + ); + }); + }); + + // only run code path analyzer if the top level node is "Program", skip otherwise + const eventGenerator = nodeQueue[0].node.type === "Program" + ? new CodePathAnalyzer(new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys })) + : new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys }); + + nodeQueue.forEach(traversalInfo => { + currentNode = traversalInfo.node; + + try { + if (traversalInfo.isEntering) { + eventGenerator.enterNode(currentNode); + } else { + eventGenerator.leaveNode(currentNode); + } + } catch (err) { + err.currentNode = currentNode; + throw err; + } + }); + + return lintingProblems; +} + +/** + * Ensure the source code to be a string. + * @param {string|SourceCode} textOrSourceCode The text or source code object. + * @returns {string} The source code text. + */ +function ensureText(textOrSourceCode) { + if (typeof textOrSourceCode === "object") { + const { hasBOM, text } = textOrSourceCode; + const bom = hasBOM ? "\uFEFF" : ""; + + return bom + text; + } + + return String(textOrSourceCode); +} + +/** + * Get an environment. + * @param {LinterInternalSlots} slots The internal slots of Linter. + * @param {string} envId The environment ID to get. + * @returns {Environment|null} The environment. + */ +function getEnv(slots, envId) { + return ( + (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) || + BuiltInEnvironments.get(envId) || + null + ); +} + +/** + * Get a rule. + * @param {LinterInternalSlots} slots The internal slots of Linter. + * @param {string} ruleId The rule ID to get. + * @returns {Rule|null} The rule. + */ +function getRule(slots, ruleId) { + return ( + (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) || + slots.ruleMap.get(ruleId) + ); +} + +/** + * Normalize the value of the cwd + * @param {string | undefined} cwd raw value of the cwd, path to a directory that should be considered as the current working directory, can be undefined. + * @returns {string | undefined} normalized cwd + */ +function normalizeCwd(cwd) { + if (cwd) { + return cwd; + } + if (typeof process === "object") { + return process.cwd(); + } + + // It's more explicit to assign the undefined + // eslint-disable-next-line no-undefined -- Consistently returning a value + return undefined; +} + +/** + * The map to store private data. + * @type {WeakMap} + */ +const internalSlotsMap = new WeakMap(); + +/** + * Throws an error when the given linter is in flat config mode. + * @param {Linter} linter The linter to check. + * @returns {void} + * @throws {Error} If the linter is in flat config mode. + */ +function assertEslintrcConfig(linter) { + const { configType } = internalSlotsMap.get(linter); + + if (configType === "flat") { + throw new Error("This method cannot be used with flat config. Add your entries directly into the config array."); + } +} + + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object that is responsible for verifying JavaScript text + * @name Linter + */ +class Linter { + + /** + * Initialize the Linter. + * @param {Object} [config] the config object + * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined. + * @param {"flat"|"eslintrc"} [config.configType="eslintrc"] the type of config used. + */ + constructor({ cwd, configType } = {}) { + internalSlotsMap.set(this, { + cwd: normalizeCwd(cwd), + lastConfigArray: null, + lastSourceCode: null, + lastSuppressedMessages: [], + configType, // TODO: Remove after flat config conversion + parserMap: new Map([["espree", espree]]), + ruleMap: new Rules() + }); + + this.version = pkg.version; + } + + /** + * Getter for package version. + * @static + * @returns {string} The version from package.json. + */ + static get version() { + return pkg.version; + } + + /** + * Same as linter.verify, except without support for processors. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) { + const slots = internalSlotsMap.get(this); + const config = providedConfig || {}; + const options = normalizeVerifyOptions(providedOptions, config); + let text; + + // evaluate arguments + if (typeof textOrSourceCode === "string") { + slots.lastSourceCode = null; + text = textOrSourceCode; + } else { + slots.lastSourceCode = textOrSourceCode; + text = textOrSourceCode.text; + } + + // Resolve parser. + let parserName = DEFAULT_PARSER_NAME; + let parser = espree; + + if (typeof config.parser === "object" && config.parser !== null) { + parserName = config.parser.filePath; + parser = config.parser.definition; + } else if (typeof config.parser === "string") { + if (!slots.parserMap.has(config.parser)) { + return [{ + ruleId: null, + fatal: true, + severity: 2, + message: `Configured parser '${config.parser}' was not found.`, + line: 0, + column: 0, + nodeType: null + }]; + } + parserName = config.parser; + parser = slots.parserMap.get(config.parser); + } + + // search and apply "eslint-env *". + const envInFile = options.allowInlineConfig && !options.warnInlineConfig + ? findEslintEnv(text) + : {}; + const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile); + const enabledEnvs = Object.keys(resolvedEnvConfig) + .filter(envName => resolvedEnvConfig[envName]) + .map(envName => getEnv(slots, envName)) + .filter(env => env); + + const parserOptions = resolveParserOptions(parser, config.parserOptions || {}, enabledEnvs); + const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs); + const settings = config.settings || {}; + const languageOptions = createLanguageOptions({ + globals: config.globals, + parser, + parserOptions + }); + + if (!slots.lastSourceCode) { + const parseResult = parse( + text, + languageOptions, + options.filename + ); + + if (!parseResult.success) { + return [parseResult.error]; + } + + slots.lastSourceCode = parseResult.sourceCode; + } else { + + /* + * If the given source code object as the first argument does not have scopeManager, analyze the scope. + * This is for backward compatibility (SourceCode is frozen so it cannot rebind). + */ + if (!slots.lastSourceCode.scopeManager) { + slots.lastSourceCode = new SourceCode({ + text: slots.lastSourceCode.text, + ast: slots.lastSourceCode.ast, + parserServices: slots.lastSourceCode.parserServices, + visitorKeys: slots.lastSourceCode.visitorKeys, + scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions) + }); + } + } + + const sourceCode = slots.lastSourceCode; + const commentDirectives = options.allowInlineConfig + ? getDirectiveComments(sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig) + : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] }; + + // augment global scope with declared global variables + addDeclaredGlobals( + sourceCode.scopeManager.scopes[0], + configuredGlobals, + { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals } + ); + + const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules); + + let lintingProblems; + + try { + lintingProblems = runRules( + sourceCode, + configuredRules, + ruleId => getRule(slots, ruleId), + parserName, + languageOptions, + settings, + options.filename, + options.disableFixes, + slots.cwd, + providedOptions.physicalFilename + ); + } catch (err) { + err.message += `\nOccurred while linting ${options.filename}`; + debug("An error occurred while traversing"); + debug("Filename:", options.filename); + if (err.currentNode) { + const { line } = err.currentNode.loc.start; + + debug("Line:", line); + err.message += `:${line}`; + } + debug("Parser Options:", parserOptions); + debug("Parser Path:", parserName); + debug("Settings:", settings); + + if (err.ruleId) { + err.message += `\nRule: "${err.ruleId}"`; + } + + throw err; + } + + return applyDisableDirectives({ + directives: commentDirectives.disableDirectives, + disableFixes: options.disableFixes, + problems: lintingProblems + .concat(commentDirectives.problems) + .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column), + reportUnusedDisableDirectives: options.reportUnusedDisableDirectives + }); + } + + /** + * Verifies the text against the rules specified by the second argument. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything. + * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked. + * If this is not set, the filename will default to '' in the rule context. If + * an object, then it has "filename", "allowInlineConfig", and some properties. + * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages. + */ + verify(textOrSourceCode, config, filenameOrOptions) { + debug("Verify"); + + const { configType } = internalSlotsMap.get(this); + + const options = typeof filenameOrOptions === "string" + ? { filename: filenameOrOptions } + : filenameOrOptions || {}; + + if (config) { + if (configType === "flat") { + + /* + * Because of how Webpack packages up the files, we can't + * compare directly to `FlatConfigArray` using `instanceof` + * because it's not the same `FlatConfigArray` as in the tests. + * So, we work around it by assuming an array is, in fact, a + * `FlatConfigArray` if it has a `getConfig()` method. + */ + let configArray = config; + + if (!Array.isArray(config) || typeof config.getConfig !== "function") { + configArray = new FlatConfigArray(config); + configArray.normalizeSync(); + } + + return this._distinguishSuppressedMessages(this._verifyWithFlatConfigArray(textOrSourceCode, configArray, options, true)); + } + + if (typeof config.extractConfig === "function") { + return this._distinguishSuppressedMessages(this._verifyWithConfigArray(textOrSourceCode, config, options)); + } + } + + /* + * If we get to here, it means `config` is just an object rather + * than a config array so we can go right into linting. + */ + + /* + * `Linter` doesn't support `overrides` property in configuration. + * So we cannot apply multiple processors. + */ + if (options.preprocess || options.postprocess) { + return this._distinguishSuppressedMessages(this._verifyWithProcessor(textOrSourceCode, config, options)); + } + return this._distinguishSuppressedMessages(this._verifyWithoutProcessors(textOrSourceCode, config, options)); + } + + /** + * Verify with a processor. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {FlatConfig} config The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {FlatConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options, configForRecursive) { + const filename = options.filename || ""; + const filenameToExpose = normalizeFilename(filename); + const physicalFilename = options.physicalFilename || filenameToExpose; + const text = ensureText(textOrSourceCode); + const preprocess = options.preprocess || (rawText => [rawText]); + const postprocess = options.postprocess || (messagesList => messagesList.flat()); + const filterCodeBlock = + options.filterCodeBlock || + (blockFilename => blockFilename.endsWith(".js")); + const originalExtname = path.extname(filename); + + let blocks; + + try { + blocks = preprocess(text, filenameToExpose); + } catch (ex) { + + // If the message includes a leading line number, strip it: + const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`; + + debug("%s\n%s", message, ex.stack); + + return [ + { + ruleId: null, + fatal: true, + severity: 2, + message, + line: ex.lineNumber, + column: ex.column, + nodeType: null + } + ]; + } + + const messageLists = blocks.map((block, i) => { + debug("A code block was found: %o", block.filename || "(unnamed)"); + + // Keep the legacy behavior. + if (typeof block === "string") { + return this._verifyWithFlatConfigArrayAndWithoutProcessors(block, config, options); + } + + const blockText = block.text; + const blockName = path.join(filename, `${i}_${block.filename}`); + + // Skip this block if filtered. + if (!filterCodeBlock(blockName, blockText)) { + debug("This code block was skipped."); + return []; + } + + // Resolve configuration again if the file content or extension was changed. + if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) { + debug("Resolving configuration again because the file content or extension was changed."); + return this._verifyWithFlatConfigArray( + blockText, + configForRecursive, + { ...options, filename: blockName, physicalFilename } + ); + } + + // Does lint. + return this._verifyWithFlatConfigArrayAndWithoutProcessors( + blockText, + config, + { ...options, filename: blockName, physicalFilename } + ); + }); + + return postprocess(messageLists, filenameToExpose); + } + + /** + * Same as linter.verify, except without support for processors. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {FlatConfig} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + _verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) { + const slots = internalSlotsMap.get(this); + const config = providedConfig || {}; + const options = normalizeVerifyOptions(providedOptions, config); + let text; + + // evaluate arguments + if (typeof textOrSourceCode === "string") { + slots.lastSourceCode = null; + text = textOrSourceCode; + } else { + slots.lastSourceCode = textOrSourceCode; + text = textOrSourceCode.text; + } + + const languageOptions = config.languageOptions; + + languageOptions.ecmaVersion = normalizeEcmaVersionForLanguageOptions( + languageOptions.ecmaVersion + ); + + /* + * add configured globals and language globals + * + * using Object.assign instead of object spread for performance reasons + * https://github.com/eslint/eslint/issues/16302 + */ + const configuredGlobals = Object.assign( + {}, + getGlobalsForEcmaVersion(languageOptions.ecmaVersion), + languageOptions.sourceType === "commonjs" ? globals.commonjs : void 0, + languageOptions.globals + ); + + // double check that there is a parser to avoid mysterious error messages + if (!languageOptions.parser) { + throw new TypeError(`No parser specified for ${options.filename}`); + } + + // Espree expects this information to be passed in + if (isEspree(languageOptions.parser)) { + const parserOptions = languageOptions.parserOptions; + + if (languageOptions.sourceType) { + + parserOptions.sourceType = languageOptions.sourceType; + + if ( + parserOptions.sourceType === "module" && + parserOptions.ecmaFeatures && + parserOptions.ecmaFeatures.globalReturn + ) { + parserOptions.ecmaFeatures.globalReturn = false; + } + } + } + + const settings = config.settings || {}; + + if (!slots.lastSourceCode) { + const parseResult = parse( + text, + languageOptions, + options.filename + ); + + if (!parseResult.success) { + return [parseResult.error]; + } + + slots.lastSourceCode = parseResult.sourceCode; + } else { + + /* + * If the given source code object as the first argument does not have scopeManager, analyze the scope. + * This is for backward compatibility (SourceCode is frozen so it cannot rebind). + */ + if (!slots.lastSourceCode.scopeManager) { + slots.lastSourceCode = new SourceCode({ + text: slots.lastSourceCode.text, + ast: slots.lastSourceCode.ast, + parserServices: slots.lastSourceCode.parserServices, + visitorKeys: slots.lastSourceCode.visitorKeys, + scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions) + }); + } + } + + const sourceCode = slots.lastSourceCode; + const commentDirectives = options.allowInlineConfig + ? getDirectiveComments( + sourceCode.ast, + ruleId => getRuleFromConfig(ruleId, config), + options.warnInlineConfig + ) + : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] }; + + // augment global scope with declared global variables + addDeclaredGlobals( + sourceCode.scopeManager.scopes[0], + configuredGlobals, + { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals } + ); + + const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules); + + let lintingProblems; + + try { + lintingProblems = runRules( + sourceCode, + configuredRules, + ruleId => getRuleFromConfig(ruleId, config), + void 0, + languageOptions, + settings, + options.filename, + options.disableFixes, + slots.cwd, + providedOptions.physicalFilename + ); + } catch (err) { + err.message += `\nOccurred while linting ${options.filename}`; + debug("An error occurred while traversing"); + debug("Filename:", options.filename); + if (err.currentNode) { + const { line } = err.currentNode.loc.start; + + debug("Line:", line); + err.message += `:${line}`; + } + debug("Parser Options:", languageOptions.parserOptions); + + // debug("Parser Path:", parserName); + debug("Settings:", settings); + + if (err.ruleId) { + err.message += `\nRule: "${err.ruleId}"`; + } + + throw err; + } + + return applyDisableDirectives({ + directives: commentDirectives.disableDirectives, + disableFixes: options.disableFixes, + problems: lintingProblems + .concat(commentDirectives.problems) + .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column), + reportUnusedDisableDirectives: options.reportUnusedDisableDirectives + }); + } + + /** + * Verify a given code with `ConfigArray`. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {ConfigArray} configArray The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithConfigArray(textOrSourceCode, configArray, options) { + debug("With ConfigArray: %s", options.filename); + + // Store the config array in order to get plugin envs and rules later. + internalSlotsMap.get(this).lastConfigArray = configArray; + + // Extract the final config for this file. + const config = configArray.extractConfig(options.filename); + const processor = + config.processor && + configArray.pluginProcessors.get(config.processor); + + // Verify. + if (processor) { + debug("Apply the processor: %o", config.processor); + const { preprocess, postprocess, supportsAutofix } = processor; + const disableFixes = options.disableFixes || !supportsAutofix; + + return this._verifyWithProcessor( + textOrSourceCode, + config, + { ...options, disableFixes, postprocess, preprocess }, + configArray + ); + } + return this._verifyWithoutProcessors(textOrSourceCode, config, options); + } + + /** + * Verify a given code with a flat config. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {FlatConfigArray} configArray The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {boolean} [firstCall=false] Indicates if this is being called directly + * from verify(). (TODO: Remove once eslintrc is removed.) + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithFlatConfigArray(textOrSourceCode, configArray, options, firstCall = false) { + debug("With flat config: %s", options.filename); + + // we need a filename to match configs against + const filename = options.filename || "__placeholder__.js"; + + // Store the config array in order to get plugin envs and rules later. + internalSlotsMap.get(this).lastConfigArray = configArray; + const config = configArray.getConfig(filename); + + if (!config) { + return [ + { + ruleId: null, + severity: 1, + message: `No matching configuration found for ${filename}.`, + line: 0, + column: 0, + nodeType: null + } + ]; + } + + // Verify. + if (config.processor) { + debug("Apply the processor: %o", config.processor); + const { preprocess, postprocess, supportsAutofix } = config.processor; + const disableFixes = options.disableFixes || !supportsAutofix; + + return this._verifyWithFlatConfigArrayAndProcessor( + textOrSourceCode, + config, + { ...options, filename, disableFixes, postprocess, preprocess }, + configArray + ); + } + + // check for options-based processing + if (firstCall && (options.preprocess || options.postprocess)) { + return this._verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options); + } + + return this._verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, config, options); + } + + /** + * Verify with a processor. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {ConfigData|ExtractedConfig} config The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) { + const filename = options.filename || ""; + const filenameToExpose = normalizeFilename(filename); + const physicalFilename = options.physicalFilename || filenameToExpose; + const text = ensureText(textOrSourceCode); + const preprocess = options.preprocess || (rawText => [rawText]); + const postprocess = options.postprocess || (messagesList => messagesList.flat()); + const filterCodeBlock = + options.filterCodeBlock || + (blockFilename => blockFilename.endsWith(".js")); + const originalExtname = path.extname(filename); + + let blocks; + + try { + blocks = preprocess(text, filenameToExpose); + } catch (ex) { + + // If the message includes a leading line number, strip it: + const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`; + + debug("%s\n%s", message, ex.stack); + + return [ + { + ruleId: null, + fatal: true, + severity: 2, + message, + line: ex.lineNumber, + column: ex.column, + nodeType: null + } + ]; + } + + const messageLists = blocks.map((block, i) => { + debug("A code block was found: %o", block.filename || "(unnamed)"); + + // Keep the legacy behavior. + if (typeof block === "string") { + return this._verifyWithoutProcessors(block, config, options); + } + + const blockText = block.text; + const blockName = path.join(filename, `${i}_${block.filename}`); + + // Skip this block if filtered. + if (!filterCodeBlock(blockName, blockText)) { + debug("This code block was skipped."); + return []; + } + + // Resolve configuration again if the file content or extension was changed. + if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) { + debug("Resolving configuration again because the file content or extension was changed."); + return this._verifyWithConfigArray( + blockText, + configForRecursive, + { ...options, filename: blockName, physicalFilename } + ); + } + + // Does lint. + return this._verifyWithoutProcessors( + blockText, + config, + { ...options, filename: blockName, physicalFilename } + ); + }); + + return postprocess(messageLists, filenameToExpose); + } + + /** + * Given a list of reported problems, distinguish problems between normal messages and suppressed messages. + * The normal messages will be returned and the suppressed messages will be stored as lastSuppressedMessages. + * @param {Array} problems A list of reported problems. + * @returns {LintMessage[]} A list of LintMessage. + */ + _distinguishSuppressedMessages(problems) { + const messages = []; + const suppressedMessages = []; + const slots = internalSlotsMap.get(this); + + for (const problem of problems) { + if (problem.suppressions) { + suppressedMessages.push(problem); + } else { + messages.push(problem); + } + } + + slots.lastSuppressedMessages = suppressedMessages; + + return messages; + } + + /** + * Gets the SourceCode object representing the parsed source. + * @returns {SourceCode} The SourceCode object. + */ + getSourceCode() { + return internalSlotsMap.get(this).lastSourceCode; + } + + /** + * Gets the list of SuppressedLintMessage produced in the last running. + * @returns {SuppressedLintMessage[]} The list of SuppressedLintMessage + */ + getSuppressedMessages() { + return internalSlotsMap.get(this).lastSuppressedMessages; + } + + /** + * Defines a new linting rule. + * @param {string} ruleId A unique rule identifier + * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers + * @returns {void} + */ + defineRule(ruleId, ruleModule) { + assertEslintrcConfig(this); + internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule); + } + + /** + * Defines many new linting rules. + * @param {Record} rulesToDefine map from unique rule identifier to rule + * @returns {void} + */ + defineRules(rulesToDefine) { + assertEslintrcConfig(this); + Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => { + this.defineRule(ruleId, rulesToDefine[ruleId]); + }); + } + + /** + * Gets an object with all loaded rules. + * @returns {Map} All loaded rules + */ + getRules() { + assertEslintrcConfig(this); + const { lastConfigArray, ruleMap } = internalSlotsMap.get(this); + + return new Map(function *() { + yield* ruleMap; + + if (lastConfigArray) { + yield* lastConfigArray.pluginRules; + } + }()); + } + + /** + * Define a new parser module + * @param {string} parserId Name of the parser + * @param {Parser} parserModule The parser object + * @returns {void} + */ + defineParser(parserId, parserModule) { + assertEslintrcConfig(this); + internalSlotsMap.get(this).parserMap.set(parserId, parserModule); + } + + /** + * Performs multiple autofix passes over the text until as many fixes as possible + * have been applied. + * @param {string} text The source text to apply fixes to. + * @param {ConfigData|ConfigArray|FlatConfigArray} config The ESLint config object to use. + * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use. + * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the + * SourceCodeFixer. + */ + verifyAndFix(text, config, options) { + let messages = [], + fixedResult, + fixed = false, + passNumber = 0, + currentText = text; + const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`; + const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true; + + /** + * This loop continues until one of the following is true: + * + * 1. No more fixes have been applied. + * 2. Ten passes have been made. + * + * That means anytime a fix is successfully applied, there will be another pass. + * Essentially, guaranteeing a minimum of two passes. + */ + do { + passNumber++; + + debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`); + messages = this.verify(currentText, config, options); + + debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`); + fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix); + + /* + * stop if there are any syntax errors. + * 'fixedResult.output' is a empty string. + */ + if (messages.length === 1 && messages[0].fatal) { + break; + } + + // keep track if any fixes were ever applied - important for return value + fixed = fixed || fixedResult.fixed; + + // update to use the fixed output instead of the original text + currentText = fixedResult.output; + + } while ( + fixedResult.fixed && + passNumber < MAX_AUTOFIX_PASSES + ); + + /* + * If the last result had fixes, we need to lint again to be sure we have + * the most up-to-date information. + */ + if (fixedResult.fixed) { + fixedResult.messages = this.verify(currentText, config, options); + } + + // ensure the last result properly reflects if fixes were done + fixedResult.fixed = fixed; + fixedResult.output = currentText; + + return fixedResult; + } +} + +module.exports = { + Linter, + + /** + * Get the internal slots of a given Linter instance for tests. + * @param {Linter} instance The Linter instance to get. + * @returns {LinterInternalSlots} The internal slots. + */ + getLinterInternalSlots(instance) { + return internalSlotsMap.get(instance); + } +}; diff --git a/node_modules/eslint/lib/linter/node-event-generator.js b/node_modules/eslint/lib/linter/node-event-generator.js new file mode 100644 index 0000000..d56bef2 --- /dev/null +++ b/node_modules/eslint/lib/linter/node-event-generator.js @@ -0,0 +1,354 @@ +/** + * @fileoverview The event generator for AST nodes. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const esquery = require("esquery"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * An object describing an AST selector + * @typedef {Object} ASTSelector + * @property {string} rawSelector The string that was parsed into this selector + * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering + * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector + * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match, + * or `null` if all node types could cause a match + * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector + * @property {number} identifierCount The total number of identifier queries in this selector + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Computes the union of one or more arrays + * @param {...any[]} arrays One or more arrays to union + * @returns {any[]} The union of the input arrays + */ +function union(...arrays) { + return [...new Set(arrays.flat())]; +} + +/** + * Computes the intersection of one or more arrays + * @param {...any[]} arrays One or more arrays to intersect + * @returns {any[]} The intersection of the input arrays + */ +function intersection(...arrays) { + if (arrays.length === 0) { + return []; + } + + let result = [...new Set(arrays[0])]; + + for (const array of arrays.slice(1)) { + result = result.filter(x => array.includes(x)); + } + return result; +} + +/** + * Gets the possible types of a selector + * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector + * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it + */ +function getPossibleTypes(parsedSelector) { + switch (parsedSelector.type) { + case "identifier": + return [parsedSelector.value]; + + case "matches": { + const typesForComponents = parsedSelector.selectors.map(getPossibleTypes); + + if (typesForComponents.every(Boolean)) { + return union(...typesForComponents); + } + return null; + } + + case "compound": { + const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent); + + // If all of the components could match any type, then the compound could also match any type. + if (!typesForComponents.length) { + return null; + } + + /* + * If at least one of the components could only match a particular type, the compound could only match + * the intersection of those types. + */ + return intersection(...typesForComponents); + } + + case "child": + case "descendant": + case "sibling": + case "adjacent": + return getPossibleTypes(parsedSelector.right); + + case "class": + if (parsedSelector.name === "function") { + return ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]; + } + + return null; + + default: + return null; + + } +} + +/** + * Counts the number of class, pseudo-class, and attribute queries in this selector + * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior + * @returns {number} The number of class, pseudo-class, and attribute queries in this selector + */ +function countClassAttributes(parsedSelector) { + switch (parsedSelector.type) { + case "child": + case "descendant": + case "sibling": + case "adjacent": + return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right); + + case "compound": + case "not": + case "matches": + return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0); + + case "attribute": + case "field": + case "nth-child": + case "nth-last-child": + return 1; + + default: + return 0; + } +} + +/** + * Counts the number of identifier queries in this selector + * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior + * @returns {number} The number of identifier queries + */ +function countIdentifiers(parsedSelector) { + switch (parsedSelector.type) { + case "child": + case "descendant": + case "sibling": + case "adjacent": + return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right); + + case "compound": + case "not": + case "matches": + return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0); + + case "identifier": + return 1; + + default: + return 0; + } +} + +/** + * Compares the specificity of two selector objects, with CSS-like rules. + * @param {ASTSelector} selectorA An AST selector descriptor + * @param {ASTSelector} selectorB Another AST selector descriptor + * @returns {number} + * a value less than 0 if selectorA is less specific than selectorB + * a value greater than 0 if selectorA is more specific than selectorB + * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically + * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically + */ +function compareSpecificity(selectorA, selectorB) { + return selectorA.attributeCount - selectorB.attributeCount || + selectorA.identifierCount - selectorB.identifierCount || + (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1); +} + +/** + * Parses a raw selector string, and throws a useful error if parsing fails. + * @param {string} rawSelector A raw AST selector + * @returns {Object} An object (from esquery) describing the matching behavior of this selector + * @throws {Error} An error if the selector is invalid + */ +function tryParseSelector(rawSelector) { + try { + return esquery.parse(rawSelector.replace(/:exit$/u, "")); + } catch (err) { + if (err.location && err.location.start && typeof err.location.start.offset === "number") { + throw new SyntaxError(`Syntax error in selector "${rawSelector}" at position ${err.location.start.offset}: ${err.message}`); + } + throw err; + } +} + +const selectorCache = new Map(); + +/** + * Parses a raw selector string, and returns the parsed selector along with specificity and type information. + * @param {string} rawSelector A raw AST selector + * @returns {ASTSelector} A selector descriptor + */ +function parseSelector(rawSelector) { + if (selectorCache.has(rawSelector)) { + return selectorCache.get(rawSelector); + } + + const parsedSelector = tryParseSelector(rawSelector); + + const result = { + rawSelector, + isExit: rawSelector.endsWith(":exit"), + parsedSelector, + listenerTypes: getPossibleTypes(parsedSelector), + attributeCount: countClassAttributes(parsedSelector), + identifierCount: countIdentifiers(parsedSelector) + }; + + selectorCache.set(rawSelector, result); + return result; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The event generator for AST nodes. + * This implements below interface. + * + * ```ts + * interface EventGenerator { + * emitter: SafeEmitter; + * enterNode(node: ASTNode): void; + * leaveNode(node: ASTNode): void; + * } + * ``` + */ +class NodeEventGenerator { + + /** + * @param {SafeEmitter} emitter + * An SafeEmitter which is the destination of events. This emitter must already + * have registered listeners for all of the events that it needs to listen for. + * (See lib/linter/safe-emitter.js for more details on `SafeEmitter`.) + * @param {ESQueryOptions} esqueryOptions `esquery` options for traversing custom nodes. + * @returns {NodeEventGenerator} new instance + */ + constructor(emitter, esqueryOptions) { + this.emitter = emitter; + this.esqueryOptions = esqueryOptions; + this.currentAncestry = []; + this.enterSelectorsByNodeType = new Map(); + this.exitSelectorsByNodeType = new Map(); + this.anyTypeEnterSelectors = []; + this.anyTypeExitSelectors = []; + + emitter.eventNames().forEach(rawSelector => { + const selector = parseSelector(rawSelector); + + if (selector.listenerTypes) { + const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType; + + selector.listenerTypes.forEach(nodeType => { + if (!typeMap.has(nodeType)) { + typeMap.set(nodeType, []); + } + typeMap.get(nodeType).push(selector); + }); + return; + } + const selectors = selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors; + + selectors.push(selector); + }); + + this.anyTypeEnterSelectors.sort(compareSpecificity); + this.anyTypeExitSelectors.sort(compareSpecificity); + this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity)); + this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity)); + } + + /** + * Checks a selector against a node, and emits it if it matches + * @param {ASTNode} node The node to check + * @param {ASTSelector} selector An AST selector descriptor + * @returns {void} + */ + applySelector(node, selector) { + if (esquery.matches(node, selector.parsedSelector, this.currentAncestry, this.esqueryOptions)) { + this.emitter.emit(selector.rawSelector, node); + } + } + + /** + * Applies all appropriate selectors to a node, in specificity order + * @param {ASTNode} node The node to check + * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited + * @returns {void} + */ + applySelectors(node, isExit) { + const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || []; + const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors; + + /* + * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor. + * Iterate through each of them, applying selectors in the right order. + */ + let selectorsByTypeIndex = 0; + let anyTypeSelectorsIndex = 0; + + while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) { + if ( + selectorsByTypeIndex >= selectorsByNodeType.length || + anyTypeSelectorsIndex < anyTypeSelectors.length && + compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0 + ) { + this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]); + } else { + this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]); + } + } + } + + /** + * Emits an event of entering AST node. + * @param {ASTNode} node A node which was entered. + * @returns {void} + */ + enterNode(node) { + if (node.parent) { + this.currentAncestry.unshift(node.parent); + } + this.applySelectors(node, false); + } + + /** + * Emits an event of leaving AST node. + * @param {ASTNode} node A node which was left. + * @returns {void} + */ + leaveNode(node) { + this.applySelectors(node, true); + this.currentAncestry.shift(); + } +} + +module.exports = NodeEventGenerator; diff --git a/node_modules/eslint/lib/linter/report-translator.js b/node_modules/eslint/lib/linter/report-translator.js new file mode 100644 index 0000000..41a43ea --- /dev/null +++ b/node_modules/eslint/lib/linter/report-translator.js @@ -0,0 +1,369 @@ +/** + * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("assert"); +const ruleFixer = require("./rule-fixer"); +const interpolate = require("./interpolate"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../shared/types").LintMessage} LintMessage */ + +/** + * An error message description + * @typedef {Object} MessageDescriptor + * @property {ASTNode} [node] The reported node + * @property {Location} loc The location of the problem. + * @property {string} message The problem message. + * @property {Object} [data] Optional data to use to fill in placeholders in the + * message. + * @property {Function} [fix] The function to call that creates a fix command. + * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes. + */ + +//------------------------------------------------------------------------------ +// Module Definition +//------------------------------------------------------------------------------ + + +/** + * Translates a multi-argument context.report() call into a single object argument call + * @param {...*} args A list of arguments passed to `context.report` + * @returns {MessageDescriptor} A normalized object containing report information + */ +function normalizeMultiArgReportCall(...args) { + + // If there is one argument, it is considered to be a new-style call already. + if (args.length === 1) { + + // Shallow clone the object to avoid surprises if reusing the descriptor + return Object.assign({}, args[0]); + } + + // If the second argument is a string, the arguments are interpreted as [node, message, data, fix]. + if (typeof args[1] === "string") { + return { + node: args[0], + message: args[1], + data: args[2], + fix: args[3] + }; + } + + // Otherwise, the arguments are interpreted as [node, loc, message, data, fix]. + return { + node: args[0], + loc: args[1], + message: args[2], + data: args[3], + fix: args[4] + }; +} + +/** + * Asserts that either a loc or a node was provided, and the node is valid if it was provided. + * @param {MessageDescriptor} descriptor A descriptor to validate + * @returns {void} + * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object + */ +function assertValidNodeInfo(descriptor) { + if (descriptor.node) { + assert(typeof descriptor.node === "object", "Node must be an object"); + } else { + assert(descriptor.loc, "Node must be provided when reporting error if location is not provided"); + } +} + +/** + * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties + * @param {MessageDescriptor} descriptor A descriptor for the report from a rule. + * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties + * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor. + */ +function normalizeReportLoc(descriptor) { + if (descriptor.loc) { + if (descriptor.loc.start) { + return descriptor.loc; + } + return { start: descriptor.loc, end: null }; + } + return descriptor.node.loc; +} + +/** + * Clones the given fix object. + * @param {Fix|null} fix The fix to clone. + * @returns {Fix|null} Deep cloned fix object or `null` if `null` or `undefined` was passed in. + */ +function cloneFix(fix) { + if (!fix) { + return null; + } + + return { + range: [fix.range[0], fix.range[1]], + text: fix.text + }; +} + +/** + * Check that a fix has a valid range. + * @param {Fix|null} fix The fix to validate. + * @returns {void} + */ +function assertValidFix(fix) { + if (fix) { + assert(fix.range && typeof fix.range[0] === "number" && typeof fix.range[1] === "number", `Fix has invalid range: ${JSON.stringify(fix, null, 2)}`); + } +} + +/** + * Compares items in a fixes array by range. + * @param {Fix} a The first message. + * @param {Fix} b The second message. + * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareFixesByRange(a, b) { + return a.range[0] - b.range[0] || a.range[1] - b.range[1]; +} + +/** + * Merges the given fixes array into one. + * @param {Fix[]} fixes The fixes to merge. + * @param {SourceCode} sourceCode The source code object to get the text between fixes. + * @returns {{text: string, range: number[]}} The merged fixes + */ +function mergeFixes(fixes, sourceCode) { + for (const fix of fixes) { + assertValidFix(fix); + } + + if (fixes.length === 0) { + return null; + } + if (fixes.length === 1) { + return cloneFix(fixes[0]); + } + + fixes.sort(compareFixesByRange); + + const originalText = sourceCode.text; + const start = fixes[0].range[0]; + const end = fixes[fixes.length - 1].range[1]; + let text = ""; + let lastPos = Number.MIN_SAFE_INTEGER; + + for (const fix of fixes) { + assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report."); + + if (fix.range[0] >= 0) { + text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]); + } + text += fix.text; + lastPos = fix.range[1]; + } + text += originalText.slice(Math.max(0, start, lastPos), end); + + return { range: [start, end], text }; +} + +/** + * Gets one fix object from the given descriptor. + * If the descriptor retrieves multiple fixes, this merges those to one. + * @param {MessageDescriptor} descriptor The report descriptor. + * @param {SourceCode} sourceCode The source code object to get text between fixes. + * @returns {({text: string, range: number[]}|null)} The fix for the descriptor + */ +function normalizeFixes(descriptor, sourceCode) { + if (typeof descriptor.fix !== "function") { + return null; + } + + // @type {null | Fix | Fix[] | IterableIterator} + const fix = descriptor.fix(ruleFixer); + + // Merge to one. + if (fix && Symbol.iterator in fix) { + return mergeFixes(Array.from(fix), sourceCode); + } + + assertValidFix(fix); + return cloneFix(fix); +} + +/** + * Gets an array of suggestion objects from the given descriptor. + * @param {MessageDescriptor} descriptor The report descriptor. + * @param {SourceCode} sourceCode The source code object to get text between fixes. + * @param {Object} messages Object of meta messages for the rule. + * @returns {Array} The suggestions for the descriptor + */ +function mapSuggestions(descriptor, sourceCode, messages) { + if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) { + return []; + } + + return descriptor.suggest + .map(suggestInfo => { + const computedDesc = suggestInfo.desc || messages[suggestInfo.messageId]; + + return { + ...suggestInfo, + desc: interpolate(computedDesc, suggestInfo.data), + fix: normalizeFixes(suggestInfo, sourceCode) + }; + }) + + // Remove suggestions that didn't provide a fix + .filter(({ fix }) => fix); +} + +/** + * Creates information about the report from a descriptor + * @param {Object} options Information about the problem + * @param {string} options.ruleId Rule ID + * @param {(0|1|2)} options.severity Rule severity + * @param {(ASTNode|null)} options.node Node + * @param {string} options.message Error message + * @param {string} [options.messageId] The error message ID. + * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location + * @param {{text: string, range: (number[]|null)}} options.fix The fix object + * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects + * @returns {LintMessage} Information about the report + */ +function createProblem(options) { + const problem = { + ruleId: options.ruleId, + severity: options.severity, + message: options.message, + line: options.loc.start.line, + column: options.loc.start.column + 1, + nodeType: options.node && options.node.type || null + }; + + /* + * If this isn’t in the conditional, some of the tests fail + * because `messageId` is present in the problem object + */ + if (options.messageId) { + problem.messageId = options.messageId; + } + + if (options.loc.end) { + problem.endLine = options.loc.end.line; + problem.endColumn = options.loc.end.column + 1; + } + + if (options.fix) { + problem.fix = options.fix; + } + + if (options.suggestions && options.suggestions.length > 0) { + problem.suggestions = options.suggestions; + } + + return problem; +} + +/** + * Validates that suggestions are properly defined. Throws if an error is detected. + * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data. + * @param {Object} messages Object of meta messages for the rule. + * @returns {void} + */ +function validateSuggestions(suggest, messages) { + if (suggest && Array.isArray(suggest)) { + suggest.forEach(suggestion => { + if (suggestion.messageId) { + const { messageId } = suggestion; + + if (!messages) { + throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`); + } + + if (!messages[messageId]) { + throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`); + } + + if (suggestion.desc) { + throw new TypeError("context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one."); + } + } else if (!suggestion.desc) { + throw new TypeError("context.report() called with a suggest option that doesn't have either a `desc` or `messageId`"); + } + + if (typeof suggestion.fix !== "function") { + throw new TypeError(`context.report() called with a suggest option without a fix function. See: ${suggestion}`); + } + }); + } +} + +/** + * Returns a function that converts the arguments of a `context.report` call from a rule into a reported + * problem for the Node.js API. + * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean}} metadata Metadata for the reported problem + * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted + * @returns {function(...args): LintMessage} Function that returns information about the report + */ + +module.exports = function createReportTranslator(metadata) { + + /* + * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant. + * The report translator itself (i.e. the function that `createReportTranslator` returns) gets + * called every time a rule reports a problem, which happens much less frequently (usually, the vast + * majority of rules don't report any problems for a given file). + */ + return (...args) => { + const descriptor = normalizeMultiArgReportCall(...args); + const messages = metadata.messageIds; + + assertValidNodeInfo(descriptor); + + let computedMessage; + + if (descriptor.messageId) { + if (!messages) { + throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata."); + } + const id = descriptor.messageId; + + if (descriptor.message) { + throw new TypeError("context.report() called with a message and a messageId. Please only pass one."); + } + if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) { + throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`); + } + computedMessage = messages[id]; + } else if (descriptor.message) { + computedMessage = descriptor.message; + } else { + throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem."); + } + + validateSuggestions(descriptor.suggest, messages); + + return createProblem({ + ruleId: metadata.ruleId, + severity: metadata.severity, + node: descriptor.node, + message: interpolate(computedMessage, descriptor.data), + messageId: descriptor.messageId, + loc: normalizeReportLoc(descriptor), + fix: metadata.disableFixes ? null : normalizeFixes(descriptor, metadata.sourceCode), + suggestions: metadata.disableFixes ? [] : mapSuggestions(descriptor, metadata.sourceCode, messages) + }); + }; +}; diff --git a/node_modules/eslint/lib/linter/rule-fixer.js b/node_modules/eslint/lib/linter/rule-fixer.js new file mode 100644 index 0000000..bdd80d1 --- /dev/null +++ b/node_modules/eslint/lib/linter/rule-fixer.js @@ -0,0 +1,140 @@ +/** + * @fileoverview An object that creates fix commands for rules. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Creates a fix command that inserts text at the specified index in the source text. + * @param {int} index The 0-based index at which to insert the new text. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + * @private + */ +function insertTextAt(index, text) { + return { + range: [index, index], + text + }; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Creates code fixing commands for rules. + */ + +const ruleFixer = Object.freeze({ + + /** + * Creates a fix command that inserts text after the given node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to insert after. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextAfter(nodeOrToken, text) { + return this.insertTextAfterRange(nodeOrToken.range, text); + }, + + /** + * Creates a fix command that inserts text after the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {int[]} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextAfterRange(range, text) { + return insertTextAt(range[1], text); + }, + + /** + * Creates a fix command that inserts text before the given node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to insert before. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextBefore(nodeOrToken, text) { + return this.insertTextBeforeRange(nodeOrToken.range, text); + }, + + /** + * Creates a fix command that inserts text before the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {int[]} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextBeforeRange(range, text) { + return insertTextAt(range[0], text); + }, + + /** + * Creates a fix command that replaces text at the node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + replaceText(nodeOrToken, text) { + return this.replaceTextRange(nodeOrToken.range, text); + }, + + /** + * Creates a fix command that replaces text at the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {int[]} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + replaceTextRange(range, text) { + return { + range, + text + }; + }, + + /** + * Creates a fix command that removes the node or token from the source. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @returns {Object} The fix command. + */ + remove(nodeOrToken) { + return this.removeRange(nodeOrToken.range); + }, + + /** + * Creates a fix command that removes the specified range of text from the source. + * The fix is not applied until applyFixes() is called. + * @param {int[]} range The range to remove, first item is start of range, second + * is end of range. + * @returns {Object} The fix command. + */ + removeRange(range) { + return { + range, + text: "" + }; + } + +}); + + +module.exports = ruleFixer; diff --git a/node_modules/eslint/lib/linter/rules.js b/node_modules/eslint/lib/linter/rules.js new file mode 100644 index 0000000..647bab6 --- /dev/null +++ b/node_modules/eslint/lib/linter/rules.js @@ -0,0 +1,80 @@ +/** + * @fileoverview Defines a storage for rules. + * @author Nicholas C. Zakas + * @author aladdin-add + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const builtInRules = require("../rules"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Normalizes a rule module to the new-style API + * @param {(Function|{create: Function})} rule A rule object, which can either be a function + * ("old-style") or an object with a `create` method ("new-style") + * @returns {{create: Function}} A new-style rule. + */ +function normalizeRule(rule) { + return typeof rule === "function" ? Object.assign({ create: rule }, rule) : rule; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A storage for rules. + */ +class Rules { + constructor() { + this._rules = Object.create(null); + } + + /** + * Registers a rule module for rule id in storage. + * @param {string} ruleId Rule id (file name). + * @param {Function} ruleModule Rule handler. + * @returns {void} + */ + define(ruleId, ruleModule) { + this._rules[ruleId] = normalizeRule(ruleModule); + } + + /** + * Access rule handler by id (file name). + * @param {string} ruleId Rule id (file name). + * @returns {{create: Function, schema: JsonSchema[]}} + * A rule. This is normalized to always have the new-style shape with a `create` method. + */ + get(ruleId) { + if (typeof this._rules[ruleId] === "string") { + this.define(ruleId, require(this._rules[ruleId])); + } + if (this._rules[ruleId]) { + return this._rules[ruleId]; + } + if (builtInRules.has(ruleId)) { + return builtInRules.get(ruleId); + } + + return null; + } + + *[Symbol.iterator]() { + yield* builtInRules; + + for (const ruleId of Object.keys(this._rules)) { + yield [ruleId, this.get(ruleId)]; + } + } +} + +module.exports = Rules; diff --git a/node_modules/eslint/lib/linter/safe-emitter.js b/node_modules/eslint/lib/linter/safe-emitter.js new file mode 100644 index 0000000..f4837c1 --- /dev/null +++ b/node_modules/eslint/lib/linter/safe-emitter.js @@ -0,0 +1,52 @@ +/** + * @fileoverview A variant of EventEmitter which does not give listeners information about each other + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * An event emitter + * @typedef {Object} SafeEmitter + * @property {(eventName: string, listenerFunc: Function) => void} on Adds a listener for a given event name + * @property {(eventName: string, arg1?: any, arg2?: any, arg3?: any) => void} emit Emits an event with a given name. + * This calls all the listeners that were listening for that name, with `arg1`, `arg2`, and `arg3` as arguments. + * @property {function(): string[]} eventNames Gets the list of event names that have registered listeners. + */ + +/** + * Creates an object which can listen for and emit events. + * This is similar to the EventEmitter API in Node's standard library, but it has a few differences. + * The goal is to allow multiple modules to attach arbitrary listeners to the same emitter, without + * letting the modules know about each other at all. + * 1. It has no special keys like `error` and `newListener`, which would allow modules to detect when + * another module throws an error or registers a listener. + * 2. It calls listener functions without any `this` value. (`EventEmitter` calls listeners with a + * `this` value of the emitter instance, which would give listeners access to other listeners.) + * @returns {SafeEmitter} An emitter + */ +module.exports = () => { + const listeners = Object.create(null); + + return Object.freeze({ + on(eventName, listener) { + if (eventName in listeners) { + listeners[eventName].push(listener); + } else { + listeners[eventName] = [listener]; + } + }, + emit(eventName, ...args) { + if (eventName in listeners) { + listeners[eventName].forEach(listener => listener(...args)); + } + }, + eventNames() { + return Object.keys(listeners); + } + }); +}; diff --git a/node_modules/eslint/lib/linter/source-code-fixer.js b/node_modules/eslint/lib/linter/source-code-fixer.js new file mode 100644 index 0000000..15386c9 --- /dev/null +++ b/node_modules/eslint/lib/linter/source-code-fixer.js @@ -0,0 +1,152 @@ +/** + * @fileoverview An object that caches and applies source code fixes. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("debug")("eslint:source-code-fixer"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const BOM = "\uFEFF"; + +/** + * Compares items in a messages array by range. + * @param {Message} a The first message. + * @param {Message} b The second message. + * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareMessagesByFixRange(a, b) { + return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1]; +} + +/** + * Compares items in a messages array by line and column. + * @param {Message} a The first message. + * @param {Message} b The second message. + * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareMessagesByLocation(a, b) { + return a.line - b.line || a.column - b.column; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Utility for apply fixes to source code. + * @constructor + */ +function SourceCodeFixer() { + Object.freeze(this); +} + +/** + * Applies the fixes specified by the messages to the given text. Tries to be + * smart about the fixes and won't apply fixes over the same area in the text. + * @param {string} sourceText The text to apply the changes to. + * @param {Message[]} messages The array of messages reported by ESLint. + * @param {boolean|Function} [shouldFix=true] Determines whether each message should be fixed + * @returns {Object} An object containing the fixed text and any unfixed messages. + */ +SourceCodeFixer.applyFixes = function(sourceText, messages, shouldFix) { + debug("Applying fixes"); + + if (shouldFix === false) { + debug("shouldFix parameter was false, not attempting fixes"); + return { + fixed: false, + messages, + output: sourceText + }; + } + + // clone the array + const remainingMessages = [], + fixes = [], + bom = sourceText.startsWith(BOM) ? BOM : "", + text = bom ? sourceText.slice(1) : sourceText; + let lastPos = Number.NEGATIVE_INFINITY, + output = bom; + + /** + * Try to use the 'fix' from a problem. + * @param {Message} problem The message object to apply fixes from + * @returns {boolean} Whether fix was successfully applied + */ + function attemptFix(problem) { + const fix = problem.fix; + const start = fix.range[0]; + const end = fix.range[1]; + + // Remain it as a problem if it's overlapped or it's a negative range + if (lastPos >= start || start > end) { + remainingMessages.push(problem); + return false; + } + + // Remove BOM. + if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) { + output = ""; + } + + // Make output to this fix. + output += text.slice(Math.max(0, lastPos), Math.max(0, start)); + output += fix.text; + lastPos = end; + return true; + } + + messages.forEach(problem => { + if (Object.prototype.hasOwnProperty.call(problem, "fix")) { + fixes.push(problem); + } else { + remainingMessages.push(problem); + } + }); + + if (fixes.length) { + debug("Found fixes to apply"); + let fixesWereApplied = false; + + for (const problem of fixes.sort(compareMessagesByFixRange)) { + if (typeof shouldFix !== "function" || shouldFix(problem)) { + attemptFix(problem); + + /* + * The only time attemptFix will fail is if a previous fix was + * applied which conflicts with it. So we can mark this as true. + */ + fixesWereApplied = true; + } else { + remainingMessages.push(problem); + } + } + output += text.slice(Math.max(0, lastPos)); + + return { + fixed: fixesWereApplied, + messages: remainingMessages.sort(compareMessagesByLocation), + output + }; + } + + debug("No fixes to apply"); + return { + fixed: false, + messages, + output: bom + text + }; + +}; + +module.exports = SourceCodeFixer; diff --git a/node_modules/eslint/lib/linter/timing.js b/node_modules/eslint/lib/linter/timing.js new file mode 100644 index 0000000..1076ff2 --- /dev/null +++ b/node_modules/eslint/lib/linter/timing.js @@ -0,0 +1,161 @@ +/** + * @fileoverview Tracks performance of individual rules. + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/* c8 ignore next */ +/** + * Align the string to left + * @param {string} str string to evaluate + * @param {int} len length of the string + * @param {string} ch delimiter character + * @returns {string} modified string + * @private + */ +function alignLeft(str, len, ch) { + return str + new Array(len - str.length + 1).join(ch || " "); +} + +/* c8 ignore next */ +/** + * Align the string to right + * @param {string} str string to evaluate + * @param {int} len length of the string + * @param {string} ch delimiter character + * @returns {string} modified string + * @private + */ +function alignRight(str, len, ch) { + return new Array(len - str.length + 1).join(ch || " ") + str; +} + +//------------------------------------------------------------------------------ +// Module definition +//------------------------------------------------------------------------------ + +const enabled = !!process.env.TIMING; + +const HEADERS = ["Rule", "Time (ms)", "Relative"]; +const ALIGN = [alignLeft, alignRight, alignRight]; + +/** + * Decide how many rules to show in the output list. + * @returns {number} the number of rules to show + */ +function getListSize() { + const MINIMUM_SIZE = 10; + + if (typeof process.env.TIMING !== "string") { + return MINIMUM_SIZE; + } + + if (process.env.TIMING.toLowerCase() === "all") { + return Number.POSITIVE_INFINITY; + } + + const TIMING_ENV_VAR_AS_INTEGER = Number.parseInt(process.env.TIMING, 10); + + return TIMING_ENV_VAR_AS_INTEGER > 10 ? TIMING_ENV_VAR_AS_INTEGER : MINIMUM_SIZE; +} + +/* c8 ignore next */ +/** + * display the data + * @param {Object} data Data object to be displayed + * @returns {void} prints modified string with console.log + * @private + */ +function display(data) { + let total = 0; + const rows = Object.keys(data) + .map(key => { + const time = data[key]; + + total += time; + return [key, time]; + }) + .sort((a, b) => b[1] - a[1]) + .slice(0, getListSize()); + + rows.forEach(row => { + row.push(`${(row[1] * 100 / total).toFixed(1)}%`); + row[1] = row[1].toFixed(3); + }); + + rows.unshift(HEADERS); + + const widths = []; + + rows.forEach(row => { + const len = row.length; + + for (let i = 0; i < len; i++) { + const n = row[i].length; + + if (!widths[i] || n > widths[i]) { + widths[i] = n; + } + } + }); + + const table = rows.map(row => ( + row + .map((cell, index) => ALIGN[index](cell, widths[index])) + .join(" | ") + )); + + table.splice(1, 0, widths.map((width, index) => { + const extraAlignment = index !== 0 && index !== widths.length - 1 ? 2 : 1; + + return ALIGN[index](":", width + extraAlignment, "-"); + }).join("|")); + + console.log(table.join("\n")); // eslint-disable-line no-console -- Debugging function +} + +/* c8 ignore next */ +module.exports = (function() { + + const data = Object.create(null); + + /** + * Time the run + * @param {any} key key from the data object + * @param {Function} fn function to be called + * @returns {Function} function to be executed + * @private + */ + function time(key, fn) { + if (typeof data[key] === "undefined") { + data[key] = 0; + } + + return function(...args) { + let t = process.hrtime(); + const result = fn(...args); + + t = process.hrtime(t); + data[key] += t[0] * 1e3 + t[1] / 1e6; + return result; + }; + } + + if (enabled) { + process.on("exit", () => { + display(data); + }); + } + + return { + time, + enabled, + getListSize + }; + +}()); diff --git a/node_modules/eslint/lib/options.js b/node_modules/eslint/lib/options.js new file mode 100644 index 0000000..2bc4018 --- /dev/null +++ b/node_modules/eslint/lib/options.js @@ -0,0 +1,377 @@ +/** + * @fileoverview Options configuration for optionator. + * @author George Zahariev + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const optionator = require("optionator"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * The options object parsed by Optionator. + * @typedef {Object} ParsedCLIOptions + * @property {boolean} cache Only check changed files + * @property {string} cacheFile Path to the cache file. Deprecated: use --cache-location + * @property {string} [cacheLocation] Path to the cache file or directory + * @property {"metadata" | "content"} cacheStrategy Strategy to use for detecting changed files in the cache + * @property {boolean} [color] Force enabling/disabling of color + * @property {string} [config] Use this configuration, overriding .eslintrc.* config options if present + * @property {boolean} debug Output debugging information + * @property {string[]} [env] Specify environments + * @property {boolean} envInfo Output execution environment information + * @property {boolean} errorOnUnmatchedPattern Prevent errors when pattern is unmatched + * @property {boolean} eslintrc Disable use of configuration from .eslintrc.* + * @property {string[]} [ext] Specify JavaScript file extensions + * @property {boolean} fix Automatically fix problems + * @property {boolean} fixDryRun Automatically fix problems without saving the changes to the file system + * @property {("directive" | "problem" | "suggestion" | "layout")[]} [fixType] Specify the types of fixes to apply (directive, problem, suggestion, layout) + * @property {string} format Use a specific output format + * @property {string[]} [global] Define global variables + * @property {boolean} [help] Show help + * @property {boolean} ignore Disable use of ignore files and patterns + * @property {string} [ignorePath] Specify path of ignore file + * @property {string[]} [ignorePattern] Pattern of files to ignore (in addition to those in .eslintignore) + * @property {boolean} init Run config initialization wizard + * @property {boolean} inlineConfig Prevent comments from changing config or rules + * @property {number} maxWarnings Number of warnings to trigger nonzero exit code + * @property {string} [outputFile] Specify file to write report to + * @property {string} [parser] Specify the parser to be used + * @property {Object} [parserOptions] Specify parser options + * @property {string[]} [plugin] Specify plugins + * @property {string} [printConfig] Print the configuration for the given file + * @property {boolean | undefined} reportUnusedDisableDirectives Adds reported errors for unused eslint-disable directives + * @property {string} [resolvePluginsRelativeTo] A folder where plugins should be resolved from, CWD by default + * @property {Object} [rule] Specify rules + * @property {string[]} [rulesdir] Load additional rules from this directory. Deprecated: Use rules from plugins + * @property {boolean} stdin Lint code provided on + * @property {string} [stdinFilename] Specify filename to process STDIN as + * @property {boolean} quiet Report errors only + * @property {boolean} [version] Output the version number + * @property {string[]} _ Positional filenames or patterns + */ + +//------------------------------------------------------------------------------ +// Initialization and Public Interface +//------------------------------------------------------------------------------ + +// exports "parse(args)", "generateHelp()", and "generateHelpForOption(optionName)" + +/** + * Creates the CLI options for ESLint. + * @param {boolean} usingFlatConfig Indicates if flat config is being used. + * @returns {Object} The optionator instance. + */ +module.exports = function(usingFlatConfig) { + + let lookupFlag; + + if (usingFlatConfig) { + lookupFlag = { + option: "config-lookup", + type: "Boolean", + default: "true", + description: "Disable look up for eslint.config.js" + }; + } else { + lookupFlag = { + option: "eslintrc", + type: "Boolean", + default: "true", + description: "Disable use of configuration from .eslintrc.*" + }; + } + + let envFlag; + + if (!usingFlatConfig) { + envFlag = { + option: "env", + type: "[String]", + description: "Specify environments" + }; + } + + let extFlag; + + if (!usingFlatConfig) { + extFlag = { + option: "ext", + type: "[String]", + description: "Specify JavaScript file extensions" + }; + } + + let resolvePluginsFlag; + + if (!usingFlatConfig) { + resolvePluginsFlag = { + option: "resolve-plugins-relative-to", + type: "path::String", + description: "A folder where plugins should be resolved from, CWD by default" + }; + } + + let rulesDirFlag; + + if (!usingFlatConfig) { + rulesDirFlag = { + option: "rulesdir", + type: "[path::String]", + description: "Load additional rules from this directory. Deprecated: Use rules from plugins" + }; + } + + let ignorePathFlag; + + if (!usingFlatConfig) { + ignorePathFlag = { + option: "ignore-path", + type: "path::String", + description: "Specify path of ignore file" + }; + } + + return optionator({ + prepend: "eslint [options] file.js [file.js] [dir]", + defaults: { + concatRepeatedArrays: true, + mergeRepeatedObjects: true + }, + options: [ + { + heading: "Basic configuration" + }, + lookupFlag, + { + option: "config", + alias: "c", + type: "path::String", + description: usingFlatConfig + ? "Use this configuration instead of eslint.config.js" + : "Use this configuration, overriding .eslintrc.* config options if present" + }, + envFlag, + extFlag, + { + option: "global", + type: "[String]", + description: "Define global variables" + }, + { + option: "parser", + type: "String", + description: "Specify the parser to be used" + }, + { + option: "parser-options", + type: "Object", + description: "Specify parser options" + }, + resolvePluginsFlag, + { + heading: "Specify Rules and Plugins" + }, + { + option: "plugin", + type: "[String]", + description: "Specify plugins" + }, + { + option: "rule", + type: "Object", + description: "Specify rules" + }, + rulesDirFlag, + { + heading: "Fix Problems" + }, + { + option: "fix", + type: "Boolean", + default: false, + description: "Automatically fix problems" + }, + { + option: "fix-dry-run", + type: "Boolean", + default: false, + description: "Automatically fix problems without saving the changes to the file system" + }, + { + option: "fix-type", + type: "Array", + description: "Specify the types of fixes to apply (directive, problem, suggestion, layout)" + }, + { + heading: "Ignore Files" + }, + ignorePathFlag, + { + option: "ignore", + type: "Boolean", + default: "true", + description: "Disable use of ignore files and patterns" + }, + { + option: "ignore-pattern", + type: "[String]", + description: "Pattern of files to ignore (in addition to those in .eslintignore)", + concatRepeatedArrays: [true, { + oneValuePerFlag: true + }] + }, + { + heading: "Use stdin" + }, + { + option: "stdin", + type: "Boolean", + default: "false", + description: "Lint code provided on " + }, + { + option: "stdin-filename", + type: "String", + description: "Specify filename to process STDIN as" + }, + { + heading: "Handle Warnings" + }, + { + option: "quiet", + type: "Boolean", + default: "false", + description: "Report errors only" + }, + { + option: "max-warnings", + type: "Int", + default: "-1", + description: "Number of warnings to trigger nonzero exit code" + }, + { + heading: "Output" + }, + { + option: "output-file", + alias: "o", + type: "path::String", + description: "Specify file to write report to" + }, + { + option: "format", + alias: "f", + type: "String", + default: "stylish", + description: "Use a specific output format" + }, + { + option: "color", + type: "Boolean", + alias: "no-color", + description: "Force enabling/disabling of color" + }, + { + heading: "Inline configuration comments" + }, + { + option: "inline-config", + type: "Boolean", + default: "true", + description: "Prevent comments from changing config or rules" + }, + { + option: "report-unused-disable-directives", + type: "Boolean", + default: void 0, + description: "Adds reported errors for unused eslint-disable directives" + }, + { + heading: "Caching" + }, + { + option: "cache", + type: "Boolean", + default: "false", + description: "Only check changed files" + }, + { + option: "cache-file", + type: "path::String", + default: ".eslintcache", + description: "Path to the cache file. Deprecated: use --cache-location" + }, + { + option: "cache-location", + type: "path::String", + description: "Path to the cache file or directory" + }, + { + option: "cache-strategy", + dependsOn: ["cache"], + type: "String", + default: "metadata", + enum: ["metadata", "content"], + description: "Strategy to use for detecting changed files in the cache" + }, + { + heading: "Miscellaneous" + }, + { + option: "init", + type: "Boolean", + default: "false", + description: "Run config initialization wizard" + }, + { + option: "env-info", + type: "Boolean", + default: "false", + description: "Output execution environment information" + }, + { + option: "error-on-unmatched-pattern", + type: "Boolean", + default: "true", + description: "Prevent errors when pattern is unmatched" + }, + { + option: "exit-on-fatal-error", + type: "Boolean", + default: "false", + description: "Exit with exit code 2 in case of fatal error" + }, + { + option: "debug", + type: "Boolean", + default: false, + description: "Output debugging information" + }, + { + option: "help", + alias: "h", + type: "Boolean", + description: "Show help" + }, + { + option: "version", + alias: "v", + type: "Boolean", + description: "Output the version number" + }, + { + option: "print-config", + type: "path::String", + description: "Print the configuration for the given file" + } + ].filter(value => !!value) + }); +}; diff --git a/node_modules/eslint/lib/rule-tester/flat-rule-tester.js b/node_modules/eslint/lib/rule-tester/flat-rule-tester.js new file mode 100644 index 0000000..f143873 --- /dev/null +++ b/node_modules/eslint/lib/rule-tester/flat-rule-tester.js @@ -0,0 +1,1043 @@ +/** + * @fileoverview Mocha/Jest test wrapper + * @author Ilya Volodin + */ +"use strict"; + +/* globals describe, it -- Mocha globals */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const + assert = require("assert"), + util = require("util"), + equal = require("fast-deep-equal"), + Traverser = require("../shared/traverser"), + { getRuleOptionsSchema } = require("../config/flat-config-helpers"), + { Linter, SourceCodeFixer, interpolate } = require("../linter"); +const { FlatConfigArray } = require("../config/flat-config-array"); +const { defaultConfig } = require("../config/default-config"); + +const ajv = require("../shared/ajv")({ strictDefaults: true }); + +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); +const { SourceCode } = require("../source-code"); +const { ConfigArraySymbol } = require("@humanwhocodes/config-array"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../shared/types").Parser} Parser */ +/** @typedef {import("../shared/types").LanguageOptions} LanguageOptions */ + + +/** + * A test case that is expected to pass lint. + * @typedef {Object} ValidTestCase + * @property {string} [name] Name for the test case. + * @property {string} code Code for the test case. + * @property {any[]} [options] Options for the test case. + * @property {LanguageOptions} [languageOptions] The language options to use in the test case. + * @property {{ [name: string]: any }} [settings] Settings for the test case. + * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. + * @property {boolean} [only] Run only this test case or the subset of test cases with this property. + */ + +/** + * A test case that is expected to fail lint. + * @typedef {Object} InvalidTestCase + * @property {string} [name] Name for the test case. + * @property {string} code Code for the test case. + * @property {number | Array} errors Expected errors. + * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested. + * @property {any[]} [options] Options for the test case. + * @property {{ [name: string]: any }} [settings] Settings for the test case. + * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. + * @property {LanguageOptions} [languageOptions] The language options to use in the test case. + * @property {boolean} [only] Run only this test case or the subset of test cases with this property. + */ + +/** + * A description of a reported error used in a rule tester test. + * @typedef {Object} TestCaseError + * @property {string | RegExp} [message] Message. + * @property {string} [messageId] Message ID. + * @property {string} [type] The type of the reported AST node. + * @property {{ [name: string]: string }} [data] The data used to fill the message template. + * @property {number} [line] The 1-based line number of the reported start location. + * @property {number} [column] The 1-based column number of the reported start location. + * @property {number} [endLine] The 1-based line number of the reported end location. + * @property {number} [endColumn] The 1-based column number of the reported end location. + */ + +//------------------------------------------------------------------------------ +// Private Members +//------------------------------------------------------------------------------ + +/* + * testerDefaultConfig must not be modified as it allows to reset the tester to + * the initial default configuration + */ +const testerDefaultConfig = { rules: {} }; + +/* + * RuleTester uses this config as its default. This can be overwritten via + * setDefaultConfig(). + */ +let sharedDefaultConfig = { rules: {} }; + +/* + * List every parameters possible on a test case that are not related to eslint + * configuration + */ +const RuleTesterParameters = [ + "name", + "code", + "filename", + "options", + "errors", + "output", + "only" +]; + +/* + * All allowed property names in error objects. + */ +const errorObjectParameters = new Set([ + "message", + "messageId", + "data", + "type", + "line", + "column", + "endLine", + "endColumn", + "suggestions" +]); +const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`; + +/* + * All allowed property names in suggestion objects. + */ +const suggestionObjectParameters = new Set([ + "desc", + "messageId", + "data", + "output" +]); +const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`; + +const hasOwnProperty = Function.call.bind(Object.hasOwnProperty); + +/** + * Clones a given value deeply. + * Note: This ignores `parent` property. + * @param {any} x A value to clone. + * @returns {any} A cloned value. + */ +function cloneDeeplyExcludesParent(x) { + if (typeof x === "object" && x !== null) { + if (Array.isArray(x)) { + return x.map(cloneDeeplyExcludesParent); + } + + const retv = {}; + + for (const key in x) { + if (key !== "parent" && hasOwnProperty(x, key)) { + retv[key] = cloneDeeplyExcludesParent(x[key]); + } + } + + return retv; + } + + return x; +} + +/** + * Freezes a given value deeply. + * @param {any} x A value to freeze. + * @returns {void} + */ +function freezeDeeply(x) { + if (typeof x === "object" && x !== null) { + if (Array.isArray(x)) { + x.forEach(freezeDeeply); + } else { + for (const key in x) { + if (key !== "parent" && hasOwnProperty(x, key)) { + freezeDeeply(x[key]); + } + } + } + Object.freeze(x); + } +} + +/** + * Replace control characters by `\u00xx` form. + * @param {string} text The text to sanitize. + * @returns {string} The sanitized text. + */ +function sanitize(text) { + if (typeof text !== "string") { + return ""; + } + return text.replace( + /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls + c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}` + ); +} + +/** + * Define `start`/`end` properties as throwing error. + * @param {string} objName Object name used for error messages. + * @param {ASTNode} node The node to define. + * @returns {void} + */ +function defineStartEndAsError(objName, node) { + Object.defineProperties(node, { + start: { + get() { + throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`); + }, + configurable: true, + enumerable: false + }, + end: { + get() { + throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`); + }, + configurable: true, + enumerable: false + } + }); +} + + +/** + * Define `start`/`end` properties of all nodes of the given AST as throwing error. + * @param {ASTNode} ast The root node to errorize `start`/`end` properties. + * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast. + * @returns {void} + */ +function defineStartEndAsErrorInTree(ast, visitorKeys) { + Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") }); + ast.tokens.forEach(defineStartEndAsError.bind(null, "token")); + ast.comments.forEach(defineStartEndAsError.bind(null, "token")); +} + +/** + * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes. + * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties. + * @param {Parser} parser Parser object. + * @returns {Parser} Wrapped parser object. + */ +function wrapParser(parser) { + + if (typeof parser.parseForESLint === "function") { + return { + [parserSymbol]: parser, + parseForESLint(...args) { + const ret = parser.parseForESLint(...args); + + defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys); + return ret; + } + }; + } + + return { + [parserSymbol]: parser, + parse(...args) { + const ast = parser.parse(...args); + + defineStartEndAsErrorInTree(ast); + return ast; + } + }; +} + +/** + * Function to replace `SourceCode.prototype.getComments`. + * @returns {void} + * @throws {Error} Deprecation message. + */ +function getCommentsDeprecation() { + throw new Error( + "`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead." + ); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +// default separators for testing +const DESCRIBE = Symbol("describe"); +const IT = Symbol("it"); +const IT_ONLY = Symbol("itOnly"); + +/** + * This is `it` default handler if `it` don't exist. + * @this {Mocha} + * @param {string} text The description of the test case. + * @param {Function} method The logic of the test case. + * @throws {Error} Any error upon execution of `method`. + * @returns {any} Returned value of `method`. + */ +function itDefaultHandler(text, method) { + try { + return method.call(this); + } catch (err) { + if (err instanceof assert.AssertionError) { + err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`; + } + throw err; + } +} + +/** + * This is `describe` default handler if `describe` don't exist. + * @this {Mocha} + * @param {string} text The description of the test case. + * @param {Function} method The logic of the test case. + * @returns {any} Returned value of `method`. + */ +function describeDefaultHandler(text, method) { + return method.call(this); +} + +/** + * Mocha test wrapper. + */ +class FlatRuleTester { + + /** + * Creates a new instance of RuleTester. + * @param {Object} [testerConfig] Optional, extra configuration for the tester + */ + constructor(testerConfig = {}) { + + /** + * The configuration to use for this tester. Combination of the tester + * configuration and the default configuration. + * @type {Object} + */ + this.testerConfig = [ + sharedDefaultConfig, + testerConfig, + { rules: { "rule-tester/validate-ast": "error" } } + ]; + + this.linter = new Linter({ configType: "flat" }); + } + + /** + * Set the configuration to use for all future tests + * @param {Object} config the configuration to use. + * @throws {TypeError} If non-object config. + * @returns {void} + */ + static setDefaultConfig(config) { + if (typeof config !== "object" || config === null) { + throw new TypeError("FlatRuleTester.setDefaultConfig: config must be an object"); + } + sharedDefaultConfig = config; + + // Make sure the rules object exists since it is assumed to exist later + sharedDefaultConfig.rules = sharedDefaultConfig.rules || {}; + } + + /** + * Get the current configuration used for all tests + * @returns {Object} the current configuration + */ + static getDefaultConfig() { + return sharedDefaultConfig; + } + + /** + * Reset the configuration to the initial configuration of the tester removing + * any changes made until now. + * @returns {void} + */ + static resetDefaultConfig() { + sharedDefaultConfig = { + rules: { + ...testerDefaultConfig.rules + } + }; + } + + + /* + * If people use `mocha test.js --watch` command, `describe` and `it` function + * instances are different for each execution. So `describe` and `it` should get fresh instance + * always. + */ + static get describe() { + return ( + this[DESCRIBE] || + (typeof describe === "function" ? describe : describeDefaultHandler) + ); + } + + static set describe(value) { + this[DESCRIBE] = value; + } + + static get it() { + return ( + this[IT] || + (typeof it === "function" ? it : itDefaultHandler) + ); + } + + static set it(value) { + this[IT] = value; + } + + /** + * Adds the `only` property to a test to run it in isolation. + * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself. + * @returns {ValidTestCase | InvalidTestCase} The test with `only` set. + */ + static only(item) { + if (typeof item === "string") { + return { code: item, only: true }; + } + + return { ...item, only: true }; + } + + static get itOnly() { + if (typeof this[IT_ONLY] === "function") { + return this[IT_ONLY]; + } + if (typeof this[IT] === "function" && typeof this[IT].only === "function") { + return Function.bind.call(this[IT].only, this[IT]); + } + if (typeof it === "function" && typeof it.only === "function") { + return Function.bind.call(it.only, it); + } + + if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") { + throw new Error( + "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" + + "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more." + ); + } + if (typeof it === "function") { + throw new Error("The current test framework does not support exclusive tests with `only`."); + } + throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha."); + } + + static set itOnly(value) { + this[IT_ONLY] = value; + } + + + /** + * Adds a new rule test to execute. + * @param {string} ruleName The name of the rule to run. + * @param {Function} rule The rule to test. + * @param {{ + * valid: (ValidTestCase | string)[], + * invalid: InvalidTestCase[] + * }} test The collection of tests to run. + * @throws {TypeError|Error} If non-object `test`, or if a required + * scenario of the given type is missing. + * @returns {void} + */ + run(ruleName, rule, test) { + + const testerConfig = this.testerConfig, + requiredScenarios = ["valid", "invalid"], + scenarioErrors = [], + linter = this.linter, + ruleId = `rule-to-test/${ruleName}`; + + if (!test || typeof test !== "object") { + throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`); + } + + requiredScenarios.forEach(scenarioType => { + if (!test[scenarioType]) { + scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`); + } + }); + + if (scenarioErrors.length > 0) { + throw new Error([ + `Test Scenarios for rule ${ruleName} is invalid:` + ].concat(scenarioErrors).join("\n")); + } + + const baseConfig = [ + { + plugins: { + + // copy root plugin over + "@": { + + /* + * Parsers are wrapped to detect more errors, so this needs + * to be a new object for each call to run(), otherwise the + * parsers will be wrapped multiple times. + */ + parsers: { + ...defaultConfig[0].plugins["@"].parsers + }, + + /* + * The rules key on the default plugin is a proxy to lazy-load + * just the rules that are needed. So, don't create a new object + * here, just use the default one to keep that performance + * enhancement. + */ + rules: defaultConfig[0].plugins["@"].rules + }, + "rule-to-test": { + rules: { + [ruleName]: Object.assign({}, rule, { + + // Create a wrapper rule that freezes the `context` properties. + create(context) { + freezeDeeply(context.options); + freezeDeeply(context.settings); + freezeDeeply(context.parserOptions); + + // freezeDeeply(context.languageOptions); + + return (typeof rule === "function" ? rule : rule.create)(context); + } + }) + } + } + }, + languageOptions: { + ...defaultConfig[0].languageOptions + } + }, + ...defaultConfig.slice(1) + ]; + + /** + * Run the rule for the given item + * @param {string|Object} item Item to run the rule against + * @throws {Error} If an invalid schema. + * @returns {Object} Eslint run result + * @private + */ + function runRuleForItem(item) { + const configs = new FlatConfigArray(testerConfig, { baseConfig }); + + /* + * Modify the returned config so that the parser is wrapped to catch + * access of the start/end properties. This method is called just + * once per code snippet being tested, so each test case gets a clean + * parser. + */ + configs[ConfigArraySymbol.finalizeConfig] = function(...args) { + + // can't do super here :( + const proto = Object.getPrototypeOf(this); + const calculatedConfig = proto[ConfigArraySymbol.finalizeConfig].apply(this, args); + + // wrap the parser to catch start/end property access + calculatedConfig.languageOptions.parser = wrapParser(calculatedConfig.languageOptions.parser); + return calculatedConfig; + }; + + let code, filename, output, beforeAST, afterAST; + + if (typeof item === "string") { + code = item; + } else { + code = item.code; + + /* + * Assumes everything on the item is a config except for the + * parameters used by this tester + */ + const itemConfig = { ...item }; + + for (const parameter of RuleTesterParameters) { + delete itemConfig[parameter]; + } + + // wrap any parsers + if (itemConfig.languageOptions && itemConfig.languageOptions.parser) { + + const parser = itemConfig.languageOptions.parser; + + if (parser && typeof parser !== "object") { + throw new Error("Parser must be an object with a parse() or parseForESLint() method."); + } + + } + + /* + * Create the config object from the tester config and this item + * specific configurations. + */ + configs.push(itemConfig); + } + + if (item.filename) { + filename = item.filename; + } + + let ruleConfig = 1; + + if (hasOwnProperty(item, "options")) { + assert(Array.isArray(item.options), "options must be an array"); + ruleConfig = [1, ...item.options]; + } + + configs.push({ + rules: { + [ruleId]: ruleConfig + } + }); + + const schema = getRuleOptionsSchema(rule); + + /* + * Setup AST getters. + * The goal is to check whether or not AST was modified when + * running the rule under test. + */ + configs.push({ + plugins: { + "rule-tester": { + rules: { + "validate-ast": { + create() { + return { + Program(node) { + beforeAST = cloneDeeplyExcludesParent(node); + }, + "Program:exit"(node) { + afterAST = node; + } + }; + } + } + } + } + } + }); + + if (schema) { + ajv.validateSchema(schema); + + if (ajv.errors) { + const errors = ajv.errors.map(error => { + const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; + + return `\t${field}: ${error.message}`; + }).join("\n"); + + throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]); + } + + /* + * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"), + * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling + * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result, + * the schema is compiled here separately from checking for `validateSchema` errors. + */ + try { + ajv.compile(schema); + } catch (err) { + throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`); + } + } + + // Verify the code. + const { getComments } = SourceCode.prototype; + let messages; + + // check for validation errors + try { + configs.normalizeSync(); + configs.getConfig("test.js"); + } catch (error) { + error.message = `ESLint configuration in rule-tester is invalid: ${error.message}`; + throw error; + } + + try { + SourceCode.prototype.getComments = getCommentsDeprecation; + messages = linter.verify(code, configs, filename); + } finally { + SourceCode.prototype.getComments = getComments; + } + + const fatalErrorMessage = messages.find(m => m.fatal); + + assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`); + + // Verify if autofix makes a syntax error or not. + if (messages.some(m => m.fix)) { + output = SourceCodeFixer.applyFixes(code, messages).output; + const errorMessageInFix = linter.verify(output, configs, filename).find(m => m.fatal); + + assert(!errorMessageInFix, [ + "A fatal parsing error occurred in autofix.", + `Error: ${errorMessageInFix && errorMessageInFix.message}`, + "Autofix output:", + output + ].join("\n")); + } else { + output = code; + } + + return { + messages, + output, + beforeAST, + afterAST: cloneDeeplyExcludesParent(afterAST) + }; + } + + /** + * Check if the AST was changed + * @param {ASTNode} beforeAST AST node before running + * @param {ASTNode} afterAST AST node after running + * @returns {void} + * @private + */ + function assertASTDidntChange(beforeAST, afterAST) { + if (!equal(beforeAST, afterAST)) { + assert.fail("Rule should not modify AST."); + } + } + + /** + * Check if the template is valid or not + * all valid cases go through this + * @param {string|Object} item Item to run the rule against + * @returns {void} + * @private + */ + function testValidTemplate(item) { + const code = typeof item === "object" ? item.code : item; + + assert.ok(typeof code === "string", "Test case must specify a string value for 'code'"); + if (item.name) { + assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string"); + } + + const result = runRuleForItem(item); + const messages = result.messages; + + assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s", + messages.length, + util.inspect(messages))); + + assertASTDidntChange(result.beforeAST, result.afterAST); + } + + /** + * Asserts that the message matches its expected value. If the expected + * value is a regular expression, it is checked against the actual + * value. + * @param {string} actual Actual value + * @param {string|RegExp} expected Expected value + * @returns {void} + * @private + */ + function assertMessageMatches(actual, expected) { + if (expected instanceof RegExp) { + + // assert.js doesn't have a built-in RegExp match function + assert.ok( + expected.test(actual), + `Expected '${actual}' to match ${expected}` + ); + } else { + assert.strictEqual(actual, expected); + } + } + + /** + * Check if the template is invalid or not + * all invalid cases go through this. + * @param {string|Object} item Item to run the rule against + * @returns {void} + * @private + */ + function testInvalidTemplate(item) { + assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'"); + if (item.name) { + assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string"); + } + assert.ok(item.errors || item.errors === 0, + `Did not specify errors for an invalid test of ${ruleName}`); + + if (Array.isArray(item.errors) && item.errors.length === 0) { + assert.fail("Invalid cases must have at least one error"); + } + + const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages"); + const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null; + + const result = runRuleForItem(item); + const messages = result.messages; + + if (typeof item.errors === "number") { + + if (item.errors === 0) { + assert.fail("Invalid cases must have 'error' value greater than 0"); + } + + assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s", + item.errors, + item.errors === 1 ? "" : "s", + messages.length, + util.inspect(messages))); + } else { + assert.strictEqual( + messages.length, item.errors.length, util.format( + "Should have %d error%s but had %d: %s", + item.errors.length, + item.errors.length === 1 ? "" : "s", + messages.length, + util.inspect(messages) + ) + ); + + const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleId); + + for (let i = 0, l = item.errors.length; i < l; i++) { + const error = item.errors[i]; + const message = messages[i]; + + assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested"); + + if (typeof error === "string" || error instanceof RegExp) { + + // Just an error message. + assertMessageMatches(message.message, error); + } else if (typeof error === "object" && error !== null) { + + /* + * Error object. + * This may have a message, messageId, data, node type, line, and/or + * column. + */ + + Object.keys(error).forEach(propertyName => { + assert.ok( + errorObjectParameters.has(propertyName), + `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.` + ); + }); + + if (hasOwnProperty(error, "message")) { + assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'."); + assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'."); + assertMessageMatches(message.message, error.message); + } else if (hasOwnProperty(error, "messageId")) { + assert.ok( + ruleHasMetaMessages, + "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'." + ); + if (!hasOwnProperty(rule.meta.messages, error.messageId)) { + assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`); + } + assert.strictEqual( + message.messageId, + error.messageId, + `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.` + ); + if (hasOwnProperty(error, "data")) { + + /* + * if data was provided, then directly compare the returned message to a synthetic + * interpolated message using the same message ID and data provided in the test. + * See https://github.com/eslint/eslint/issues/9890 for context. + */ + const unformattedOriginalMessage = rule.meta.messages[error.messageId]; + const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data); + + assert.strictEqual( + message.message, + rehydratedMessage, + `Hydrated message "${rehydratedMessage}" does not match "${message.message}"` + ); + } + } + + assert.ok( + hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true, + "Error must specify 'messageId' if 'data' is used." + ); + + if (error.type) { + assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`); + } + + if (hasOwnProperty(error, "line")) { + assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`); + } + + if (hasOwnProperty(error, "column")) { + assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`); + } + + if (hasOwnProperty(error, "endLine")) { + assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`); + } + + if (hasOwnProperty(error, "endColumn")) { + assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`); + } + + if (hasOwnProperty(error, "suggestions")) { + + // Support asserting there are no suggestions + if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) { + if (Array.isArray(message.suggestions) && message.suggestions.length > 0) { + assert.fail(`Error should have no suggestions on error with message: "${message.message}"`); + } + } else { + assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`); + assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`); + + error.suggestions.forEach((expectedSuggestion, index) => { + assert.ok( + typeof expectedSuggestion === "object" && expectedSuggestion !== null, + "Test suggestion in 'suggestions' array must be an object." + ); + Object.keys(expectedSuggestion).forEach(propertyName => { + assert.ok( + suggestionObjectParameters.has(propertyName), + `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.` + ); + }); + + const actualSuggestion = message.suggestions[index]; + const suggestionPrefix = `Error Suggestion at index ${index} :`; + + if (hasOwnProperty(expectedSuggestion, "desc")) { + assert.ok( + !hasOwnProperty(expectedSuggestion, "data"), + `${suggestionPrefix} Test should not specify both 'desc' and 'data'.` + ); + assert.strictEqual( + actualSuggestion.desc, + expectedSuggestion.desc, + `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.` + ); + } + + if (hasOwnProperty(expectedSuggestion, "messageId")) { + assert.ok( + ruleHasMetaMessages, + `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.` + ); + assert.ok( + hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId), + `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.` + ); + assert.strictEqual( + actualSuggestion.messageId, + expectedSuggestion.messageId, + `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.` + ); + if (hasOwnProperty(expectedSuggestion, "data")) { + const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId]; + const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data); + + assert.strictEqual( + actualSuggestion.desc, + rehydratedDesc, + `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".` + ); + } + } else { + assert.ok( + !hasOwnProperty(expectedSuggestion, "data"), + `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.` + ); + } + + if (hasOwnProperty(expectedSuggestion, "output")) { + const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output; + + assert.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`); + } + }); + } + } + } else { + + // Message was an unexpected type + assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`); + } + } + } + + if (hasOwnProperty(item, "output")) { + if (item.output === null) { + assert.strictEqual( + result.output, + item.code, + "Expected no autofixes to be suggested" + ); + } else { + assert.strictEqual(result.output, item.output, "Output is incorrect."); + } + } else { + assert.strictEqual( + result.output, + item.code, + "The rule fixed the code. Please add 'output' property." + ); + } + + assertASTDidntChange(result.beforeAST, result.afterAST); + } + + /* + * This creates a mocha test suite and pipes all supplied info through + * one of the templates above. + */ + this.constructor.describe(ruleName, () => { + this.constructor.describe("valid", () => { + test.valid.forEach(valid => { + this.constructor[valid.only ? "itOnly" : "it"]( + sanitize(typeof valid === "object" ? valid.name || valid.code : valid), + () => { + testValidTemplate(valid); + } + ); + }); + }); + + this.constructor.describe("invalid", () => { + test.invalid.forEach(invalid => { + this.constructor[invalid.only ? "itOnly" : "it"]( + sanitize(invalid.name || invalid.code), + () => { + testInvalidTemplate(invalid); + } + ); + }); + }); + }); + } +} + +FlatRuleTester[DESCRIBE] = FlatRuleTester[IT] = FlatRuleTester[IT_ONLY] = null; + +module.exports = FlatRuleTester; diff --git a/node_modules/eslint/lib/rule-tester/index.js b/node_modules/eslint/lib/rule-tester/index.js new file mode 100644 index 0000000..f52d140 --- /dev/null +++ b/node_modules/eslint/lib/rule-tester/index.js @@ -0,0 +1,5 @@ +"use strict"; + +module.exports = { + RuleTester: require("./rule-tester") +}; diff --git a/node_modules/eslint/lib/rule-tester/rule-tester.js b/node_modules/eslint/lib/rule-tester/rule-tester.js new file mode 100644 index 0000000..e4dc126 --- /dev/null +++ b/node_modules/eslint/lib/rule-tester/rule-tester.js @@ -0,0 +1,1053 @@ +/** + * @fileoverview Mocha test wrapper + * @author Ilya Volodin + */ +"use strict"; + +/* globals describe, it -- Mocha globals */ + +/* + * This is a wrapper around mocha to allow for DRY unittests for eslint + * Format: + * RuleTester.run("{ruleName}", { + * valid: [ + * "{code}", + * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} } + * ], + * invalid: [ + * { code: "{code}", errors: {numErrors} }, + * { code: "{code}", errors: ["{errorMessage}"] }, + * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings}, errors: [{ message: "{errorMessage}", type: "{errorNodeType}"}] } + * ] + * }); + * + * Variables: + * {code} - String that represents the code to be tested + * {options} - Arguments that are passed to the configurable rules. + * {globals} - An object representing a list of variables that are + * registered as globals + * {parser} - String representing the parser to use + * {settings} - An object representing global settings for all rules + * {numErrors} - If failing case doesn't need to check error message, + * this integer will specify how many errors should be + * received + * {errorMessage} - Message that is returned by the rule on failure + * {errorNodeType} - AST node type that is returned by they rule as + * a cause of the failure. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const + assert = require("assert"), + path = require("path"), + util = require("util"), + merge = require("lodash.merge"), + equal = require("fast-deep-equal"), + Traverser = require("../../lib/shared/traverser"), + { getRuleOptionsSchema, validate } = require("../shared/config-validator"), + { Linter, SourceCodeFixer, interpolate } = require("../linter"); + +const ajv = require("../shared/ajv")({ strictDefaults: true }); + +const espreePath = require.resolve("espree"); +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); + +const { SourceCode } = require("../source-code"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../shared/types").Parser} Parser */ + + +/** + * A test case that is expected to pass lint. + * @typedef {Object} ValidTestCase + * @property {string} [name] Name for the test case. + * @property {string} code Code for the test case. + * @property {any[]} [options] Options for the test case. + * @property {{ [name: string]: any }} [settings] Settings for the test case. + * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. + * @property {string} [parser] The absolute path for the parser. + * @property {{ [name: string]: any }} [parserOptions] Options for the parser. + * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables. + * @property {{ [name: string]: boolean }} [env] Environments for the test case. + * @property {boolean} [only] Run only this test case or the subset of test cases with this property. + */ + +/** + * A test case that is expected to fail lint. + * @typedef {Object} InvalidTestCase + * @property {string} [name] Name for the test case. + * @property {string} code Code for the test case. + * @property {number | Array} errors Expected errors. + * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested. + * @property {any[]} [options] Options for the test case. + * @property {{ [name: string]: any }} [settings] Settings for the test case. + * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. + * @property {string} [parser] The absolute path for the parser. + * @property {{ [name: string]: any }} [parserOptions] Options for the parser. + * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables. + * @property {{ [name: string]: boolean }} [env] Environments for the test case. + * @property {boolean} [only] Run only this test case or the subset of test cases with this property. + */ + +/** + * A description of a reported error used in a rule tester test. + * @typedef {Object} TestCaseError + * @property {string | RegExp} [message] Message. + * @property {string} [messageId] Message ID. + * @property {string} [type] The type of the reported AST node. + * @property {{ [name: string]: string }} [data] The data used to fill the message template. + * @property {number} [line] The 1-based line number of the reported start location. + * @property {number} [column] The 1-based column number of the reported start location. + * @property {number} [endLine] The 1-based line number of the reported end location. + * @property {number} [endColumn] The 1-based column number of the reported end location. + */ + +//------------------------------------------------------------------------------ +// Private Members +//------------------------------------------------------------------------------ + +/* + * testerDefaultConfig must not be modified as it allows to reset the tester to + * the initial default configuration + */ +const testerDefaultConfig = { rules: {} }; +let defaultConfig = { rules: {} }; + +/* + * List every parameters possible on a test case that are not related to eslint + * configuration + */ +const RuleTesterParameters = [ + "name", + "code", + "filename", + "options", + "errors", + "output", + "only" +]; + +/* + * All allowed property names in error objects. + */ +const errorObjectParameters = new Set([ + "message", + "messageId", + "data", + "type", + "line", + "column", + "endLine", + "endColumn", + "suggestions" +]); +const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`; + +/* + * All allowed property names in suggestion objects. + */ +const suggestionObjectParameters = new Set([ + "desc", + "messageId", + "data", + "output" +]); +const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`; + +const hasOwnProperty = Function.call.bind(Object.hasOwnProperty); + +/** + * Clones a given value deeply. + * Note: This ignores `parent` property. + * @param {any} x A value to clone. + * @returns {any} A cloned value. + */ +function cloneDeeplyExcludesParent(x) { + if (typeof x === "object" && x !== null) { + if (Array.isArray(x)) { + return x.map(cloneDeeplyExcludesParent); + } + + const retv = {}; + + for (const key in x) { + if (key !== "parent" && hasOwnProperty(x, key)) { + retv[key] = cloneDeeplyExcludesParent(x[key]); + } + } + + return retv; + } + + return x; +} + +/** + * Freezes a given value deeply. + * @param {any} x A value to freeze. + * @returns {void} + */ +function freezeDeeply(x) { + if (typeof x === "object" && x !== null) { + if (Array.isArray(x)) { + x.forEach(freezeDeeply); + } else { + for (const key in x) { + if (key !== "parent" && hasOwnProperty(x, key)) { + freezeDeeply(x[key]); + } + } + } + Object.freeze(x); + } +} + +/** + * Replace control characters by `\u00xx` form. + * @param {string} text The text to sanitize. + * @returns {string} The sanitized text. + */ +function sanitize(text) { + if (typeof text !== "string") { + return ""; + } + return text.replace( + /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls + c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}` + ); +} + +/** + * Define `start`/`end` properties as throwing error. + * @param {string} objName Object name used for error messages. + * @param {ASTNode} node The node to define. + * @returns {void} + */ +function defineStartEndAsError(objName, node) { + Object.defineProperties(node, { + start: { + get() { + throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`); + }, + configurable: true, + enumerable: false + }, + end: { + get() { + throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`); + }, + configurable: true, + enumerable: false + } + }); +} + + +/** + * Define `start`/`end` properties of all nodes of the given AST as throwing error. + * @param {ASTNode} ast The root node to errorize `start`/`end` properties. + * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast. + * @returns {void} + */ +function defineStartEndAsErrorInTree(ast, visitorKeys) { + Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") }); + ast.tokens.forEach(defineStartEndAsError.bind(null, "token")); + ast.comments.forEach(defineStartEndAsError.bind(null, "token")); +} + +/** + * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes. + * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties. + * @param {Parser} parser Parser object. + * @returns {Parser} Wrapped parser object. + */ +function wrapParser(parser) { + + if (typeof parser.parseForESLint === "function") { + return { + [parserSymbol]: parser, + parseForESLint(...args) { + const ret = parser.parseForESLint(...args); + + defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys); + return ret; + } + }; + } + + return { + [parserSymbol]: parser, + parse(...args) { + const ast = parser.parse(...args); + + defineStartEndAsErrorInTree(ast); + return ast; + } + }; +} + +/** + * Function to replace `SourceCode.prototype.getComments`. + * @returns {void} + * @throws {Error} Deprecation message. + */ +function getCommentsDeprecation() { + throw new Error( + "`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead." + ); +} + +/** + * Emit a deprecation warning if function-style format is being used. + * @param {string} ruleName Name of the rule. + * @returns {void} + */ +function emitLegacyRuleAPIWarning(ruleName) { + if (!emitLegacyRuleAPIWarning[`warned-${ruleName}`]) { + emitLegacyRuleAPIWarning[`warned-${ruleName}`] = true; + process.emitWarning( + `"${ruleName}" rule is using the deprecated function-style format and will stop working in ESLint v9. Please use object-style format: https://eslint.org/docs/latest/extend/custom-rules`, + "DeprecationWarning" + ); + } +} + +/** + * Emit a deprecation warning if rule has options but is missing the "meta.schema" property + * @param {string} ruleName Name of the rule. + * @returns {void} + */ +function emitMissingSchemaWarning(ruleName) { + if (!emitMissingSchemaWarning[`warned-${ruleName}`]) { + emitMissingSchemaWarning[`warned-${ruleName}`] = true; + process.emitWarning( + `"${ruleName}" rule has options but is missing the "meta.schema" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/latest/extend/custom-rules#options-schemas`, + "DeprecationWarning" + ); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +// default separators for testing +const DESCRIBE = Symbol("describe"); +const IT = Symbol("it"); +const IT_ONLY = Symbol("itOnly"); + +/** + * This is `it` default handler if `it` don't exist. + * @this {Mocha} + * @param {string} text The description of the test case. + * @param {Function} method The logic of the test case. + * @throws {Error} Any error upon execution of `method`. + * @returns {any} Returned value of `method`. + */ +function itDefaultHandler(text, method) { + try { + return method.call(this); + } catch (err) { + if (err instanceof assert.AssertionError) { + err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`; + } + throw err; + } +} + +/** + * This is `describe` default handler if `describe` don't exist. + * @this {Mocha} + * @param {string} text The description of the test case. + * @param {Function} method The logic of the test case. + * @returns {any} Returned value of `method`. + */ +function describeDefaultHandler(text, method) { + return method.call(this); +} + +/** + * Mocha test wrapper. + */ +class RuleTester { + + /** + * Creates a new instance of RuleTester. + * @param {Object} [testerConfig] Optional, extra configuration for the tester + */ + constructor(testerConfig) { + + /** + * The configuration to use for this tester. Combination of the tester + * configuration and the default configuration. + * @type {Object} + */ + this.testerConfig = merge( + {}, + defaultConfig, + testerConfig, + { rules: { "rule-tester/validate-ast": "error" } } + ); + + /** + * Rule definitions to define before tests. + * @type {Object} + */ + this.rules = {}; + this.linter = new Linter(); + } + + /** + * Set the configuration to use for all future tests + * @param {Object} config the configuration to use. + * @throws {TypeError} If non-object config. + * @returns {void} + */ + static setDefaultConfig(config) { + if (typeof config !== "object" || config === null) { + throw new TypeError("RuleTester.setDefaultConfig: config must be an object"); + } + defaultConfig = config; + + // Make sure the rules object exists since it is assumed to exist later + defaultConfig.rules = defaultConfig.rules || {}; + } + + /** + * Get the current configuration used for all tests + * @returns {Object} the current configuration + */ + static getDefaultConfig() { + return defaultConfig; + } + + /** + * Reset the configuration to the initial configuration of the tester removing + * any changes made until now. + * @returns {void} + */ + static resetDefaultConfig() { + defaultConfig = merge({}, testerDefaultConfig); + } + + + /* + * If people use `mocha test.js --watch` command, `describe` and `it` function + * instances are different for each execution. So `describe` and `it` should get fresh instance + * always. + */ + static get describe() { + return ( + this[DESCRIBE] || + (typeof describe === "function" ? describe : describeDefaultHandler) + ); + } + + static set describe(value) { + this[DESCRIBE] = value; + } + + static get it() { + return ( + this[IT] || + (typeof it === "function" ? it : itDefaultHandler) + ); + } + + static set it(value) { + this[IT] = value; + } + + /** + * Adds the `only` property to a test to run it in isolation. + * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself. + * @returns {ValidTestCase | InvalidTestCase} The test with `only` set. + */ + static only(item) { + if (typeof item === "string") { + return { code: item, only: true }; + } + + return { ...item, only: true }; + } + + static get itOnly() { + if (typeof this[IT_ONLY] === "function") { + return this[IT_ONLY]; + } + if (typeof this[IT] === "function" && typeof this[IT].only === "function") { + return Function.bind.call(this[IT].only, this[IT]); + } + if (typeof it === "function" && typeof it.only === "function") { + return Function.bind.call(it.only, it); + } + + if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") { + throw new Error( + "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" + + "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more." + ); + } + if (typeof it === "function") { + throw new Error("The current test framework does not support exclusive tests with `only`."); + } + throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha."); + } + + static set itOnly(value) { + this[IT_ONLY] = value; + } + + /** + * Define a rule for one particular run of tests. + * @param {string} name The name of the rule to define. + * @param {Function} rule The rule definition. + * @returns {void} + */ + defineRule(name, rule) { + this.rules[name] = rule; + } + + /** + * Adds a new rule test to execute. + * @param {string} ruleName The name of the rule to run. + * @param {Function} rule The rule to test. + * @param {{ + * valid: (ValidTestCase | string)[], + * invalid: InvalidTestCase[] + * }} test The collection of tests to run. + * @throws {TypeError|Error} If non-object `test`, or if a required + * scenario of the given type is missing. + * @returns {void} + */ + run(ruleName, rule, test) { + + const testerConfig = this.testerConfig, + requiredScenarios = ["valid", "invalid"], + scenarioErrors = [], + linter = this.linter; + + if (!test || typeof test !== "object") { + throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`); + } + + requiredScenarios.forEach(scenarioType => { + if (!test[scenarioType]) { + scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`); + } + }); + + if (scenarioErrors.length > 0) { + throw new Error([ + `Test Scenarios for rule ${ruleName} is invalid:` + ].concat(scenarioErrors).join("\n")); + } + + if (typeof rule === "function") { + emitLegacyRuleAPIWarning(ruleName); + } + + linter.defineRule(ruleName, Object.assign({}, rule, { + + // Create a wrapper rule that freezes the `context` properties. + create(context) { + freezeDeeply(context.options); + freezeDeeply(context.settings); + freezeDeeply(context.parserOptions); + + return (typeof rule === "function" ? rule : rule.create)(context); + } + })); + + linter.defineRules(this.rules); + + /** + * Run the rule for the given item + * @param {string|Object} item Item to run the rule against + * @throws {Error} If an invalid schema. + * @returns {Object} Eslint run result + * @private + */ + function runRuleForItem(item) { + let config = merge({}, testerConfig), + code, filename, output, beforeAST, afterAST; + + if (typeof item === "string") { + code = item; + } else { + code = item.code; + + /* + * Assumes everything on the item is a config except for the + * parameters used by this tester + */ + const itemConfig = { ...item }; + + for (const parameter of RuleTesterParameters) { + delete itemConfig[parameter]; + } + + /* + * Create the config object from the tester config and this item + * specific configurations. + */ + config = merge( + config, + itemConfig + ); + } + + if (item.filename) { + filename = item.filename; + } + + if (hasOwnProperty(item, "options")) { + assert(Array.isArray(item.options), "options must be an array"); + if ( + item.options.length > 0 && + typeof rule === "object" && + ( + !rule.meta || (rule.meta && (typeof rule.meta.schema === "undefined" || rule.meta.schema === null)) + ) + ) { + emitMissingSchemaWarning(ruleName); + } + config.rules[ruleName] = [1].concat(item.options); + } else { + config.rules[ruleName] = 1; + } + + const schema = getRuleOptionsSchema(rule); + + /* + * Setup AST getters. + * The goal is to check whether or not AST was modified when + * running the rule under test. + */ + linter.defineRule("rule-tester/validate-ast", { + create() { + return { + Program(node) { + beforeAST = cloneDeeplyExcludesParent(node); + }, + "Program:exit"(node) { + afterAST = node; + } + }; + } + }); + + if (typeof config.parser === "string") { + assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths"); + } else { + config.parser = espreePath; + } + + linter.defineParser(config.parser, wrapParser(require(config.parser))); + + if (schema) { + ajv.validateSchema(schema); + + if (ajv.errors) { + const errors = ajv.errors.map(error => { + const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; + + return `\t${field}: ${error.message}`; + }).join("\n"); + + throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]); + } + + /* + * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"), + * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling + * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result, + * the schema is compiled here separately from checking for `validateSchema` errors. + */ + try { + ajv.compile(schema); + } catch (err) { + throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`); + } + } + + validate(config, "rule-tester", id => (id === ruleName ? rule : null)); + + // Verify the code. + const { getComments } = SourceCode.prototype; + let messages; + + try { + SourceCode.prototype.getComments = getCommentsDeprecation; + messages = linter.verify(code, config, filename); + } finally { + SourceCode.prototype.getComments = getComments; + } + + const fatalErrorMessage = messages.find(m => m.fatal); + + assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`); + + // Verify if autofix makes a syntax error or not. + if (messages.some(m => m.fix)) { + output = SourceCodeFixer.applyFixes(code, messages).output; + const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal); + + assert(!errorMessageInFix, [ + "A fatal parsing error occurred in autofix.", + `Error: ${errorMessageInFix && errorMessageInFix.message}`, + "Autofix output:", + output + ].join("\n")); + } else { + output = code; + } + + return { + messages, + output, + beforeAST, + afterAST: cloneDeeplyExcludesParent(afterAST) + }; + } + + /** + * Check if the AST was changed + * @param {ASTNode} beforeAST AST node before running + * @param {ASTNode} afterAST AST node after running + * @returns {void} + * @private + */ + function assertASTDidntChange(beforeAST, afterAST) { + if (!equal(beforeAST, afterAST)) { + assert.fail("Rule should not modify AST."); + } + } + + /** + * Check if the template is valid or not + * all valid cases go through this + * @param {string|Object} item Item to run the rule against + * @returns {void} + * @private + */ + function testValidTemplate(item) { + const code = typeof item === "object" ? item.code : item; + + assert.ok(typeof code === "string", "Test case must specify a string value for 'code'"); + if (item.name) { + assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string"); + } + + const result = runRuleForItem(item); + const messages = result.messages; + + assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s", + messages.length, + util.inspect(messages))); + + assertASTDidntChange(result.beforeAST, result.afterAST); + } + + /** + * Asserts that the message matches its expected value. If the expected + * value is a regular expression, it is checked against the actual + * value. + * @param {string} actual Actual value + * @param {string|RegExp} expected Expected value + * @returns {void} + * @private + */ + function assertMessageMatches(actual, expected) { + if (expected instanceof RegExp) { + + // assert.js doesn't have a built-in RegExp match function + assert.ok( + expected.test(actual), + `Expected '${actual}' to match ${expected}` + ); + } else { + assert.strictEqual(actual, expected); + } + } + + /** + * Check if the template is invalid or not + * all invalid cases go through this. + * @param {string|Object} item Item to run the rule against + * @returns {void} + * @private + */ + function testInvalidTemplate(item) { + assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'"); + if (item.name) { + assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string"); + } + assert.ok(item.errors || item.errors === 0, + `Did not specify errors for an invalid test of ${ruleName}`); + + if (Array.isArray(item.errors) && item.errors.length === 0) { + assert.fail("Invalid cases must have at least one error"); + } + + const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages"); + const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null; + + const result = runRuleForItem(item); + const messages = result.messages; + + if (typeof item.errors === "number") { + + if (item.errors === 0) { + assert.fail("Invalid cases must have 'error' value greater than 0"); + } + + assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s", + item.errors, + item.errors === 1 ? "" : "s", + messages.length, + util.inspect(messages))); + } else { + assert.strictEqual( + messages.length, item.errors.length, util.format( + "Should have %d error%s but had %d: %s", + item.errors.length, + item.errors.length === 1 ? "" : "s", + messages.length, + util.inspect(messages) + ) + ); + + const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName); + + for (let i = 0, l = item.errors.length; i < l; i++) { + const error = item.errors[i]; + const message = messages[i]; + + assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested"); + + if (typeof error === "string" || error instanceof RegExp) { + + // Just an error message. + assertMessageMatches(message.message, error); + } else if (typeof error === "object" && error !== null) { + + /* + * Error object. + * This may have a message, messageId, data, node type, line, and/or + * column. + */ + + Object.keys(error).forEach(propertyName => { + assert.ok( + errorObjectParameters.has(propertyName), + `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.` + ); + }); + + if (hasOwnProperty(error, "message")) { + assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'."); + assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'."); + assertMessageMatches(message.message, error.message); + } else if (hasOwnProperty(error, "messageId")) { + assert.ok( + ruleHasMetaMessages, + "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'." + ); + if (!hasOwnProperty(rule.meta.messages, error.messageId)) { + assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`); + } + assert.strictEqual( + message.messageId, + error.messageId, + `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.` + ); + if (hasOwnProperty(error, "data")) { + + /* + * if data was provided, then directly compare the returned message to a synthetic + * interpolated message using the same message ID and data provided in the test. + * See https://github.com/eslint/eslint/issues/9890 for context. + */ + const unformattedOriginalMessage = rule.meta.messages[error.messageId]; + const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data); + + assert.strictEqual( + message.message, + rehydratedMessage, + `Hydrated message "${rehydratedMessage}" does not match "${message.message}"` + ); + } + } + + assert.ok( + hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true, + "Error must specify 'messageId' if 'data' is used." + ); + + if (error.type) { + assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`); + } + + if (hasOwnProperty(error, "line")) { + assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`); + } + + if (hasOwnProperty(error, "column")) { + assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`); + } + + if (hasOwnProperty(error, "endLine")) { + assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`); + } + + if (hasOwnProperty(error, "endColumn")) { + assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`); + } + + if (hasOwnProperty(error, "suggestions")) { + + // Support asserting there are no suggestions + if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) { + if (Array.isArray(message.suggestions) && message.suggestions.length > 0) { + assert.fail(`Error should have no suggestions on error with message: "${message.message}"`); + } + } else { + assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`); + assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`); + + error.suggestions.forEach((expectedSuggestion, index) => { + assert.ok( + typeof expectedSuggestion === "object" && expectedSuggestion !== null, + "Test suggestion in 'suggestions' array must be an object." + ); + Object.keys(expectedSuggestion).forEach(propertyName => { + assert.ok( + suggestionObjectParameters.has(propertyName), + `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.` + ); + }); + + const actualSuggestion = message.suggestions[index]; + const suggestionPrefix = `Error Suggestion at index ${index} :`; + + if (hasOwnProperty(expectedSuggestion, "desc")) { + assert.ok( + !hasOwnProperty(expectedSuggestion, "data"), + `${suggestionPrefix} Test should not specify both 'desc' and 'data'.` + ); + assert.strictEqual( + actualSuggestion.desc, + expectedSuggestion.desc, + `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.` + ); + } + + if (hasOwnProperty(expectedSuggestion, "messageId")) { + assert.ok( + ruleHasMetaMessages, + `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.` + ); + assert.ok( + hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId), + `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.` + ); + assert.strictEqual( + actualSuggestion.messageId, + expectedSuggestion.messageId, + `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.` + ); + if (hasOwnProperty(expectedSuggestion, "data")) { + const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId]; + const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data); + + assert.strictEqual( + actualSuggestion.desc, + rehydratedDesc, + `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".` + ); + } + } else { + assert.ok( + !hasOwnProperty(expectedSuggestion, "data"), + `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.` + ); + } + + if (hasOwnProperty(expectedSuggestion, "output")) { + const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output; + + assert.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`); + } + }); + } + } + } else { + + // Message was an unexpected type + assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`); + } + } + } + + if (hasOwnProperty(item, "output")) { + if (item.output === null) { + assert.strictEqual( + result.output, + item.code, + "Expected no autofixes to be suggested" + ); + } else { + assert.strictEqual(result.output, item.output, "Output is incorrect."); + } + } else { + assert.strictEqual( + result.output, + item.code, + "The rule fixed the code. Please add 'output' property." + ); + } + + assertASTDidntChange(result.beforeAST, result.afterAST); + } + + /* + * This creates a mocha test suite and pipes all supplied info through + * one of the templates above. + */ + this.constructor.describe(ruleName, () => { + this.constructor.describe("valid", () => { + test.valid.forEach(valid => { + this.constructor[valid.only ? "itOnly" : "it"]( + sanitize(typeof valid === "object" ? valid.name || valid.code : valid), + () => { + testValidTemplate(valid); + } + ); + }); + }); + + this.constructor.describe("invalid", () => { + test.invalid.forEach(invalid => { + this.constructor[invalid.only ? "itOnly" : "it"]( + sanitize(invalid.name || invalid.code), + () => { + testInvalidTemplate(invalid); + } + ); + }); + }); + }); + } +} + +RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null; + +module.exports = RuleTester; diff --git a/node_modules/eslint/lib/rules/accessor-pairs.js b/node_modules/eslint/lib/rules/accessor-pairs.js new file mode 100644 index 0000000..f970328 --- /dev/null +++ b/node_modules/eslint/lib/rules/accessor-pairs.js @@ -0,0 +1,346 @@ +/** + * @fileoverview Rule to enforce getter and setter pairs in objects and classes. + * @author Gyandeep Singh + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * Property name if it can be computed statically, otherwise the list of the tokens of the key node. + * @typedef {string|Token[]} Key + */ + +/** + * Accessor nodes with the same key. + * @typedef {Object} AccessorData + * @property {Key} key Accessor's key + * @property {ASTNode[]} getters List of getter nodes. + * @property {ASTNode[]} setters List of setter nodes. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not the given lists represent the equal tokens in the same order. + * Tokens are compared by their properties, not by instance. + * @param {Token[]} left First list of tokens. + * @param {Token[]} right Second list of tokens. + * @returns {boolean} `true` if the lists have same tokens. + */ +function areEqualTokenLists(left, right) { + if (left.length !== right.length) { + return false; + } + + for (let i = 0; i < left.length; i++) { + const leftToken = left[i], + rightToken = right[i]; + + if (leftToken.type !== rightToken.type || leftToken.value !== rightToken.value) { + return false; + } + } + + return true; +} + +/** + * Checks whether or not the given keys are equal. + * @param {Key} left First key. + * @param {Key} right Second key. + * @returns {boolean} `true` if the keys are equal. + */ +function areEqualKeys(left, right) { + if (typeof left === "string" && typeof right === "string") { + + // Statically computed names. + return left === right; + } + if (Array.isArray(left) && Array.isArray(right)) { + + // Token lists. + return areEqualTokenLists(left, right); + } + + return false; +} + +/** + * Checks whether or not a given node is of an accessor kind ('get' or 'set'). + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is of an accessor kind. + */ +function isAccessorKind(node) { + return node.kind === "get" || node.kind === "set"; +} + +/** + * Checks whether or not a given node is an argument of a specified method call. + * @param {ASTNode} node A node to check. + * @param {number} index An expected index of the node in arguments. + * @param {string} object An expected name of the object of the method. + * @param {string} property An expected name of the method. + * @returns {boolean} `true` if the node is an argument of the specified method call. + */ +function isArgumentOfMethodCall(node, index, object, property) { + const parent = node.parent; + + return ( + parent.type === "CallExpression" && + astUtils.isSpecificMemberAccess(parent.callee, object, property) && + parent.arguments[index] === node + ); +} + +/** + * Checks whether or not a given node is a property descriptor. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a property descriptor. + */ +function isPropertyDescriptor(node) { + + // Object.defineProperty(obj, "foo", {set: ...}) + if (isArgumentOfMethodCall(node, 2, "Object", "defineProperty") || + isArgumentOfMethodCall(node, 2, "Reflect", "defineProperty") + ) { + return true; + } + + /* + * Object.defineProperties(obj, {foo: {set: ...}}) + * Object.create(proto, {foo: {set: ...}}) + */ + const grandparent = node.parent.parent; + + return grandparent.type === "ObjectExpression" && ( + isArgumentOfMethodCall(grandparent, 1, "Object", "create") || + isArgumentOfMethodCall(grandparent, 1, "Object", "defineProperties") + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce getter and setter pairs in objects and classes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/accessor-pairs" + }, + + schema: [{ + type: "object", + properties: { + getWithoutSet: { + type: "boolean", + default: false + }, + setWithoutGet: { + type: "boolean", + default: true + }, + enforceForClassMembers: { + type: "boolean", + default: true + } + }, + additionalProperties: false + }], + + messages: { + missingGetterInPropertyDescriptor: "Getter is not present in property descriptor.", + missingSetterInPropertyDescriptor: "Setter is not present in property descriptor.", + missingGetterInObjectLiteral: "Getter is not present for {{ name }}.", + missingSetterInObjectLiteral: "Setter is not present for {{ name }}.", + missingGetterInClass: "Getter is not present for class {{ name }}.", + missingSetterInClass: "Setter is not present for class {{ name }}." + } + }, + create(context) { + const config = context.options[0] || {}; + const checkGetWithoutSet = config.getWithoutSet === true; + const checkSetWithoutGet = config.setWithoutGet !== false; + const enforceForClassMembers = config.enforceForClassMembers !== false; + const sourceCode = context.sourceCode; + + /** + * Reports the given node. + * @param {ASTNode} node The node to report. + * @param {string} messageKind "missingGetter" or "missingSetter". + * @returns {void} + * @private + */ + function report(node, messageKind) { + if (node.type === "Property") { + context.report({ + node, + messageId: `${messageKind}InObjectLiteral`, + loc: astUtils.getFunctionHeadLoc(node.value, sourceCode), + data: { name: astUtils.getFunctionNameWithKind(node.value) } + }); + } else if (node.type === "MethodDefinition") { + context.report({ + node, + messageId: `${messageKind}InClass`, + loc: astUtils.getFunctionHeadLoc(node.value, sourceCode), + data: { name: astUtils.getFunctionNameWithKind(node.value) } + }); + } else { + context.report({ + node, + messageId: `${messageKind}InPropertyDescriptor` + }); + } + } + + /** + * Reports each of the nodes in the given list using the same messageId. + * @param {ASTNode[]} nodes Nodes to report. + * @param {string} messageKind "missingGetter" or "missingSetter". + * @returns {void} + * @private + */ + function reportList(nodes, messageKind) { + for (const node of nodes) { + report(node, messageKind); + } + } + + /** + * Checks accessor pairs in the given list of nodes. + * @param {ASTNode[]} nodes The list to check. + * @returns {void} + * @private + */ + function checkList(nodes) { + const accessors = []; + let found = false; + + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + + if (isAccessorKind(node)) { + + // Creates a new `AccessorData` object for the given getter or setter node. + const name = astUtils.getStaticPropertyName(node); + const key = (name !== null) ? name : sourceCode.getTokens(node.key); + + // Merges the given `AccessorData` object into the given accessors list. + for (let j = 0; j < accessors.length; j++) { + const accessor = accessors[j]; + + if (areEqualKeys(accessor.key, key)) { + accessor.getters.push(...node.kind === "get" ? [node] : []); + accessor.setters.push(...node.kind === "set" ? [node] : []); + found = true; + break; + } + } + if (!found) { + accessors.push({ + key, + getters: node.kind === "get" ? [node] : [], + setters: node.kind === "set" ? [node] : [] + }); + } + found = false; + } + } + + for (const { getters, setters } of accessors) { + if (checkSetWithoutGet && setters.length && !getters.length) { + reportList(setters, "missingGetter"); + } + if (checkGetWithoutSet && getters.length && !setters.length) { + reportList(getters, "missingSetter"); + } + } + } + + /** + * Checks accessor pairs in an object literal. + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkObjectLiteral(node) { + checkList(node.properties.filter(p => p.type === "Property")); + } + + /** + * Checks accessor pairs in a property descriptor. + * @param {ASTNode} node Property descriptor `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkPropertyDescriptor(node) { + const namesToCheck = new Set(node.properties + .filter(p => p.type === "Property" && p.kind === "init" && !p.computed) + .map(({ key }) => key.name)); + + const hasGetter = namesToCheck.has("get"); + const hasSetter = namesToCheck.has("set"); + + if (checkSetWithoutGet && hasSetter && !hasGetter) { + report(node, "missingGetter"); + } + if (checkGetWithoutSet && hasGetter && !hasSetter) { + report(node, "missingSetter"); + } + } + + /** + * Checks the given object expression as an object literal and as a possible property descriptor. + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkObjectExpression(node) { + checkObjectLiteral(node); + if (isPropertyDescriptor(node)) { + checkPropertyDescriptor(node); + } + } + + /** + * Checks the given class body. + * @param {ASTNode} node `ClassBody` node to check. + * @returns {void} + * @private + */ + function checkClassBody(node) { + const methodDefinitions = node.body.filter(m => m.type === "MethodDefinition"); + + checkList(methodDefinitions.filter(m => m.static)); + checkList(methodDefinitions.filter(m => !m.static)); + } + + const listeners = {}; + + if (checkSetWithoutGet || checkGetWithoutSet) { + listeners.ObjectExpression = checkObjectExpression; + if (enforceForClassMembers) { + listeners.ClassBody = checkClassBody; + } + } + + return listeners; + } +}; diff --git a/node_modules/eslint/lib/rules/array-bracket-newline.js b/node_modules/eslint/lib/rules/array-bracket-newline.js new file mode 100644 index 0000000..c3676bf --- /dev/null +++ b/node_modules/eslint/lib/rules/array-bracket-newline.js @@ -0,0 +1,258 @@ +/** + * @fileoverview Rule to enforce linebreaks after open and before close array brackets + * @author Jan Peer Stöcklmair + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce linebreaks after opening and before closing array brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-bracket-newline" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never", "consistent"] + }, + { + type: "object", + properties: { + multiline: { + type: "boolean" + }, + minItems: { + type: ["integer", "null"], + minimum: 0 + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + unexpectedOpeningLinebreak: "There should be no linebreak after '['.", + unexpectedClosingLinebreak: "There should be no linebreak before ']'.", + missingOpeningLinebreak: "A linebreak is required after '['.", + missingClosingLinebreak: "A linebreak is required before ']'." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} option An option value to parse. + * @returns {{multiline: boolean, minItems: number}} Normalized option object. + */ + function normalizeOptionValue(option) { + let consistent = false; + let multiline = false; + let minItems = 0; + + if (option) { + if (option === "consistent") { + consistent = true; + minItems = Number.POSITIVE_INFINITY; + } else if (option === "always" || option.minItems === 0) { + minItems = 0; + } else if (option === "never") { + minItems = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(option.multiline); + minItems = option.minItems || Number.POSITIVE_INFINITY; + } + } else { + consistent = false; + multiline = true; + minItems = Number.POSITIVE_INFINITY; + } + + return { consistent, multiline, minItems }; + } + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. + */ + function normalizeOptions(options) { + const value = normalizeOptionValue(options); + + return { ArrayExpression: value, ArrayPattern: value }; + } + + /** + * Reports that there shouldn't be a linebreak after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "unexpectedOpeningLinebreak", + fix(fixer) { + const nextToken = sourceCode.getTokenAfter(token, { includeComments: true }); + + if (astUtils.isCommentToken(nextToken)) { + return null; + } + + return fixer.removeRange([token.range[1], nextToken.range[0]]); + } + }); + } + + /** + * Reports that there shouldn't be a linebreak before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "unexpectedClosingLinebreak", + fix(fixer) { + const previousToken = sourceCode.getTokenBefore(token, { includeComments: true }); + + if (astUtils.isCommentToken(previousToken)) { + return null; + } + + return fixer.removeRange([previousToken.range[1], token.range[0]]); + } + }); + } + + /** + * Reports that there should be a linebreak after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingOpeningLinebreak", + fix(fixer) { + return fixer.insertTextAfter(token, "\n"); + } + }); + } + + /** + * Reports that there should be a linebreak before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingClosingLinebreak", + fix(fixer) { + return fixer.insertTextBefore(token, "\n"); + } + }); + } + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ArrayExpression node or an ArrayPattern node. + * @returns {void} + */ + function check(node) { + const elements = node.elements; + const normalizedOptions = normalizeOptions(context.options[0]); + const options = normalizedOptions[node.type]; + const openBracket = sourceCode.getFirstToken(node); + const closeBracket = sourceCode.getLastToken(node); + const firstIncComment = sourceCode.getTokenAfter(openBracket, { includeComments: true }); + const lastIncComment = sourceCode.getTokenBefore(closeBracket, { includeComments: true }); + const first = sourceCode.getTokenAfter(openBracket); + const last = sourceCode.getTokenBefore(closeBracket); + + const needsLinebreaks = ( + elements.length >= options.minItems || + ( + options.multiline && + elements.length > 0 && + firstIncComment.loc.start.line !== lastIncComment.loc.end.line + ) || + ( + elements.length === 0 && + firstIncComment.type === "Block" && + firstIncComment.loc.start.line !== lastIncComment.loc.end.line && + firstIncComment === lastIncComment + ) || + ( + options.consistent && + openBracket.loc.end.line !== first.loc.start.line + ) + ); + + /* + * Use tokens or comments to check multiline or not. + * But use only tokens to check whether linebreaks are needed. + * This allows: + * var arr = [ // eslint-disable-line foo + * 'a' + * ] + */ + + if (needsLinebreaks) { + if (astUtils.isTokenOnSameLine(openBracket, first)) { + reportRequiredBeginningLinebreak(node, openBracket); + } + if (astUtils.isTokenOnSameLine(last, closeBracket)) { + reportRequiredEndingLinebreak(node, closeBracket); + } + } else { + if (!astUtils.isTokenOnSameLine(openBracket, first)) { + reportNoBeginningLinebreak(node, openBracket); + } + if (!astUtils.isTokenOnSameLine(last, closeBracket)) { + reportNoEndingLinebreak(node, closeBracket); + } + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + ArrayPattern: check, + ArrayExpression: check + }; + } +}; diff --git a/node_modules/eslint/lib/rules/array-bracket-spacing.js b/node_modules/eslint/lib/rules/array-bracket-spacing.js new file mode 100644 index 0000000..e3a46d8 --- /dev/null +++ b/node_modules/eslint/lib/rules/array-bracket-spacing.js @@ -0,0 +1,241 @@ +/** + * @fileoverview Disallows or enforces spaces inside of array brackets. + * @author Jamund Ferguson + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing inside array brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-bracket-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + singleValue: { + type: "boolean" + }, + objectsInArrays: { + type: "boolean" + }, + arraysInArrays: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.", + unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.", + missingSpaceAfter: "A space is required after '{{tokenValue}}'.", + missingSpaceBefore: "A space is required before '{{tokenValue}}'." + } + }, + create(context) { + const spaced = context.options[0] === "always", + sourceCode = context.sourceCode; + + /** + * Determines whether an option is set, relative to the spacing option. + * If spaced is "always", then check whether option is set to false. + * If spaced is "never", then check whether option is set to true. + * @param {Object} option The option to exclude. + * @returns {boolean} Whether or not the property is excluded. + */ + function isOptionSet(option) { + return context.options[1] ? context.options[1][option] === !spaced : false; + } + + const options = { + spaced, + singleElementException: isOptionSet("singleValue"), + objectsInArraysException: isOptionSet("objectsInArrays"), + arraysInArraysException: isOptionSet("arraysInArrays") + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningSpace(node, token) { + const nextToken = sourceCode.getTokenAfter(token); + + context.report({ + node, + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + tokenValue: token.value + }, + fix(fixer) { + return fixer.removeRange([token.range[1], nextToken.range[0]]); + } + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingSpace(node, token) { + const previousToken = sourceCode.getTokenBefore(token); + + context.report({ + node, + loc: { start: previousToken.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + tokenValue: token.value + }, + fix(fixer) { + return fixer.removeRange([previousToken.range[1], token.range[0]]); + } + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceAfter", + data: { + tokenValue: token.value + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + } + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceBefore", + data: { + tokenValue: token.value + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + } + }); + } + + /** + * Determines if a node is an object type + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an object type. + */ + function isObjectType(node) { + return node && (node.type === "ObjectExpression" || node.type === "ObjectPattern"); + } + + /** + * Determines if a node is an array type + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an array type. + */ + function isArrayType(node) { + return node && (node.type === "ArrayExpression" || node.type === "ArrayPattern"); + } + + /** + * Validates the spacing around array brackets + * @param {ASTNode} node The node we're checking for spacing + * @returns {void} + */ + function validateArraySpacing(node) { + if (options.spaced && node.elements.length === 0) { + return; + } + + const first = sourceCode.getFirstToken(node), + second = sourceCode.getFirstToken(node, 1), + last = node.typeAnnotation + ? sourceCode.getTokenBefore(node.typeAnnotation) + : sourceCode.getLastToken(node), + penultimate = sourceCode.getTokenBefore(last), + firstElement = node.elements[0], + lastElement = node.elements[node.elements.length - 1]; + + const openingBracketMustBeSpaced = + options.objectsInArraysException && isObjectType(firstElement) || + options.arraysInArraysException && isArrayType(firstElement) || + options.singleElementException && node.elements.length === 1 + ? !options.spaced : options.spaced; + + const closingBracketMustBeSpaced = + options.objectsInArraysException && isObjectType(lastElement) || + options.arraysInArraysException && isArrayType(lastElement) || + options.singleElementException && node.elements.length === 1 + ? !options.spaced : options.spaced; + + if (astUtils.isTokenOnSameLine(first, second)) { + if (openingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(first, second)) { + reportRequiredBeginningSpace(node, first); + } + if (!openingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(first, second)) { + reportNoBeginningSpace(node, first); + } + } + + if (first !== penultimate && astUtils.isTokenOnSameLine(penultimate, last)) { + if (closingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(penultimate, last)) { + reportRequiredEndingSpace(node, last); + } + if (!closingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(penultimate, last)) { + reportNoEndingSpace(node, last); + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ArrayPattern: validateArraySpacing, + ArrayExpression: validateArraySpacing + }; + } +}; diff --git a/node_modules/eslint/lib/rules/array-callback-return.js b/node_modules/eslint/lib/rules/array-callback-return.js new file mode 100644 index 0000000..05cd4ed --- /dev/null +++ b/node_modules/eslint/lib/rules/array-callback-return.js @@ -0,0 +1,296 @@ +/** + * @fileoverview Rule to enforce return statements in callbacks of array's methods + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u; +const TARGET_METHODS = /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort|toSorted)$/u; + +/** + * Checks a given code path segment is reachable. + * @param {CodePathSegment} segment A segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +/** + * Checks a given node is a member access which has the specified name's + * property. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a member access which has + * the specified name's property. The node may be a `(Chain|Member)Expression` node. + */ +function isTargetMethod(node) { + return astUtils.isSpecificMemberAccess(node, null, TARGET_METHODS); +} + +/** + * Returns a human-legible description of an array method + * @param {string} arrayMethodName A method name to fully qualify + * @returns {string} the method name prefixed with `Array.` if it is a class method, + * or else `Array.prototype.` if it is an instance method. + */ +function fullMethodName(arrayMethodName) { + if (["from", "of", "isArray"].includes(arrayMethodName)) { + return "Array.".concat(arrayMethodName); + } + return "Array.prototype.".concat(arrayMethodName); +} + +/** + * Checks whether or not a given node is a function expression which is the + * callback of an array method, returning the method name. + * @param {ASTNode} node A node to check. This is one of + * FunctionExpression or ArrowFunctionExpression. + * @returns {string} The method name if the node is a callback method, + * null otherwise. + */ +function getArrayMethodName(node) { + let currentNode = node; + + while (currentNode) { + const parent = currentNode.parent; + + switch (parent.type) { + + /* + * Looks up the destination. e.g., + * foo.every(nativeFoo || function foo() { ... }); + */ + case "LogicalExpression": + case "ConditionalExpression": + case "ChainExpression": + currentNode = parent; + break; + + /* + * If the upper function is IIFE, checks the destination of the return value. + * e.g. + * foo.every((function() { + * // setup... + * return function callback() { ... }; + * })()); + */ + case "ReturnStatement": { + const func = astUtils.getUpperFunction(parent); + + if (func === null || !astUtils.isCallee(func)) { + return null; + } + currentNode = func.parent; + break; + } + + /* + * e.g. + * Array.from([], function() {}); + * list.every(function() {}); + */ + case "CallExpression": + if (astUtils.isArrayFromMethod(parent.callee)) { + if ( + parent.arguments.length >= 2 && + parent.arguments[1] === currentNode + ) { + return "from"; + } + } + if (isTargetMethod(parent.callee)) { + if ( + parent.arguments.length >= 1 && + parent.arguments[0] === currentNode + ) { + return astUtils.getStaticPropertyName(parent.callee); + } + } + return null; + + // Otherwise this node is not target. + default: + return null; + } + } + + /* c8 ignore next */ + return null; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Enforce `return` statements in callbacks of array methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-callback-return" + }, + + schema: [ + { + type: "object", + properties: { + allowImplicit: { + type: "boolean", + default: false + }, + checkForEach: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + expectedAtEnd: "{{arrayMethodName}}() expects a value to be returned at the end of {{name}}.", + expectedInside: "{{arrayMethodName}}() expects a return value from {{name}}.", + expectedReturnValue: "{{arrayMethodName}}() expects a return value from {{name}}.", + expectedNoReturnValue: "{{arrayMethodName}}() expects no useless return value from {{name}}." + } + }, + + create(context) { + + const options = context.options[0] || { allowImplicit: false, checkForEach: false }; + const sourceCode = context.sourceCode; + + let funcInfo = { + arrayMethodName: null, + upper: null, + codePath: null, + hasReturn: false, + shouldCheck: false, + node: null + }; + + /** + * Checks whether or not the last code path segment is reachable. + * Then reports this function if the segment is reachable. + * + * If the last code path segment is reachable, there are paths which are not + * returned or thrown. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkLastSegment(node) { + + if (!funcInfo.shouldCheck) { + return; + } + + let messageId = null; + + if (funcInfo.arrayMethodName === "forEach") { + if (options.checkForEach && node.type === "ArrowFunctionExpression" && node.expression) { + messageId = "expectedNoReturnValue"; + } + } else { + if (node.body.type === "BlockStatement" && funcInfo.codePath.currentSegments.some(isReachable)) { + messageId = funcInfo.hasReturn ? "expectedAtEnd" : "expectedInside"; + } + } + + if (messageId) { + const name = astUtils.getFunctionNameWithKind(node); + + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId, + data: { name, arrayMethodName: fullMethodName(funcInfo.arrayMethodName) } + }); + } + } + + return { + + // Stacks this function's information. + onCodePathStart(codePath, node) { + + let methodName = null; + + if (TARGET_NODE_TYPE.test(node.type)) { + methodName = getArrayMethodName(node); + } + + funcInfo = { + arrayMethodName: methodName, + upper: funcInfo, + codePath, + hasReturn: false, + shouldCheck: + methodName && + !node.async && + !node.generator, + node + }; + }, + + // Pops this function's information. + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + // Checks the return statement is valid. + ReturnStatement(node) { + + if (!funcInfo.shouldCheck) { + return; + } + + funcInfo.hasReturn = true; + + let messageId = null; + + if (funcInfo.arrayMethodName === "forEach") { + + // if checkForEach: true, returning a value at any path inside a forEach is not allowed + if (options.checkForEach && node.argument) { + messageId = "expectedNoReturnValue"; + } + } else { + + // if allowImplicit: false, should also check node.argument + if (!options.allowImplicit && !node.argument) { + messageId = "expectedReturnValue"; + } + } + + if (messageId) { + context.report({ + node, + messageId, + data: { + name: astUtils.getFunctionNameWithKind(funcInfo.node), + arrayMethodName: fullMethodName(funcInfo.arrayMethodName) + } + }); + } + }, + + // Reports a given function if the last path is reachable. + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment + }; + } +}; diff --git a/node_modules/eslint/lib/rules/array-element-newline.js b/node_modules/eslint/lib/rules/array-element-newline.js new file mode 100644 index 0000000..0c806ef --- /dev/null +++ b/node_modules/eslint/lib/rules/array-element-newline.js @@ -0,0 +1,308 @@ +/** + * @fileoverview Rule to enforce line breaks after each array element + * @author Jan Peer Stöcklmair + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce line breaks after each array element", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-element-newline" + }, + + fixable: "whitespace", + + schema: { + definitions: { + basicConfig: { + oneOf: [ + { + enum: ["always", "never", "consistent"] + }, + { + type: "object", + properties: { + multiline: { + type: "boolean" + }, + minItems: { + type: ["integer", "null"], + minimum: 0 + } + }, + additionalProperties: false + } + ] + } + }, + type: "array", + items: [ + { + oneOf: [ + { + $ref: "#/definitions/basicConfig" + }, + { + type: "object", + properties: { + ArrayExpression: { + $ref: "#/definitions/basicConfig" + }, + ArrayPattern: { + $ref: "#/definitions/basicConfig" + } + }, + additionalProperties: false, + minProperties: 1 + } + ] + } + ] + }, + + messages: { + unexpectedLineBreak: "There should be no linebreak here.", + missingLineBreak: "There should be a linebreak after this element." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} providedOption An option value to parse. + * @returns {{multiline: boolean, minItems: number}} Normalized option object. + */ + function normalizeOptionValue(providedOption) { + let consistent = false; + let multiline = false; + let minItems; + + const option = providedOption || "always"; + + if (!option || option === "always" || option.minItems === 0) { + minItems = 0; + } else if (option === "never") { + minItems = Number.POSITIVE_INFINITY; + } else if (option === "consistent") { + consistent = true; + minItems = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(option.multiline); + minItems = option.minItems || Number.POSITIVE_INFINITY; + } + + return { consistent, multiline, minItems }; + } + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. + */ + function normalizeOptions(options) { + if (options && (options.ArrayExpression || options.ArrayPattern)) { + let expressionOptions, patternOptions; + + if (options.ArrayExpression) { + expressionOptions = normalizeOptionValue(options.ArrayExpression); + } + + if (options.ArrayPattern) { + patternOptions = normalizeOptionValue(options.ArrayPattern); + } + + return { ArrayExpression: expressionOptions, ArrayPattern: patternOptions }; + } + + const value = normalizeOptionValue(options); + + return { ArrayExpression: value, ArrayPattern: value }; + } + + /** + * Reports that there shouldn't be a line break after the first token + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoLineBreak(token) { + const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); + + context.report({ + loc: { + start: tokenBefore.loc.end, + end: token.loc.start + }, + messageId: "unexpectedLineBreak", + fix(fixer) { + if (astUtils.isCommentToken(tokenBefore)) { + return null; + } + + if (!astUtils.isTokenOnSameLine(tokenBefore, token)) { + return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " "); + } + + /* + * This will check if the comma is on the same line as the next element + * Following array: + * [ + * 1 + * , 2 + * , 3 + * ] + * + * will be fixed to: + * [ + * 1, 2, 3 + * ] + */ + const twoTokensBefore = sourceCode.getTokenBefore(tokenBefore, { includeComments: true }); + + if (astUtils.isCommentToken(twoTokensBefore)) { + return null; + } + + return fixer.replaceTextRange([twoTokensBefore.range[1], tokenBefore.range[0]], ""); + + } + }); + } + + /** + * Reports that there should be a line break after the first token + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredLineBreak(token) { + const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); + + context.report({ + loc: { + start: tokenBefore.loc.end, + end: token.loc.start + }, + messageId: "missingLineBreak", + fix(fixer) { + return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n"); + } + }); + } + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ObjectExpression node or an ObjectPattern node. + * @returns {void} + */ + function check(node) { + const elements = node.elements; + const normalizedOptions = normalizeOptions(context.options[0]); + const options = normalizedOptions[node.type]; + + if (!options) { + return; + } + + let elementBreak = false; + + /* + * MULTILINE: true + * loop through every element and check + * if at least one element has linebreaks inside + * this ensures that following is not valid (due to elements are on the same line): + * + * [ + * 1, + * 2, + * 3 + * ] + */ + if (options.multiline) { + elementBreak = elements + .filter(element => element !== null) + .some(element => element.loc.start.line !== element.loc.end.line); + } + + let linebreaksCount = 0; + + for (let i = 0; i < node.elements.length; i++) { + const element = node.elements[i]; + + const previousElement = elements[i - 1]; + + if (i === 0 || element === null || previousElement === null) { + continue; + } + + const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken); + const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken); + const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken); + + if (!astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) { + linebreaksCount++; + } + } + + const needsLinebreaks = ( + elements.length >= options.minItems || + ( + options.multiline && + elementBreak + ) || + ( + options.consistent && + linebreaksCount > 0 && + linebreaksCount < node.elements.length + ) + ); + + elements.forEach((element, i) => { + const previousElement = elements[i - 1]; + + if (i === 0 || element === null || previousElement === null) { + return; + } + + const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken); + const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken); + const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken); + + if (needsLinebreaks) { + if (astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) { + reportRequiredLineBreak(firstTokenOfCurrentElement); + } + } else { + if (!astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) { + reportNoLineBreak(firstTokenOfCurrentElement); + } + } + }); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + ArrayPattern: check, + ArrayExpression: check + }; + } +}; diff --git a/node_modules/eslint/lib/rules/arrow-body-style.js b/node_modules/eslint/lib/rules/arrow-body-style.js new file mode 100644 index 0000000..7590704 --- /dev/null +++ b/node_modules/eslint/lib/rules/arrow-body-style.js @@ -0,0 +1,296 @@ +/** + * @fileoverview Rule to require braces in arrow function body. + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require braces around arrow function bodies", + recommended: false, + url: "https://eslint.org/docs/latest/rules/arrow-body-style" + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always", "never"] + } + ], + minItems: 0, + maxItems: 1 + }, + { + type: "array", + items: [ + { + enum: ["as-needed"] + }, + { + type: "object", + properties: { + requireReturnForObjectLiteral: { type: "boolean" } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + } + ] + }, + + fixable: "code", + + messages: { + unexpectedOtherBlock: "Unexpected block statement surrounding arrow body.", + unexpectedEmptyBlock: "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.", + unexpectedObjectBlock: "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.", + unexpectedSingleBlock: "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.", + expectedBlock: "Expected block statement surrounding arrow body." + } + }, + + create(context) { + const options = context.options; + const always = options[0] === "always"; + const asNeeded = !options[0] || options[0] === "as-needed"; + const never = options[0] === "never"; + const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral; + const sourceCode = context.sourceCode; + let funcInfo = null; + + /** + * Checks whether the given node has ASI problem or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed. + */ + function hasASIProblem(token) { + return token && token.type === "Punctuator" && /^[([/`+-]/u.test(token.value); + } + + /** + * Gets the closing parenthesis by the given node. + * @param {ASTNode} node first node after an opening parenthesis. + * @returns {Token} The found closing parenthesis token. + */ + function findClosingParen(node) { + let nodeToCheck = node; + + while (!astUtils.isParenthesised(sourceCode, nodeToCheck)) { + nodeToCheck = nodeToCheck.parent; + } + return sourceCode.getTokenAfter(nodeToCheck); + } + + /** + * Check whether the node is inside of a for loop's init + * @param {ASTNode} node node is inside for loop + * @returns {boolean} `true` if the node is inside of a for loop, else `false` + */ + function isInsideForLoopInitializer(node) { + if (node && node.parent) { + if (node.parent.type === "ForStatement" && node.parent.init === node) { + return true; + } + return isInsideForLoopInitializer(node.parent); + } + return false; + } + + /** + * Determines whether a arrow function body needs braces + * @param {ASTNode} node The arrow function node. + * @returns {void} + */ + function validate(node) { + const arrowBody = node.body; + + if (arrowBody.type === "BlockStatement") { + const blockBody = arrowBody.body; + + if (blockBody.length !== 1 && !never) { + return; + } + + if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" && + blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") { + return; + } + + if (never || asNeeded && blockBody[0].type === "ReturnStatement") { + let messageId; + + if (blockBody.length === 0) { + messageId = "unexpectedEmptyBlock"; + } else if (blockBody.length > 1) { + messageId = "unexpectedOtherBlock"; + } else if (blockBody[0].argument === null) { + messageId = "unexpectedSingleBlock"; + } else if (astUtils.isOpeningBraceToken(sourceCode.getFirstToken(blockBody[0], { skip: 1 }))) { + messageId = "unexpectedObjectBlock"; + } else { + messageId = "unexpectedSingleBlock"; + } + + context.report({ + node, + loc: arrowBody.loc, + messageId, + fix(fixer) { + const fixes = []; + + if (blockBody.length !== 1 || + blockBody[0].type !== "ReturnStatement" || + !blockBody[0].argument || + hasASIProblem(sourceCode.getTokenAfter(arrowBody)) + ) { + return fixes; + } + + const openingBrace = sourceCode.getFirstToken(arrowBody); + const closingBrace = sourceCode.getLastToken(arrowBody); + const firstValueToken = sourceCode.getFirstToken(blockBody[0], 1); + const lastValueToken = sourceCode.getLastToken(blockBody[0]); + const commentsExist = + sourceCode.commentsExistBetween(openingBrace, firstValueToken) || + sourceCode.commentsExistBetween(lastValueToken, closingBrace); + + /* + * Remove tokens around the return value. + * If comments don't exist, remove extra spaces as well. + */ + if (commentsExist) { + fixes.push( + fixer.remove(openingBrace), + fixer.remove(closingBrace), + fixer.remove(sourceCode.getTokenAfter(openingBrace)) // return keyword + ); + } else { + fixes.push( + fixer.removeRange([openingBrace.range[0], firstValueToken.range[0]]), + fixer.removeRange([lastValueToken.range[1], closingBrace.range[1]]) + ); + } + + /* + * If the first token of the return value is `{` or the return value is a sequence expression, + * enclose the return value by parentheses to avoid syntax error. + */ + if (astUtils.isOpeningBraceToken(firstValueToken) || blockBody[0].argument.type === "SequenceExpression" || (funcInfo.hasInOperator && isInsideForLoopInitializer(node))) { + if (!astUtils.isParenthesised(sourceCode, blockBody[0].argument)) { + fixes.push( + fixer.insertTextBefore(firstValueToken, "("), + fixer.insertTextAfter(lastValueToken, ")") + ); + } + } + + /* + * If the last token of the return statement is semicolon, remove it. + * Non-block arrow body is an expression, not a statement. + */ + if (astUtils.isSemicolonToken(lastValueToken)) { + fixes.push(fixer.remove(lastValueToken)); + } + + return fixes; + } + }); + } + } else { + if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) { + context.report({ + node, + loc: arrowBody.loc, + messageId: "expectedBlock", + fix(fixer) { + const fixes = []; + const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken); + const [firstTokenAfterArrow, secondTokenAfterArrow] = sourceCode.getTokensAfter(arrowToken, { count: 2 }); + const lastToken = sourceCode.getLastToken(node); + + let parenthesisedObjectLiteral = null; + + if ( + astUtils.isOpeningParenToken(firstTokenAfterArrow) && + astUtils.isOpeningBraceToken(secondTokenAfterArrow) + ) { + const braceNode = sourceCode.getNodeByRangeIndex(secondTokenAfterArrow.range[0]); + + if (braceNode.type === "ObjectExpression") { + parenthesisedObjectLiteral = braceNode; + } + } + + // If the value is object literal, remove parentheses which were forced by syntax. + if (parenthesisedObjectLiteral) { + const openingParenToken = firstTokenAfterArrow; + const openingBraceToken = secondTokenAfterArrow; + + if (astUtils.isTokenOnSameLine(openingParenToken, openingBraceToken)) { + fixes.push(fixer.replaceText(openingParenToken, "{return ")); + } else { + + // Avoid ASI + fixes.push( + fixer.replaceText(openingParenToken, "{"), + fixer.insertTextBefore(openingBraceToken, "return ") + ); + } + + // Closing paren for the object doesn't have to be lastToken, e.g.: () => ({}).foo() + fixes.push(fixer.remove(findClosingParen(parenthesisedObjectLiteral))); + fixes.push(fixer.insertTextAfter(lastToken, "}")); + + } else { + fixes.push(fixer.insertTextBefore(firstTokenAfterArrow, "{return ")); + fixes.push(fixer.insertTextAfter(lastToken, "}")); + } + + return fixes; + } + }); + } + } + } + + return { + "BinaryExpression[operator='in']"() { + let info = funcInfo; + + while (info) { + info.hasInOperator = true; + info = info.upper; + } + }, + ArrowFunctionExpression() { + funcInfo = { + upper: funcInfo, + hasInOperator: false + }; + }, + "ArrowFunctionExpression:exit"(node) { + validate(node); + funcInfo = funcInfo.upper; + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/arrow-parens.js b/node_modules/eslint/lib/rules/arrow-parens.js new file mode 100644 index 0000000..0463323 --- /dev/null +++ b/node_modules/eslint/lib/rules/arrow-parens.js @@ -0,0 +1,183 @@ +/** + * @fileoverview Rule to require parens in arrow function arguments. + * @author Jxck + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given arrow function has block body. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {boolean} `true` if the function has block body. + */ +function hasBlockBody(node) { + return node.body.type === "BlockStatement"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require parentheses around arrow function arguments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/arrow-parens" + }, + + fixable: "code", + + schema: [ + { + enum: ["always", "as-needed"] + }, + { + type: "object", + properties: { + requireForBlockBody: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedParens: "Unexpected parentheses around single function argument.", + expectedParens: "Expected parentheses around arrow function argument.", + + unexpectedParensInline: "Unexpected parentheses around single function argument having a body with no curly braces.", + expectedParensBlock: "Expected parentheses around arrow function argument having a body with curly braces." + } + }, + + create(context) { + const asNeeded = context.options[0] === "as-needed"; + const requireForBlockBody = asNeeded && context.options[1] && context.options[1].requireForBlockBody === true; + + const sourceCode = context.sourceCode; + + /** + * Finds opening paren of parameters for the given arrow function, if it exists. + * It is assumed that the given arrow function has exactly one parameter. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {Token|null} the opening paren, or `null` if the given arrow function doesn't have parens of parameters. + */ + function findOpeningParenOfParams(node) { + const tokenBeforeParams = sourceCode.getTokenBefore(node.params[0]); + + if ( + tokenBeforeParams && + astUtils.isOpeningParenToken(tokenBeforeParams) && + node.range[0] <= tokenBeforeParams.range[0] + ) { + return tokenBeforeParams; + } + + return null; + } + + /** + * Finds closing paren of parameters for the given arrow function. + * It is assumed that the given arrow function has parens of parameters and that it has exactly one parameter. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {Token} the closing paren of parameters. + */ + function getClosingParenOfParams(node) { + return sourceCode.getTokenAfter(node.params[0], astUtils.isClosingParenToken); + } + + /** + * Determines whether the given arrow function has comments inside parens of parameters. + * It is assumed that the given arrow function has parens of parameters. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @param {Token} openingParen Opening paren of parameters. + * @returns {boolean} `true` if the function has at least one comment inside of parens of parameters. + */ + function hasCommentsInParensOfParams(node, openingParen) { + return sourceCode.commentsExistBetween(openingParen, getClosingParenOfParams(node)); + } + + /** + * Determines whether the given arrow function has unexpected tokens before opening paren of parameters, + * in which case it will be assumed that the existing parens of parameters are necessary. + * Only tokens within the range of the arrow function (tokens that are part of the arrow function) are taken into account. + * Example: (a) => b + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @param {Token} openingParen Opening paren of parameters. + * @returns {boolean} `true` if the function has at least one unexpected token. + */ + function hasUnexpectedTokensBeforeOpeningParen(node, openingParen) { + const expectedCount = node.async ? 1 : 0; + + return sourceCode.getFirstToken(node, { skip: expectedCount }) !== openingParen; + } + + return { + "ArrowFunctionExpression[params.length=1]"(node) { + const shouldHaveParens = !asNeeded || requireForBlockBody && hasBlockBody(node); + const openingParen = findOpeningParenOfParams(node); + const hasParens = openingParen !== null; + const [param] = node.params; + + if (shouldHaveParens && !hasParens) { + context.report({ + node, + messageId: requireForBlockBody ? "expectedParensBlock" : "expectedParens", + loc: param.loc, + *fix(fixer) { + yield fixer.insertTextBefore(param, "("); + yield fixer.insertTextAfter(param, ")"); + } + }); + } + + if ( + !shouldHaveParens && + hasParens && + param.type === "Identifier" && + !param.typeAnnotation && + !node.returnType && + !hasCommentsInParensOfParams(node, openingParen) && + !hasUnexpectedTokensBeforeOpeningParen(node, openingParen) + ) { + context.report({ + node, + messageId: requireForBlockBody ? "unexpectedParensInline" : "unexpectedParens", + loc: param.loc, + *fix(fixer) { + const tokenBeforeOpeningParen = sourceCode.getTokenBefore(openingParen); + const closingParen = getClosingParenOfParams(node); + + if ( + tokenBeforeOpeningParen && + tokenBeforeOpeningParen.range[1] === openingParen.range[0] && + !astUtils.canTokensBeAdjacent(tokenBeforeOpeningParen, sourceCode.getFirstToken(param)) + ) { + yield fixer.insertTextBefore(openingParen, " "); + } + + // remove parens, whitespace inside parens, and possible trailing comma + yield fixer.removeRange([openingParen.range[0], param.range[0]]); + yield fixer.removeRange([param.range[1], closingParen.range[1]]); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/arrow-spacing.js b/node_modules/eslint/lib/rules/arrow-spacing.js new file mode 100644 index 0000000..fb74d2c --- /dev/null +++ b/node_modules/eslint/lib/rules/arrow-spacing.js @@ -0,0 +1,161 @@ +/** + * @fileoverview Rule to define spacing before/after arrow function's arrow. + * @author Jxck + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing before and after the arrow in arrow functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/arrow-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: true + }, + after: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + expectedBefore: "Missing space before =>.", + unexpectedBefore: "Unexpected space before =>.", + + expectedAfter: "Missing space after =>.", + unexpectedAfter: "Unexpected space after =>." + } + }, + + create(context) { + + // merge rules with default + const rule = Object.assign({}, context.options[0]); + + rule.before = rule.before !== false; + rule.after = rule.after !== false; + + const sourceCode = context.sourceCode; + + /** + * Get tokens of arrow(`=>`) and before/after arrow. + * @param {ASTNode} node The arrow function node. + * @returns {Object} Tokens of arrow and before/after arrow. + */ + function getTokens(node) { + const arrow = sourceCode.getTokenBefore(node.body, astUtils.isArrowToken); + + return { + before: sourceCode.getTokenBefore(arrow), + arrow, + after: sourceCode.getTokenAfter(arrow) + }; + } + + /** + * Count spaces before/after arrow(`=>`) token. + * @param {Object} tokens Tokens before/after arrow. + * @returns {Object} count of space before/after arrow. + */ + function countSpaces(tokens) { + const before = tokens.arrow.range[0] - tokens.before.range[1]; + const after = tokens.after.range[0] - tokens.arrow.range[1]; + + return { before, after }; + } + + /** + * Determines whether space(s) before after arrow(`=>`) is satisfy rule. + * if before/after value is `true`, there should be space(s). + * if before/after value is `false`, there should be no space. + * @param {ASTNode} node The arrow function node. + * @returns {void} + */ + function spaces(node) { + const tokens = getTokens(node); + const countSpace = countSpaces(tokens); + + if (rule.before) { + + // should be space(s) before arrow + if (countSpace.before === 0) { + context.report({ + node: tokens.before, + messageId: "expectedBefore", + fix(fixer) { + return fixer.insertTextBefore(tokens.arrow, " "); + } + }); + } + } else { + + // should be no space before arrow + if (countSpace.before > 0) { + context.report({ + node: tokens.before, + messageId: "unexpectedBefore", + fix(fixer) { + return fixer.removeRange([tokens.before.range[1], tokens.arrow.range[0]]); + } + }); + } + } + + if (rule.after) { + + // should be space(s) after arrow + if (countSpace.after === 0) { + context.report({ + node: tokens.after, + messageId: "expectedAfter", + fix(fixer) { + return fixer.insertTextAfter(tokens.arrow, " "); + } + }); + } + } else { + + // should be no space after arrow + if (countSpace.after > 0) { + context.report({ + node: tokens.after, + messageId: "unexpectedAfter", + fix(fixer) { + return fixer.removeRange([tokens.arrow.range[1], tokens.after.range[0]]); + } + }); + } + } + } + + return { + ArrowFunctionExpression: spaces + }; + } +}; diff --git a/node_modules/eslint/lib/rules/block-scoped-var.js b/node_modules/eslint/lib/rules/block-scoped-var.js new file mode 100644 index 0000000..ec597d5 --- /dev/null +++ b/node_modules/eslint/lib/rules/block-scoped-var.js @@ -0,0 +1,135 @@ +/** + * @fileoverview Rule to check for "block scoped" variables by binding context + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce the use of variables within the scope they are defined", + recommended: false, + url: "https://eslint.org/docs/latest/rules/block-scoped-var" + }, + + schema: [], + + messages: { + outOfScope: "'{{name}}' declared on line {{definitionLine}} column {{definitionColumn}} is used outside of binding context." + } + }, + + create(context) { + let stack = []; + const sourceCode = context.sourceCode; + + /** + * Makes a block scope. + * @param {ASTNode} node A node of a scope. + * @returns {void} + */ + function enterScope(node) { + stack.push(node.range); + } + + /** + * Pops the last block scope. + * @returns {void} + */ + function exitScope() { + stack.pop(); + } + + /** + * Reports a given reference. + * @param {eslint-scope.Reference} reference A reference to report. + * @param {eslint-scope.Definition} definition A definition for which to report reference. + * @returns {void} + */ + function report(reference, definition) { + const identifier = reference.identifier; + const definitionPosition = definition.name.loc.start; + + context.report({ + node: identifier, + messageId: "outOfScope", + data: { + name: identifier.name, + definitionLine: definitionPosition.line, + definitionColumn: definitionPosition.column + 1 + } + }); + } + + /** + * Finds and reports references which are outside of valid scopes. + * @param {ASTNode} node A node to get variables. + * @returns {void} + */ + function checkForVariables(node) { + if (node.kind !== "var") { + return; + } + + // Defines a predicate to check whether or not a given reference is outside of valid scope. + const scopeRange = stack[stack.length - 1]; + + /** + * Check if a reference is out of scope + * @param {ASTNode} reference node to examine + * @returns {boolean} True is its outside the scope + * @private + */ + function isOutsideOfScope(reference) { + const idRange = reference.identifier.range; + + return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1]; + } + + // Gets declared variables, and checks its references. + const variables = sourceCode.getDeclaredVariables(node); + + for (let i = 0; i < variables.length; ++i) { + + // Reports. + variables[i] + .references + .filter(isOutsideOfScope) + .forEach(ref => report(ref, variables[i].defs.find(def => def.parent === node))); + } + } + + return { + Program(node) { + stack = [node.range]; + }, + + // Manages scopes. + BlockStatement: enterScope, + "BlockStatement:exit": exitScope, + ForStatement: enterScope, + "ForStatement:exit": exitScope, + ForInStatement: enterScope, + "ForInStatement:exit": exitScope, + ForOfStatement: enterScope, + "ForOfStatement:exit": exitScope, + SwitchStatement: enterScope, + "SwitchStatement:exit": exitScope, + CatchClause: enterScope, + "CatchClause:exit": exitScope, + StaticBlock: enterScope, + "StaticBlock:exit": exitScope, + + // Finds and reports references which are outside of valid scope. + VariableDeclaration: checkForVariables + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/block-spacing.js b/node_modules/eslint/lib/rules/block-spacing.js new file mode 100644 index 0000000..dd4851c --- /dev/null +++ b/node_modules/eslint/lib/rules/block-spacing.js @@ -0,0 +1,171 @@ +/** + * @fileoverview A rule to disallow or enforce spaces inside of single line blocks. + * @author Toru Nagashima + */ + +"use strict"; + +const util = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow or enforce spaces inside of blocks after opening block and before closing block", + recommended: false, + url: "https://eslint.org/docs/latest/rules/block-spacing" + }, + + fixable: "whitespace", + + schema: [ + { enum: ["always", "never"] } + ], + + messages: { + missing: "Requires a space {{location}} '{{token}}'.", + extra: "Unexpected space(s) {{location}} '{{token}}'." + } + }, + + create(context) { + const always = (context.options[0] !== "never"), + messageId = always ? "missing" : "extra", + sourceCode = context.sourceCode; + + /** + * Gets the open brace token from a given node. + * @param {ASTNode} node A BlockStatement/StaticBlock/SwitchStatement node to get. + * @returns {Token} The token of the open brace. + */ + function getOpenBrace(node) { + if (node.type === "SwitchStatement") { + if (node.cases.length > 0) { + return sourceCode.getTokenBefore(node.cases[0]); + } + return sourceCode.getLastToken(node, 1); + } + + if (node.type === "StaticBlock") { + return sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token + } + + // "BlockStatement" + return sourceCode.getFirstToken(node); + } + + /** + * Checks whether or not: + * - given tokens are on same line. + * - there is/isn't a space between given tokens. + * @param {Token} left A token to check. + * @param {Token} right The token which is next to `left`. + * @returns {boolean} + * When the option is `"always"`, `true` if there are one or more spaces between given tokens. + * When the option is `"never"`, `true` if there are not any spaces between given tokens. + * If given tokens are not on same line, it's always `true`. + */ + function isValid(left, right) { + return ( + !util.isTokenOnSameLine(left, right) || + sourceCode.isSpaceBetweenTokens(left, right) === always + ); + } + + /** + * Checks and reports invalid spacing style inside braces. + * @param {ASTNode} node A BlockStatement/StaticBlock/SwitchStatement node to check. + * @returns {void} + */ + function checkSpacingInsideBraces(node) { + + // Gets braces and the first/last token of content. + const openBrace = getOpenBrace(node); + const closeBrace = sourceCode.getLastToken(node); + const firstToken = sourceCode.getTokenAfter(openBrace, { includeComments: true }); + const lastToken = sourceCode.getTokenBefore(closeBrace, { includeComments: true }); + + // Skip if the node is invalid or empty. + if (openBrace.type !== "Punctuator" || + openBrace.value !== "{" || + closeBrace.type !== "Punctuator" || + closeBrace.value !== "}" || + firstToken === closeBrace + ) { + return; + } + + // Skip line comments for option never + if (!always && firstToken.type === "Line") { + return; + } + + // Check. + if (!isValid(openBrace, firstToken)) { + let loc = openBrace.loc; + + if (messageId === "extra") { + loc = { + start: openBrace.loc.end, + end: firstToken.loc.start + }; + } + + context.report({ + node, + loc, + messageId, + data: { + location: "after", + token: openBrace.value + }, + fix(fixer) { + if (always) { + return fixer.insertTextBefore(firstToken, " "); + } + + return fixer.removeRange([openBrace.range[1], firstToken.range[0]]); + } + }); + } + if (!isValid(lastToken, closeBrace)) { + let loc = closeBrace.loc; + + if (messageId === "extra") { + loc = { + start: lastToken.loc.end, + end: closeBrace.loc.start + }; + } + context.report({ + node, + loc, + messageId, + data: { + location: "before", + token: closeBrace.value + }, + fix(fixer) { + if (always) { + return fixer.insertTextAfter(lastToken, " "); + } + + return fixer.removeRange([lastToken.range[1], closeBrace.range[0]]); + } + }); + } + } + + return { + BlockStatement: checkSpacingInsideBraces, + StaticBlock: checkSpacingInsideBraces, + SwitchStatement: checkSpacingInsideBraces + }; + } +}; diff --git a/node_modules/eslint/lib/rules/brace-style.js b/node_modules/eslint/lib/rules/brace-style.js new file mode 100644 index 0000000..59758c9 --- /dev/null +++ b/node_modules/eslint/lib/rules/brace-style.js @@ -0,0 +1,194 @@ +/** + * @fileoverview Rule to flag block statements that do not use the one true brace style + * @author Ian Christian Myers + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent brace style for blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/brace-style" + }, + + schema: [ + { + enum: ["1tbs", "stroustrup", "allman"] + }, + { + type: "object", + properties: { + allowSingleLine: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + fixable: "whitespace", + + messages: { + nextLineOpen: "Opening curly brace does not appear on the same line as controlling statement.", + sameLineOpen: "Opening curly brace appears on the same line as controlling statement.", + blockSameLine: "Statement inside of curly braces should be on next line.", + nextLineClose: "Closing curly brace does not appear on the same line as the subsequent block.", + singleLineClose: "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.", + sameLineClose: "Closing curly brace appears on the same line as the subsequent block." + } + }, + + create(context) { + const style = context.options[0] || "1tbs", + params = context.options[1] || {}, + sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Fixes a place where a newline unexpectedly appears + * @param {Token} firstToken The token before the unexpected newline + * @param {Token} secondToken The token after the unexpected newline + * @returns {Function} A fixer function to remove the newlines between the tokens + */ + function removeNewlineBetween(firstToken, secondToken) { + const textRange = [firstToken.range[1], secondToken.range[0]]; + const textBetween = sourceCode.text.slice(textRange[0], textRange[1]); + + // Don't do a fix if there is a comment between the tokens + if (textBetween.trim()) { + return null; + } + return fixer => fixer.replaceTextRange(textRange, " "); + } + + /** + * Validates a pair of curly brackets based on the user's config + * @param {Token} openingCurly The opening curly bracket + * @param {Token} closingCurly The closing curly bracket + * @returns {void} + */ + function validateCurlyPair(openingCurly, closingCurly) { + const tokenBeforeOpeningCurly = sourceCode.getTokenBefore(openingCurly); + const tokenAfterOpeningCurly = sourceCode.getTokenAfter(openingCurly); + const tokenBeforeClosingCurly = sourceCode.getTokenBefore(closingCurly); + const singleLineException = params.allowSingleLine && astUtils.isTokenOnSameLine(openingCurly, closingCurly); + + if (style !== "allman" && !astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly)) { + context.report({ + node: openingCurly, + messageId: "nextLineOpen", + fix: removeNewlineBetween(tokenBeforeOpeningCurly, openingCurly) + }); + } + + if (style === "allman" && astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly) && !singleLineException) { + context.report({ + node: openingCurly, + messageId: "sameLineOpen", + fix: fixer => fixer.insertTextBefore(openingCurly, "\n") + }); + } + + if (astUtils.isTokenOnSameLine(openingCurly, tokenAfterOpeningCurly) && tokenAfterOpeningCurly !== closingCurly && !singleLineException) { + context.report({ + node: openingCurly, + messageId: "blockSameLine", + fix: fixer => fixer.insertTextAfter(openingCurly, "\n") + }); + } + + if (tokenBeforeClosingCurly !== openingCurly && !singleLineException && astUtils.isTokenOnSameLine(tokenBeforeClosingCurly, closingCurly)) { + context.report({ + node: closingCurly, + messageId: "singleLineClose", + fix: fixer => fixer.insertTextBefore(closingCurly, "\n") + }); + } + } + + /** + * Validates the location of a token that appears before a keyword (e.g. a newline before `else`) + * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`). + * @returns {void} + */ + function validateCurlyBeforeKeyword(curlyToken) { + const keywordToken = sourceCode.getTokenAfter(curlyToken); + + if (style === "1tbs" && !astUtils.isTokenOnSameLine(curlyToken, keywordToken)) { + context.report({ + node: curlyToken, + messageId: "nextLineClose", + fix: removeNewlineBetween(curlyToken, keywordToken) + }); + } + + if (style !== "1tbs" && astUtils.isTokenOnSameLine(curlyToken, keywordToken)) { + context.report({ + node: curlyToken, + messageId: "sameLineClose", + fix: fixer => fixer.insertTextAfter(curlyToken, "\n") + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + BlockStatement(node) { + if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { + validateCurlyPair(sourceCode.getFirstToken(node), sourceCode.getLastToken(node)); + } + }, + StaticBlock(node) { + validateCurlyPair( + sourceCode.getFirstToken(node, { skip: 1 }), // skip the `static` token + sourceCode.getLastToken(node) + ); + }, + ClassBody(node) { + validateCurlyPair(sourceCode.getFirstToken(node), sourceCode.getLastToken(node)); + }, + SwitchStatement(node) { + const closingCurly = sourceCode.getLastToken(node); + const openingCurly = sourceCode.getTokenBefore(node.cases.length ? node.cases[0] : closingCurly); + + validateCurlyPair(openingCurly, closingCurly); + }, + IfStatement(node) { + if (node.consequent.type === "BlockStatement" && node.alternate) { + + // Handle the keyword after the `if` block (before `else`) + validateCurlyBeforeKeyword(sourceCode.getLastToken(node.consequent)); + } + }, + TryStatement(node) { + + // Handle the keyword after the `try` block (before `catch` or `finally`) + validateCurlyBeforeKeyword(sourceCode.getLastToken(node.block)); + + if (node.handler && node.finalizer) { + + // Handle the keyword after the `catch` block (before `finally`) + validateCurlyBeforeKeyword(sourceCode.getLastToken(node.handler.body)); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/callback-return.js b/node_modules/eslint/lib/rules/callback-return.js new file mode 100644 index 0000000..5d441bd --- /dev/null +++ b/node_modules/eslint/lib/rules/callback-return.js @@ -0,0 +1,187 @@ +/** + * @fileoverview Enforce return after a callback. + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Require `return` statements after callbacks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/callback-return" + }, + + schema: [{ + type: "array", + items: { type: "string" } + }], + + messages: { + missingReturn: "Expected return with your callback function." + } + }, + + create(context) { + + const callbacks = context.options[0] || ["callback", "cb", "next"], + sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Find the closest parent matching a list of types. + * @param {ASTNode} node The node whose parents we are searching + * @param {Array} types The node types to match + * @returns {ASTNode} The matched node or undefined. + */ + function findClosestParentOfType(node, types) { + if (!node.parent) { + return null; + } + if (!types.includes(node.parent.type)) { + return findClosestParentOfType(node.parent, types); + } + return node.parent; + } + + /** + * Check to see if a node contains only identifiers + * @param {ASTNode} node The node to check + * @returns {boolean} Whether or not the node contains only identifiers + */ + function containsOnlyIdentifiers(node) { + if (node.type === "Identifier") { + return true; + } + + if (node.type === "MemberExpression") { + if (node.object.type === "Identifier") { + return true; + } + if (node.object.type === "MemberExpression") { + return containsOnlyIdentifiers(node.object); + } + } + + return false; + } + + /** + * Check to see if a CallExpression is in our callback list. + * @param {ASTNode} node The node to check against our callback names list. + * @returns {boolean} Whether or not this function matches our callback name. + */ + function isCallback(node) { + return containsOnlyIdentifiers(node.callee) && callbacks.includes(sourceCode.getText(node.callee)); + } + + /** + * Determines whether or not the callback is part of a callback expression. + * @param {ASTNode} node The callback node + * @param {ASTNode} parentNode The expression node + * @returns {boolean} Whether or not this is part of a callback expression + */ + function isCallbackExpression(node, parentNode) { + + // ensure the parent node exists and is an expression + if (!parentNode || parentNode.type !== "ExpressionStatement") { + return false; + } + + // cb() + if (parentNode.expression === node) { + return true; + } + + // special case for cb && cb() and similar + if (parentNode.expression.type === "BinaryExpression" || parentNode.expression.type === "LogicalExpression") { + if (parentNode.expression.right === node) { + return true; + } + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + CallExpression(node) { + + // if we're not a callback we can return + if (!isCallback(node)) { + return; + } + + // find the closest block, return or loop + const closestBlock = findClosestParentOfType(node, ["BlockStatement", "ReturnStatement", "ArrowFunctionExpression"]) || {}; + + // if our parent is a return we know we're ok + if (closestBlock.type === "ReturnStatement") { + return; + } + + // arrow functions don't always have blocks and implicitly return + if (closestBlock.type === "ArrowFunctionExpression") { + return; + } + + // block statements are part of functions and most if statements + if (closestBlock.type === "BlockStatement") { + + // find the last item in the block + const lastItem = closestBlock.body[closestBlock.body.length - 1]; + + // if the callback is the last thing in a block that might be ok + if (isCallbackExpression(node, lastItem)) { + + const parentType = closestBlock.parent.type; + + // but only if the block is part of a function + if (parentType === "FunctionExpression" || + parentType === "FunctionDeclaration" || + parentType === "ArrowFunctionExpression" + ) { + return; + } + + } + + // ending a block with a return is also ok + if (lastItem.type === "ReturnStatement") { + + // but only if the callback is immediately before + if (isCallbackExpression(node, closestBlock.body[closestBlock.body.length - 2])) { + return; + } + } + + } + + // as long as you're the child of a function at this point you should be asked to return + if (findClosestParentOfType(node, ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"])) { + context.report({ node, messageId: "missingReturn" }); + } + + } + + }; + } +}; diff --git a/node_modules/eslint/lib/rules/camelcase.js b/node_modules/eslint/lib/rules/camelcase.js new file mode 100644 index 0000000..51bb412 --- /dev/null +++ b/node_modules/eslint/lib/rules/camelcase.js @@ -0,0 +1,399 @@ +/** + * @fileoverview Rule to flag non-camelcased identifiers + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce camelcase naming convention", + recommended: false, + url: "https://eslint.org/docs/latest/rules/camelcase" + }, + + schema: [ + { + type: "object", + properties: { + ignoreDestructuring: { + type: "boolean", + default: false + }, + ignoreImports: { + type: "boolean", + default: false + }, + ignoreGlobals: { + type: "boolean", + default: false + }, + properties: { + enum: ["always", "never"] + }, + allow: { + type: "array", + items: [ + { + type: "string" + } + ], + minItems: 0, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + notCamelCase: "Identifier '{{name}}' is not in camel case.", + notCamelCasePrivate: "#{{name}} is not in camel case." + } + }, + + create(context) { + const options = context.options[0] || {}; + const properties = options.properties === "never" ? "never" : "always"; + const ignoreDestructuring = options.ignoreDestructuring; + const ignoreImports = options.ignoreImports; + const ignoreGlobals = options.ignoreGlobals; + const allow = options.allow || []; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // contains reported nodes to avoid reporting twice on destructuring with shorthand notation + const reported = new Set(); + + /** + * Checks if a string contains an underscore and isn't all upper-case + * @param {string} name The string to check. + * @returns {boolean} if the string is underscored + * @private + */ + function isUnderscored(name) { + const nameBody = name.replace(/^_+|_+$/gu, ""); + + // if there's an underscore, it might be A_CONSTANT, which is okay + return nameBody.includes("_") && nameBody !== nameBody.toUpperCase(); + } + + /** + * Checks if a string match the ignore list + * @param {string} name The string to check. + * @returns {boolean} if the string is ignored + * @private + */ + function isAllowed(name) { + return allow.some( + entry => name === entry || name.match(new RegExp(entry, "u")) + ); + } + + /** + * Checks if a given name is good or not. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is good. + * @private + */ + function isGoodName(name) { + return !isUnderscored(name) || isAllowed(name); + } + + /** + * Checks if a given identifier reference or member expression is an assignment + * target. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is an assignment target. + */ + function isAssignmentTarget(node) { + const parent = node.parent; + + switch (parent.type) { + case "AssignmentExpression": + case "AssignmentPattern": + return parent.left === node; + + case "Property": + return ( + parent.parent.type === "ObjectPattern" && + parent.value === node + ); + case "ArrayPattern": + case "RestElement": + return true; + + default: + return false; + } + } + + /** + * Checks if a given binding identifier uses the original name as-is. + * - If it's in object destructuring or object expression, the original name is its property name. + * - If it's in import declaration, the original name is its exported name. + * @param {ASTNode} node The `Identifier` node to check. + * @returns {boolean} `true` if the identifier uses the original name as-is. + */ + function equalsToOriginalName(node) { + const localName = node.name; + const valueNode = node.parent.type === "AssignmentPattern" + ? node.parent + : node; + const parent = valueNode.parent; + + switch (parent.type) { + case "Property": + return ( + (parent.parent.type === "ObjectPattern" || parent.parent.type === "ObjectExpression") && + parent.value === valueNode && + !parent.computed && + parent.key.type === "Identifier" && + parent.key.name === localName + ); + + case "ImportSpecifier": + return ( + parent.local === node && + astUtils.getModuleExportName(parent.imported) === localName + ); + + default: + return false; + } + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + if (reported.has(node.range[0])) { + return; + } + reported.add(node.range[0]); + + // Report it. + context.report({ + node, + messageId: node.type === "PrivateIdentifier" + ? "notCamelCasePrivate" + : "notCamelCase", + data: { name: node.name } + }); + } + + /** + * Reports an identifier reference or a binding identifier. + * @param {ASTNode} node The `Identifier` node to report. + * @returns {void} + */ + function reportReferenceId(node) { + + /* + * For backward compatibility, if it's in callings then ignore it. + * Not sure why it is. + */ + if ( + node.parent.type === "CallExpression" || + node.parent.type === "NewExpression" + ) { + return; + } + + /* + * For backward compatibility, if it's a default value of + * destructuring/parameters then ignore it. + * Not sure why it is. + */ + if ( + node.parent.type === "AssignmentPattern" && + node.parent.right === node + ) { + return; + } + + /* + * The `ignoreDestructuring` flag skips the identifiers that uses + * the property name as-is. + */ + if (ignoreDestructuring && equalsToOriginalName(node)) { + return; + } + + report(node); + } + + return { + + // Report camelcase of global variable references ------------------ + Program(node) { + const scope = sourceCode.getScope(node); + + if (!ignoreGlobals) { + + // Defined globals in config files or directive comments. + for (const variable of scope.variables) { + if ( + variable.identifiers.length > 0 || + isGoodName(variable.name) + ) { + continue; + } + for (const reference of variable.references) { + + /* + * For backward compatibility, this rule reports read-only + * references as well. + */ + reportReferenceId(reference.identifier); + } + } + } + + // Undefined globals. + for (const reference of scope.through) { + const id = reference.identifier; + + if (isGoodName(id.name)) { + continue; + } + + /* + * For backward compatibility, this rule reports read-only + * references as well. + */ + reportReferenceId(id); + } + }, + + // Report camelcase of declared variables -------------------------- + [[ + "VariableDeclaration", + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", + "ClassDeclaration", + "ClassExpression", + "CatchClause" + ]](node) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if (isGoodName(variable.name)) { + continue; + } + const id = variable.identifiers[0]; + + // Report declaration. + if (!(ignoreDestructuring && equalsToOriginalName(id))) { + report(id); + } + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + for (const reference of variable.references) { + if (reference.init) { + continue; // Skip the write references of initializers. + } + reportReferenceId(reference.identifier); + } + } + }, + + // Report camelcase in properties ---------------------------------- + [[ + "ObjectExpression > Property[computed!=true] > Identifier.key", + "MethodDefinition[computed!=true] > Identifier.key", + "PropertyDefinition[computed!=true] > Identifier.key", + "MethodDefinition > PrivateIdentifier.key", + "PropertyDefinition > PrivateIdentifier.key" + ]](node) { + if (properties === "never" || isGoodName(node.name)) { + return; + } + report(node); + }, + "MemberExpression[computed!=true] > Identifier.property"(node) { + if ( + properties === "never" || + !isAssignmentTarget(node.parent) || // ← ignore read-only references. + isGoodName(node.name) + ) { + return; + } + report(node); + }, + + // Report camelcase in import -------------------------------------- + ImportDeclaration(node) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if (isGoodName(variable.name)) { + continue; + } + const id = variable.identifiers[0]; + + // Report declaration. + if (!(ignoreImports && equalsToOriginalName(id))) { + report(id); + } + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + for (const reference of variable.references) { + reportReferenceId(reference.identifier); + } + } + }, + + // Report camelcase in re-export ----------------------------------- + [[ + "ExportAllDeclaration > Identifier.exported", + "ExportSpecifier > Identifier.exported" + ]](node) { + if (isGoodName(node.name)) { + return; + } + report(node); + }, + + // Report camelcase in labels -------------------------------------- + [[ + "LabeledStatement > Identifier.label", + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + "BreakStatement > Identifier.label", + "ContinueStatement > Identifier.label" + ]](node) { + if (isGoodName(node.name)) { + return; + } + report(node); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/capitalized-comments.js b/node_modules/eslint/lib/rules/capitalized-comments.js new file mode 100644 index 0000000..3a17b05 --- /dev/null +++ b/node_modules/eslint/lib/rules/capitalized-comments.js @@ -0,0 +1,300 @@ +/** + * @fileoverview enforce or disallow capitalization of the first letter of a comment + * @author Kevin Partington + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const LETTER_PATTERN = require("./utils/patterns/letters"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, + WHITESPACE = /\s/gu, + MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/u; // TODO: Combine w/ max-len pattern? + +/* + * Base schema body for defining the basic capitalization rule, ignorePattern, + * and ignoreInlineComments values. + * This can be used in a few different ways in the actual schema. + */ +const SCHEMA_BODY = { + type: "object", + properties: { + ignorePattern: { + type: "string" + }, + ignoreInlineComments: { + type: "boolean" + }, + ignoreConsecutiveComments: { + type: "boolean" + } + }, + additionalProperties: false +}; +const DEFAULTS = { + ignorePattern: "", + ignoreInlineComments: false, + ignoreConsecutiveComments: false +}; + +/** + * Get normalized options for either block or line comments from the given + * user-provided options. + * - If the user-provided options is just a string, returns a normalized + * set of options using default values for all other options. + * - If the user-provided options is an object, then a normalized option + * set is returned. Options specified in overrides will take priority + * over options specified in the main options object, which will in + * turn take priority over the rule's defaults. + * @param {Object|string} rawOptions The user-provided options. + * @param {string} which Either "line" or "block". + * @returns {Object} The normalized options. + */ +function getNormalizedOptions(rawOptions, which) { + return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); +} + +/** + * Get normalized options for block and line comments. + * @param {Object|string} rawOptions The user-provided options. + * @returns {Object} An object with "Line" and "Block" keys and corresponding + * normalized options objects. + */ +function getAllNormalizedOptions(rawOptions = {}) { + return { + Line: getNormalizedOptions(rawOptions, "line"), + Block: getNormalizedOptions(rawOptions, "block") + }; +} + +/** + * Creates a regular expression for each ignorePattern defined in the rule + * options. + * + * This is done in order to avoid invoking the RegExp constructor repeatedly. + * @param {Object} normalizedOptions The normalized rule options. + * @returns {void} + */ +function createRegExpForIgnorePatterns(normalizedOptions) { + Object.keys(normalizedOptions).forEach(key => { + const ignorePatternStr = normalizedOptions[key].ignorePattern; + + if (ignorePatternStr) { + const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u"); + + normalizedOptions[key].ignorePatternRegExp = regExp; + } + }); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce or disallow capitalization of the first letter of a comment", + recommended: false, + url: "https://eslint.org/docs/latest/rules/capitalized-comments" + }, + + fixable: "code", + + schema: [ + { enum: ["always", "never"] }, + { + oneOf: [ + SCHEMA_BODY, + { + type: "object", + properties: { + line: SCHEMA_BODY, + block: SCHEMA_BODY + }, + additionalProperties: false + } + ] + } + ], + + messages: { + unexpectedLowercaseComment: "Comments should not begin with a lowercase character.", + unexpectedUppercaseComment: "Comments should not begin with an uppercase character." + } + }, + + create(context) { + + const capitalize = context.options[0] || "always", + normalizedOptions = getAllNormalizedOptions(context.options[1]), + sourceCode = context.sourceCode; + + createRegExpForIgnorePatterns(normalizedOptions); + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks whether a comment is an inline comment. + * + * For the purpose of this rule, a comment is inline if: + * 1. The comment is preceded by a token on the same line; and + * 2. The command is followed by a token on the same line. + * + * Note that the comment itself need not be single-line! + * + * Also, it follows from this definition that only block comments can + * be considered as possibly inline. This is because line comments + * would consume any following tokens on the same line as the comment. + * @param {ASTNode} comment The comment node to check. + * @returns {boolean} True if the comment is an inline comment, false + * otherwise. + */ + function isInlineComment(comment) { + const previousToken = sourceCode.getTokenBefore(comment, { includeComments: true }), + nextToken = sourceCode.getTokenAfter(comment, { includeComments: true }); + + return Boolean( + previousToken && + nextToken && + comment.loc.start.line === previousToken.loc.end.line && + comment.loc.end.line === nextToken.loc.start.line + ); + } + + /** + * Determine if a comment follows another comment. + * @param {ASTNode} comment The comment to check. + * @returns {boolean} True if the comment follows a valid comment. + */ + function isConsecutiveComment(comment) { + const previousTokenOrComment = sourceCode.getTokenBefore(comment, { includeComments: true }); + + return Boolean( + previousTokenOrComment && + ["Block", "Line"].includes(previousTokenOrComment.type) + ); + } + + /** + * Check a comment to determine if it is valid for this rule. + * @param {ASTNode} comment The comment node to process. + * @param {Object} options The options for checking this comment. + * @returns {boolean} True if the comment is valid, false otherwise. + */ + function isCommentValid(comment, options) { + + // 1. Check for default ignore pattern. + if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { + return true; + } + + // 2. Check for custom ignore pattern. + const commentWithoutAsterisks = comment.value + .replace(/\*/gu, ""); + + if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) { + return true; + } + + // 3. Check for inline comments. + if (options.ignoreInlineComments && isInlineComment(comment)) { + return true; + } + + // 4. Is this a consecutive comment (and are we tolerating those)? + if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) { + return true; + } + + // 5. Does the comment start with a possible URL? + if (MAYBE_URL.test(commentWithoutAsterisks)) { + return true; + } + + // 6. Is the initial word character a letter? + const commentWordCharsOnly = commentWithoutAsterisks + .replace(WHITESPACE, ""); + + if (commentWordCharsOnly.length === 0) { + return true; + } + + const firstWordChar = commentWordCharsOnly[0]; + + if (!LETTER_PATTERN.test(firstWordChar)) { + return true; + } + + // 7. Check the case of the initial word character. + const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(), + isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase(); + + if (capitalize === "always" && isLowercase) { + return false; + } + if (capitalize === "never" && isUppercase) { + return false; + } + + return true; + } + + /** + * Process a comment to determine if it needs to be reported. + * @param {ASTNode} comment The comment node to process. + * @returns {void} + */ + function processComment(comment) { + const options = normalizedOptions[comment.type], + commentValid = isCommentValid(comment, options); + + if (!commentValid) { + const messageId = capitalize === "always" + ? "unexpectedLowercaseComment" + : "unexpectedUppercaseComment"; + + context.report({ + node: null, // Intentionally using loc instead + loc: comment.loc, + messageId, + fix(fixer) { + const match = comment.value.match(LETTER_PATTERN); + + return fixer.replaceTextRange( + + // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) + [comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], + capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase() + ); + } + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments.filter(token => token.type !== "Shebang").forEach(processComment); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/class-methods-use-this.js b/node_modules/eslint/lib/rules/class-methods-use-this.js new file mode 100644 index 0000000..9cf8a1b --- /dev/null +++ b/node_modules/eslint/lib/rules/class-methods-use-this.js @@ -0,0 +1,187 @@ +/** + * @fileoverview Rule to enforce that all class methods use 'this'. + * @author Patrick Williams + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce that class methods utilize `this`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/class-methods-use-this" + }, + + schema: [{ + type: "object", + properties: { + exceptMethods: { + type: "array", + items: { + type: "string" + } + }, + enforceForClassFields: { + type: "boolean", + default: true + } + }, + additionalProperties: false + }], + + messages: { + missingThis: "Expected 'this' to be used by class {{name}}." + } + }, + create(context) { + const config = Object.assign({}, context.options[0]); + const enforceForClassFields = config.enforceForClassFields !== false; + const exceptMethods = new Set(config.exceptMethods || []); + + const stack = []; + + /** + * Push `this` used flag initialized with `false` onto the stack. + * @returns {void} + */ + function pushContext() { + stack.push(false); + } + + /** + * Pop `this` used flag from the stack. + * @returns {boolean | undefined} `this` used flag + */ + function popContext() { + return stack.pop(); + } + + /** + * Initializes the current context to false and pushes it onto the stack. + * These booleans represent whether 'this' has been used in the context. + * @returns {void} + * @private + */ + function enterFunction() { + pushContext(); + } + + /** + * Check if the node is an instance method + * @param {ASTNode} node node to check + * @returns {boolean} True if its an instance method + * @private + */ + function isInstanceMethod(node) { + switch (node.type) { + case "MethodDefinition": + return !node.static && node.kind !== "constructor"; + case "PropertyDefinition": + return !node.static && enforceForClassFields; + default: + return false; + } + } + + /** + * Check if the node is an instance method not excluded by config + * @param {ASTNode} node node to check + * @returns {boolean} True if it is an instance method, and not excluded by config + * @private + */ + function isIncludedInstanceMethod(node) { + if (isInstanceMethod(node)) { + if (node.computed) { + return true; + } + + const hashIfNeeded = node.key.type === "PrivateIdentifier" ? "#" : ""; + const name = node.key.type === "Literal" + ? astUtils.getStaticStringValue(node.key) + : (node.key.name || ""); + + return !exceptMethods.has(hashIfNeeded + name); + } + return false; + } + + /** + * Checks if we are leaving a function that is a method, and reports if 'this' has not been used. + * Static methods and the constructor are exempt. + * Then pops the context off the stack. + * @param {ASTNode} node A function node that was entered. + * @returns {void} + * @private + */ + function exitFunction(node) { + const methodUsesThis = popContext(); + + if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, context.sourceCode), + messageId: "missingThis", + data: { + name: astUtils.getFunctionNameWithKind(node) + } + }); + } + } + + /** + * Mark the current context as having used 'this'. + * @returns {void} + * @private + */ + function markThisUsed() { + if (stack.length) { + stack[stack.length - 1] = true; + } + } + + return { + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + + /* + * Class field value are implicit functions. + */ + "PropertyDefinition > *.key:exit": pushContext, + "PropertyDefinition:exit": popContext, + + /* + * Class static blocks are implicit functions. They aren't required to use `this`, + * but we have to push context so that it captures any use of `this` in the static block + * separately from enclosing contexts, because static blocks have their own `this` and it + * shouldn't count as used `this` in enclosing contexts. + */ + StaticBlock: pushContext, + "StaticBlock:exit": popContext, + + ThisExpression: markThisUsed, + Super: markThisUsed, + ...( + enforceForClassFields && { + "PropertyDefinition > ArrowFunctionExpression.value": enterFunction, + "PropertyDefinition > ArrowFunctionExpression.value:exit": exitFunction + } + ) + }; + } +}; diff --git a/node_modules/eslint/lib/rules/comma-dangle.js b/node_modules/eslint/lib/rules/comma-dangle.js new file mode 100644 index 0000000..e49983b --- /dev/null +++ b/node_modules/eslint/lib/rules/comma-dangle.js @@ -0,0 +1,370 @@ +/** + * @fileoverview Rule to forbid or enforce dangling commas. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_OPTIONS = Object.freeze({ + arrays: "never", + objects: "never", + imports: "never", + exports: "never", + functions: "never" +}); + +/** + * Checks whether or not a trailing comma is allowed in a given node. + * If the `lastItem` is `RestElement` or `RestProperty`, it disallows trailing commas. + * @param {ASTNode} lastItem The node of the last element in the given node. + * @returns {boolean} `true` if a trailing comma is allowed. + */ +function isTrailingCommaAllowed(lastItem) { + return !( + lastItem.type === "RestElement" || + lastItem.type === "RestProperty" || + lastItem.type === "ExperimentalRestProperty" + ); +} + +/** + * Normalize option value. + * @param {string|Object|undefined} optionValue The 1st option value to normalize. + * @param {number} ecmaVersion The normalized ECMAScript version. + * @returns {Object} The normalized option value. + */ +function normalizeOptions(optionValue, ecmaVersion) { + if (typeof optionValue === "string") { + return { + arrays: optionValue, + objects: optionValue, + imports: optionValue, + exports: optionValue, + functions: ecmaVersion < 2017 ? "ignore" : optionValue + }; + } + if (typeof optionValue === "object" && optionValue !== null) { + return { + arrays: optionValue.arrays || DEFAULT_OPTIONS.arrays, + objects: optionValue.objects || DEFAULT_OPTIONS.objects, + imports: optionValue.imports || DEFAULT_OPTIONS.imports, + exports: optionValue.exports || DEFAULT_OPTIONS.exports, + functions: optionValue.functions || DEFAULT_OPTIONS.functions + }; + } + + return DEFAULT_OPTIONS; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow trailing commas", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-dangle" + }, + + fixable: "code", + + schema: { + definitions: { + value: { + enum: [ + "always-multiline", + "always", + "never", + "only-multiline" + ] + }, + valueWithIgnore: { + enum: [ + "always-multiline", + "always", + "ignore", + "never", + "only-multiline" + ] + } + }, + type: "array", + items: [ + { + oneOf: [ + { + $ref: "#/definitions/value" + }, + { + type: "object", + properties: { + arrays: { $ref: "#/definitions/valueWithIgnore" }, + objects: { $ref: "#/definitions/valueWithIgnore" }, + imports: { $ref: "#/definitions/valueWithIgnore" }, + exports: { $ref: "#/definitions/valueWithIgnore" }, + functions: { $ref: "#/definitions/valueWithIgnore" } + }, + additionalProperties: false + } + ] + } + ], + additionalItems: false + }, + + messages: { + unexpected: "Unexpected trailing comma.", + missing: "Missing trailing comma." + } + }, + + create(context) { + const options = normalizeOptions(context.options[0], context.languageOptions.ecmaVersion); + + const sourceCode = context.sourceCode; + + /** + * Gets the last item of the given node. + * @param {ASTNode} node The node to get. + * @returns {ASTNode|null} The last node or null. + */ + function getLastItem(node) { + + /** + * Returns the last element of an array + * @param {any[]} array The input array + * @returns {any} The last element + */ + function last(array) { + return array[array.length - 1]; + } + + switch (node.type) { + case "ObjectExpression": + case "ObjectPattern": + return last(node.properties); + case "ArrayExpression": + case "ArrayPattern": + return last(node.elements); + case "ImportDeclaration": + case "ExportNamedDeclaration": + return last(node.specifiers); + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + return last(node.params); + case "CallExpression": + case "NewExpression": + return last(node.arguments); + default: + return null; + } + } + + /** + * Gets the trailing comma token of the given node. + * If the trailing comma does not exist, this returns the token which is + * the insertion point of the trailing comma token. + * @param {ASTNode} node The node to get. + * @param {ASTNode} lastItem The last item of the node. + * @returns {Token} The trailing comma token or the insertion point. + */ + function getTrailingToken(node, lastItem) { + switch (node.type) { + case "ObjectExpression": + case "ArrayExpression": + case "CallExpression": + case "NewExpression": + return sourceCode.getLastToken(node, 1); + default: { + const nextToken = sourceCode.getTokenAfter(lastItem); + + if (astUtils.isCommaToken(nextToken)) { + return nextToken; + } + return sourceCode.getLastToken(lastItem); + } + } + } + + /** + * Checks whether or not a given node is multiline. + * This rule handles a given node as multiline when the closing parenthesis + * and the last element are not on the same line. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is multiline. + */ + function isMultiline(node) { + const lastItem = getLastItem(node); + + if (!lastItem) { + return false; + } + + const penultimateToken = getTrailingToken(node, lastItem); + const lastToken = sourceCode.getTokenAfter(penultimateToken); + + return lastToken.loc.end.line !== penultimateToken.loc.end.line; + } + + /** + * Reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forbidTrailingComma(node) { + const lastItem = getLastItem(node); + + if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { + return; + } + + const trailingToken = getTrailingToken(node, lastItem); + + if (astUtils.isCommaToken(trailingToken)) { + context.report({ + node: lastItem, + loc: trailingToken.loc, + messageId: "unexpected", + *fix(fixer) { + yield fixer.remove(trailingToken); + + /* + * Extend the range of the fix to include surrounding tokens to ensure + * that the element after which the comma is removed stays _last_. + * This intentionally makes conflicts in fix ranges with rules that may be + * adding or removing elements in the same autofix pass. + * https://github.com/eslint/eslint/issues/15660 + */ + yield fixer.insertTextBefore(sourceCode.getTokenBefore(trailingToken), ""); + yield fixer.insertTextAfter(sourceCode.getTokenAfter(trailingToken), ""); + } + }); + } + } + + /** + * Reports the last element of a given node if it does not have a trailing + * comma. + * + * If a given node is `ArrayPattern` which has `RestElement`, the trailing + * comma is disallowed, so report if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forceTrailingComma(node) { + const lastItem = getLastItem(node); + + if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { + return; + } + if (!isTrailingCommaAllowed(lastItem)) { + forbidTrailingComma(node); + return; + } + + const trailingToken = getTrailingToken(node, lastItem); + + if (trailingToken.value !== ",") { + context.report({ + node: lastItem, + loc: { + start: trailingToken.loc.end, + end: astUtils.getNextLocation(sourceCode, trailingToken.loc.end) + }, + messageId: "missing", + *fix(fixer) { + yield fixer.insertTextAfter(trailingToken, ","); + + /* + * Extend the range of the fix to include surrounding tokens to ensure + * that the element after which the comma is inserted stays _last_. + * This intentionally makes conflicts in fix ranges with rules that may be + * adding or removing elements in the same autofix pass. + * https://github.com/eslint/eslint/issues/15660 + */ + yield fixer.insertTextBefore(trailingToken, ""); + yield fixer.insertTextAfter(sourceCode.getTokenAfter(trailingToken), ""); + } + }); + } + } + + /** + * If a given node is multiline, reports the last element of a given node + * when it does not have a trailing comma. + * Otherwise, reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forceTrailingCommaIfMultiline(node) { + if (isMultiline(node)) { + forceTrailingComma(node); + } else { + forbidTrailingComma(node); + } + } + + /** + * Only if a given node is not multiline, reports the last element of a given node + * when it does not have a trailing comma. + * Otherwise, reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function allowTrailingCommaIfMultiline(node) { + if (!isMultiline(node)) { + forbidTrailingComma(node); + } + } + + const predicate = { + always: forceTrailingComma, + "always-multiline": forceTrailingCommaIfMultiline, + "only-multiline": allowTrailingCommaIfMultiline, + never: forbidTrailingComma, + ignore() {} + }; + + return { + ObjectExpression: predicate[options.objects], + ObjectPattern: predicate[options.objects], + + ArrayExpression: predicate[options.arrays], + ArrayPattern: predicate[options.arrays], + + ImportDeclaration: predicate[options.imports], + + ExportNamedDeclaration: predicate[options.exports], + + FunctionDeclaration: predicate[options.functions], + FunctionExpression: predicate[options.functions], + ArrowFunctionExpression: predicate[options.functions], + CallExpression: predicate[options.functions], + NewExpression: predicate[options.functions] + }; + } +}; diff --git a/node_modules/eslint/lib/rules/comma-spacing.js b/node_modules/eslint/lib/rules/comma-spacing.js new file mode 100644 index 0000000..96015ef --- /dev/null +++ b/node_modules/eslint/lib/rules/comma-spacing.js @@ -0,0 +1,189 @@ +/** + * @fileoverview Comma spacing - validates spacing before and after comma + * @author Vignesh Anand aka vegetableman. + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing before and after commas", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: false + }, + after: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + missing: "A space is required {{loc}} ','.", + unexpected: "There should be no space {{loc}} ','." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + const tokensAndComments = sourceCode.tokensAndComments; + + const options = { + before: context.options[0] ? context.options[0].before : false, + after: context.options[0] ? context.options[0].after : true + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // list of comma tokens to ignore for the check of leading whitespace + const commaTokensToIgnore = []; + + /** + * Reports a spacing error with an appropriate message. + * @param {ASTNode} node The binary expression node to report. + * @param {string} loc Is the error "before" or "after" the comma? + * @param {ASTNode} otherNode The node at the left or right of `node` + * @returns {void} + * @private + */ + function report(node, loc, otherNode) { + context.report({ + node, + fix(fixer) { + if (options[loc]) { + if (loc === "before") { + return fixer.insertTextBefore(node, " "); + } + return fixer.insertTextAfter(node, " "); + + } + let start, end; + const newText = ""; + + if (loc === "before") { + start = otherNode.range[1]; + end = node.range[0]; + } else { + start = node.range[1]; + end = otherNode.range[0]; + } + + return fixer.replaceTextRange([start, end], newText); + + }, + messageId: options[loc] ? "missing" : "unexpected", + data: { + loc + } + }); + } + + /** + * Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list. + * @param {ASTNode} node An ArrayExpression or ArrayPattern node. + * @returns {void} + */ + function addNullElementsToIgnoreList(node) { + let previousToken = sourceCode.getFirstToken(node); + + node.elements.forEach(element => { + let token; + + if (element === null) { + token = sourceCode.getTokenAfter(previousToken); + + if (astUtils.isCommaToken(token)) { + commaTokensToIgnore.push(token); + } + } else { + token = sourceCode.getTokenAfter(element); + } + + previousToken = token; + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program:exit"() { + tokensAndComments.forEach((token, i) => { + + if (!astUtils.isCommaToken(token)) { + return; + } + + const previousToken = tokensAndComments[i - 1]; + const nextToken = tokensAndComments[i + 1]; + + if ( + previousToken && + !astUtils.isCommaToken(previousToken) && // ignore spacing between two commas + + /* + * `commaTokensToIgnore` are ending commas of `null` elements (array holes/elisions). + * In addition to spacing between two commas, this can also ignore: + * + * - Spacing after `[` (controlled by array-bracket-spacing) + * Example: [ , ] + * ^ + * - Spacing after a comment (for backwards compatibility, this was possibly unintentional) + * Example: [a, /* * / ,] + * ^ + */ + !commaTokensToIgnore.includes(token) && + + astUtils.isTokenOnSameLine(previousToken, token) && + options.before !== sourceCode.isSpaceBetweenTokens(previousToken, token) + ) { + report(token, "before", previousToken); + } + + if ( + nextToken && + !astUtils.isCommaToken(nextToken) && // ignore spacing between two commas + !astUtils.isClosingParenToken(nextToken) && // controlled by space-in-parens + !astUtils.isClosingBracketToken(nextToken) && // controlled by array-bracket-spacing + !astUtils.isClosingBraceToken(nextToken) && // controlled by object-curly-spacing + !(!options.after && nextToken.type === "Line") && // special case, allow space before line comment + astUtils.isTokenOnSameLine(token, nextToken) && + options.after !== sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + report(token, "after", nextToken); + } + }); + }, + ArrayExpression: addNullElementsToIgnoreList, + ArrayPattern: addNullElementsToIgnoreList + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/comma-style.js b/node_modules/eslint/lib/rules/comma-style.js new file mode 100644 index 0000000..bc69de4 --- /dev/null +++ b/node_modules/eslint/lib/rules/comma-style.js @@ -0,0 +1,311 @@ +/** + * @fileoverview Comma style - enforces comma styles of two types: last and first + * @author Vignesh Anand aka vegetableman + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent comma style", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-style" + }, + + fixable: "code", + + schema: [ + { + enum: ["first", "last"] + }, + { + type: "object", + properties: { + exceptions: { + type: "object", + additionalProperties: { + type: "boolean" + } + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedLineBeforeAndAfterComma: "Bad line breaking before and after ','.", + expectedCommaFirst: "',' should be placed first.", + expectedCommaLast: "',' should be placed last." + } + }, + + create(context) { + const style = context.options[0] || "last", + sourceCode = context.sourceCode; + const exceptions = { + ArrayPattern: true, + ArrowFunctionExpression: true, + CallExpression: true, + FunctionDeclaration: true, + FunctionExpression: true, + ImportDeclaration: true, + ObjectPattern: true, + NewExpression: true + }; + + if (context.options.length === 2 && Object.prototype.hasOwnProperty.call(context.options[1], "exceptions")) { + const keys = Object.keys(context.options[1].exceptions); + + for (let i = 0; i < keys.length; i++) { + exceptions[keys[i]] = context.options[1].exceptions[keys[i]]; + } + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Modified text based on the style + * @param {string} styleType Style type + * @param {string} text Source code text + * @returns {string} modified text + * @private + */ + function getReplacedText(styleType, text) { + switch (styleType) { + case "between": + return `,${text.replace(astUtils.LINEBREAK_MATCHER, "")}`; + + case "first": + return `${text},`; + + case "last": + return `,${text}`; + + default: + return ""; + } + } + + /** + * Determines the fixer function for a given style. + * @param {string} styleType comma style + * @param {ASTNode} previousItemToken The token to check. + * @param {ASTNode} commaToken The token to check. + * @param {ASTNode} currentItemToken The token to check. + * @returns {Function} Fixer function + * @private + */ + function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) { + const text = + sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) + + sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]); + const range = [previousItemToken.range[1], currentItemToken.range[0]]; + + return function(fixer) { + return fixer.replaceTextRange(range, getReplacedText(styleType, text)); + }; + } + + /** + * Validates the spacing around single items in lists. + * @param {Token} previousItemToken The last token from the previous item. + * @param {Token} commaToken The token representing the comma. + * @param {Token} currentItemToken The first token of the current item. + * @param {Token} reportItem The item to use when reporting an error. + * @returns {void} + * @private + */ + function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) { + + // if single line + if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) && + astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { + + // do nothing. + + } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) && + !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { + + const comment = sourceCode.getCommentsAfter(commaToken)[0]; + const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment) + ? style + : "between"; + + // lone comma + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "unexpectedLineBeforeAndAfterComma", + fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) + }); + + } else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) { + + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "expectedCommaFirst", + fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken) + }); + + } else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) { + + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "expectedCommaLast", + fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken) + }); + } + } + + /** + * Checks the comma placement with regards to a declaration/property/element + * @param {ASTNode} node The binary expression node to check + * @param {string} property The property of the node containing child nodes. + * @private + * @returns {void} + */ + function validateComma(node, property) { + const items = node[property], + arrayLiteral = (node.type === "ArrayExpression" || node.type === "ArrayPattern"); + + if (items.length > 1 || arrayLiteral) { + + // seed as opening [ + let previousItemToken = sourceCode.getFirstToken(node); + + items.forEach(item => { + const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken, + currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken), + reportItem = item || currentItemToken; + + /* + * This works by comparing three token locations: + * - previousItemToken is the last token of the previous item + * - commaToken is the location of the comma before the current item + * - currentItemToken is the first token of the current item + * + * These values get switched around if item is undefined. + * previousItemToken will refer to the last token not belonging + * to the current item, which could be a comma or an opening + * square bracket. currentItemToken could be a comma. + * + * All comparisons are done based on these tokens directly, so + * they are always valid regardless of an undefined item. + */ + if (astUtils.isCommaToken(commaToken)) { + validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem); + } + + if (item) { + const tokenAfterItem = sourceCode.getTokenAfter(item, astUtils.isNotClosingParenToken); + + previousItemToken = tokenAfterItem + ? sourceCode.getTokenBefore(tokenAfterItem) + : sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1]; + } else { + previousItemToken = currentItemToken; + } + }); + + /* + * Special case for array literals that have empty last items, such + * as [ 1, 2, ]. These arrays only have two items show up in the + * AST, so we need to look at the token to verify that there's no + * dangling comma. + */ + if (arrayLiteral) { + + const lastToken = sourceCode.getLastToken(node), + nextToLastToken = sourceCode.getTokenBefore(lastToken); + + if (astUtils.isCommaToken(nextToLastToken)) { + validateCommaItemSpacing( + sourceCode.getTokenBefore(nextToLastToken), + nextToLastToken, + lastToken, + lastToken + ); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + const nodes = {}; + + if (!exceptions.VariableDeclaration) { + nodes.VariableDeclaration = function(node) { + validateComma(node, "declarations"); + }; + } + if (!exceptions.ObjectExpression) { + nodes.ObjectExpression = function(node) { + validateComma(node, "properties"); + }; + } + if (!exceptions.ObjectPattern) { + nodes.ObjectPattern = function(node) { + validateComma(node, "properties"); + }; + } + if (!exceptions.ArrayExpression) { + nodes.ArrayExpression = function(node) { + validateComma(node, "elements"); + }; + } + if (!exceptions.ArrayPattern) { + nodes.ArrayPattern = function(node) { + validateComma(node, "elements"); + }; + } + if (!exceptions.FunctionDeclaration) { + nodes.FunctionDeclaration = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.FunctionExpression) { + nodes.FunctionExpression = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.ArrowFunctionExpression) { + nodes.ArrowFunctionExpression = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.CallExpression) { + nodes.CallExpression = function(node) { + validateComma(node, "arguments"); + }; + } + if (!exceptions.ImportDeclaration) { + nodes.ImportDeclaration = function(node) { + validateComma(node, "specifiers"); + }; + } + if (!exceptions.NewExpression) { + nodes.NewExpression = function(node) { + validateComma(node, "arguments"); + }; + } + + return nodes; + } +}; diff --git a/node_modules/eslint/lib/rules/complexity.js b/node_modules/eslint/lib/rules/complexity.js new file mode 100644 index 0000000..b792507 --- /dev/null +++ b/node_modules/eslint/lib/rules/complexity.js @@ -0,0 +1,165 @@ +/** + * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity. + * Counts the number of if, conditional, for, while, try, switch/case, + * @author Patrick Brosset + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum cyclomatic complexity allowed in a program", + recommended: false, + url: "https://eslint.org/docs/latest/rules/complexity" + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0 + }, + max: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + complex: "{{name}} has a complexity of {{complexity}}. Maximum allowed is {{max}}." + } + }, + + create(context) { + const option = context.options[0]; + let THRESHOLD = 20; + + if ( + typeof option === "object" && + (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) + ) { + THRESHOLD = option.maximum || option.max; + } else if (typeof option === "number") { + THRESHOLD = option; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // Using a stack to store complexity per code path + const complexities = []; + + /** + * Increase the complexity of the code path in context + * @returns {void} + * @private + */ + function increaseComplexity() { + complexities[complexities.length - 1]++; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + onCodePathStart() { + + // The initial complexity is 1, representing one execution path in the CodePath + complexities.push(1); + }, + + // Each branching in the code adds 1 to the complexity + CatchClause: increaseComplexity, + ConditionalExpression: increaseComplexity, + LogicalExpression: increaseComplexity, + ForStatement: increaseComplexity, + ForInStatement: increaseComplexity, + ForOfStatement: increaseComplexity, + IfStatement: increaseComplexity, + WhileStatement: increaseComplexity, + DoWhileStatement: increaseComplexity, + + // Avoid `default` + "SwitchCase[test]": increaseComplexity, + + // Logical assignment operators have short-circuiting behavior + AssignmentExpression(node) { + if (astUtils.isLogicalAssignmentOperator(node.operator)) { + increaseComplexity(); + } + }, + + onCodePathEnd(codePath, node) { + const complexity = complexities.pop(); + + /* + * This rule only evaluates complexity of functions, so "program" is excluded. + * Class field initializers and class static blocks are implicit functions. Therefore, + * they shouldn't contribute to the enclosing function's complexity, but their + * own complexity should be evaluated. + */ + if ( + codePath.origin !== "function" && + codePath.origin !== "class-field-initializer" && + codePath.origin !== "class-static-block" + ) { + return; + } + + if (complexity > THRESHOLD) { + let name; + + if (codePath.origin === "class-field-initializer") { + name = "class field initializer"; + } else if (codePath.origin === "class-static-block") { + name = "class static block"; + } else { + name = astUtils.getFunctionNameWithKind(node); + } + + context.report({ + node, + messageId: "complex", + data: { + name: upperCaseFirst(name), + complexity, + max: THRESHOLD + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/computed-property-spacing.js b/node_modules/eslint/lib/rules/computed-property-spacing.js new file mode 100644 index 0000000..1e4e17c --- /dev/null +++ b/node_modules/eslint/lib/rules/computed-property-spacing.js @@ -0,0 +1,205 @@ +/** + * @fileoverview Disallows or enforces spaces inside computed properties. + * @author Jamund Ferguson + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing inside computed property brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/computed-property-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + enforceForClassMembers: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.", + unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.", + + missingSpaceBefore: "A space is required before '{{tokenValue}}'.", + missingSpaceAfter: "A space is required after '{{tokenValue}}'." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never" + const enforceForClassMembers = !context.options[1] || context.options[1].enforceForClassMembers; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @param {Token} tokenAfter The token after `token`. + * @returns {void} + */ + function reportNoBeginningSpace(node, token, tokenAfter) { + context.report({ + node, + loc: { start: token.loc.end, end: tokenAfter.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + tokenValue: token.value + }, + fix(fixer) { + return fixer.removeRange([token.range[1], tokenAfter.range[0]]); + } + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @param {Token} tokenBefore The token before `token`. + * @returns {void} + */ + function reportNoEndingSpace(node, token, tokenBefore) { + context.report({ + node, + loc: { start: tokenBefore.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + tokenValue: token.value + }, + fix(fixer) { + return fixer.removeRange([tokenBefore.range[1], token.range[0]]); + } + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceAfter", + data: { + tokenValue: token.value + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + } + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceBefore", + data: { + tokenValue: token.value + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + } + }); + } + + /** + * Returns a function that checks the spacing of a node on the property name + * that was passed in. + * @param {string} propertyName The property on the node to check for spacing + * @returns {Function} A function that will check spacing on a node + */ + function checkSpacing(propertyName) { + return function(node) { + if (!node.computed) { + return; + } + + const property = node[propertyName]; + + const before = sourceCode.getTokenBefore(property, astUtils.isOpeningBracketToken), + first = sourceCode.getTokenAfter(before, { includeComments: true }), + after = sourceCode.getTokenAfter(property, astUtils.isClosingBracketToken), + last = sourceCode.getTokenBefore(after, { includeComments: true }); + + if (astUtils.isTokenOnSameLine(before, first)) { + if (propertyNameMustBeSpaced) { + if (!sourceCode.isSpaceBetweenTokens(before, first) && astUtils.isTokenOnSameLine(before, first)) { + reportRequiredBeginningSpace(node, before); + } + } else { + if (sourceCode.isSpaceBetweenTokens(before, first)) { + reportNoBeginningSpace(node, before, first); + } + } + } + + if (astUtils.isTokenOnSameLine(last, after)) { + if (propertyNameMustBeSpaced) { + if (!sourceCode.isSpaceBetweenTokens(last, after) && astUtils.isTokenOnSameLine(last, after)) { + reportRequiredEndingSpace(node, after); + } + } else { + if (sourceCode.isSpaceBetweenTokens(last, after)) { + reportNoEndingSpace(node, after, last); + } + } + } + }; + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + const listeners = { + Property: checkSpacing("key"), + MemberExpression: checkSpacing("property") + }; + + if (enforceForClassMembers) { + listeners.MethodDefinition = + listeners.PropertyDefinition = listeners.Property; + } + + return listeners; + + } +}; diff --git a/node_modules/eslint/lib/rules/consistent-return.js b/node_modules/eslint/lib/rules/consistent-return.js new file mode 100644 index 0000000..e2d3f07 --- /dev/null +++ b/node_modules/eslint/lib/rules/consistent-return.js @@ -0,0 +1,185 @@ +/** + * @fileoverview Rule to flag consistent return values + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given code path segment is unreachable. + * @param {CodePathSegment} segment A CodePathSegment to check. + * @returns {boolean} `true` if the segment is unreachable. + */ +function isUnreachable(segment) { + return !segment.reachable; +} + +/** + * Checks whether a given node is a `constructor` method in an ES6 class + * @param {ASTNode} node A node to check + * @returns {boolean} `true` if the node is a `constructor` method + */ +function isClassConstructor(node) { + return node.type === "FunctionExpression" && + node.parent && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `return` statements to either always or never specify values", + recommended: false, + url: "https://eslint.org/docs/latest/rules/consistent-return" + }, + + schema: [{ + type: "object", + properties: { + treatUndefinedAsUnspecified: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + + messages: { + missingReturn: "Expected to return a value at the end of {{name}}.", + missingReturnValue: "{{name}} expected a return value.", + unexpectedReturnValue: "{{name}} expected no return value." + } + }, + + create(context) { + const options = context.options[0] || {}; + const treatUndefinedAsUnspecified = options.treatUndefinedAsUnspecified === true; + let funcInfo = null; + + /** + * Checks whether of not the implicit returning is consistent if the last + * code path segment is reachable. + * @param {ASTNode} node A program/function node to check. + * @returns {void} + */ + function checkLastSegment(node) { + let loc, name; + + /* + * Skip if it expected no return value or unreachable. + * When unreachable, all paths are returned or thrown. + */ + if (!funcInfo.hasReturnValue || + funcInfo.codePath.currentSegments.every(isUnreachable) || + astUtils.isES5Constructor(node) || + isClassConstructor(node) + ) { + return; + } + + // Adjust a location and a message. + if (node.type === "Program") { + + // The head of program. + loc = { line: 1, column: 0 }; + name = "program"; + } else if (node.type === "ArrowFunctionExpression") { + + // `=>` token + loc = context.sourceCode.getTokenBefore(node.body, astUtils.isArrowToken).loc; + } else if ( + node.parent.type === "MethodDefinition" || + (node.parent.type === "Property" && node.parent.method) + ) { + + // Method name. + loc = node.parent.key.loc; + } else { + + // Function name or `function` keyword. + loc = (node.id || context.sourceCode.getFirstToken(node)).loc; + } + + if (!name) { + name = astUtils.getFunctionNameWithKind(node); + } + + // Reports. + context.report({ + node, + loc, + messageId: "missingReturn", + data: { name } + }); + } + + return { + + // Initializes/Disposes state of each code path. + onCodePathStart(codePath, node) { + funcInfo = { + upper: funcInfo, + codePath, + hasReturn: false, + hasReturnValue: false, + messageId: "", + node + }; + }, + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + // Reports a given return statement if it's inconsistent. + ReturnStatement(node) { + const argument = node.argument; + let hasReturnValue = Boolean(argument); + + if (treatUndefinedAsUnspecified && hasReturnValue) { + hasReturnValue = !astUtils.isSpecificId(argument, "undefined") && argument.operator !== "void"; + } + + if (!funcInfo.hasReturn) { + funcInfo.hasReturn = true; + funcInfo.hasReturnValue = hasReturnValue; + funcInfo.messageId = hasReturnValue ? "missingReturnValue" : "unexpectedReturnValue"; + funcInfo.data = { + name: funcInfo.node.type === "Program" + ? "Program" + : upperCaseFirst(astUtils.getFunctionNameWithKind(funcInfo.node)) + }; + } else if (funcInfo.hasReturnValue !== hasReturnValue) { + context.report({ + node, + messageId: funcInfo.messageId, + data: funcInfo.data + }); + } + }, + + // Reports a given program/function if the implicit returning is not consistent. + "Program:exit": checkLastSegment, + "FunctionDeclaration:exit": checkLastSegment, + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment + }; + } +}; diff --git a/node_modules/eslint/lib/rules/consistent-this.js b/node_modules/eslint/lib/rules/consistent-this.js new file mode 100644 index 0000000..658957a --- /dev/null +++ b/node_modules/eslint/lib/rules/consistent-this.js @@ -0,0 +1,153 @@ +/** + * @fileoverview Rule to enforce consistent naming of "this" context variables + * @author Raphael Pigulla + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce consistent naming when capturing the current execution context", + recommended: false, + url: "https://eslint.org/docs/latest/rules/consistent-this" + }, + + schema: { + type: "array", + items: { + type: "string", + minLength: 1 + }, + uniqueItems: true + }, + + messages: { + aliasNotAssignedToThis: "Designated alias '{{name}}' is not assigned to 'this'.", + unexpectedAlias: "Unexpected alias '{{name}}' for 'this'." + } + }, + + create(context) { + let aliases = []; + const sourceCode = context.sourceCode; + + if (context.options.length === 0) { + aliases.push("that"); + } else { + aliases = context.options; + } + + /** + * Reports that a variable declarator or assignment expression is assigning + * a non-'this' value to the specified alias. + * @param {ASTNode} node The assigning node. + * @param {string} name the name of the alias that was incorrectly used. + * @returns {void} + */ + function reportBadAssignment(node, name) { + context.report({ node, messageId: "aliasNotAssignedToThis", data: { name } }); + } + + /** + * Checks that an assignment to an identifier only assigns 'this' to the + * appropriate alias, and the alias is only assigned to 'this'. + * @param {ASTNode} node The assigning node. + * @param {Identifier} name The name of the variable assigned to. + * @param {Expression} value The value of the assignment. + * @returns {void} + */ + function checkAssignment(node, name, value) { + const isThis = value.type === "ThisExpression"; + + if (aliases.includes(name)) { + if (!isThis || node.operator && node.operator !== "=") { + reportBadAssignment(node, name); + } + } else if (isThis) { + context.report({ node, messageId: "unexpectedAlias", data: { name } }); + } + } + + /** + * Ensures that a variable declaration of the alias in a program or function + * is assigned to the correct value. + * @param {string} alias alias the check the assignment of. + * @param {Object} scope scope of the current code we are checking. + * @private + * @returns {void} + */ + function checkWasAssigned(alias, scope) { + const variable = scope.set.get(alias); + + if (!variable) { + return; + } + + if (variable.defs.some(def => def.node.type === "VariableDeclarator" && + def.node.init !== null)) { + return; + } + + /* + * The alias has been declared and not assigned: check it was + * assigned later in the same scope. + */ + if (!variable.references.some(reference => { + const write = reference.writeExpr; + + return ( + reference.from === scope && + write && write.type === "ThisExpression" && + write.parent.operator === "=" + ); + })) { + variable.defs.map(def => def.node).forEach(node => { + reportBadAssignment(node, alias); + }); + } + } + + /** + * Check each alias to ensure that is was assigned to the correct value. + * @param {ASTNode} node The node that represents the scope to check. + * @returns {void} + */ + function ensureWasAssigned(node) { + const scope = sourceCode.getScope(node); + + aliases.forEach(alias => { + checkWasAssigned(alias, scope); + }); + } + + return { + "Program:exit": ensureWasAssigned, + "FunctionExpression:exit": ensureWasAssigned, + "FunctionDeclaration:exit": ensureWasAssigned, + + VariableDeclarator(node) { + const id = node.id; + const isDestructuring = + id.type === "ArrayPattern" || id.type === "ObjectPattern"; + + if (node.init !== null && !isDestructuring) { + checkAssignment(node, id.name, node.init); + } + }, + + AssignmentExpression(node) { + if (node.left.type === "Identifier") { + checkAssignment(node, node.left.name, node.right); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/constructor-super.js b/node_modules/eslint/lib/rules/constructor-super.js new file mode 100644 index 0000000..5f40588 --- /dev/null +++ b/node_modules/eslint/lib/rules/constructor-super.js @@ -0,0 +1,423 @@ +/** + * @fileoverview A rule to verify `super()` callings in constructor. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether a given code path segment is reachable or not. + * @param {CodePathSegment} segment A code path segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +/** + * Checks whether or not a given node is a constructor. + * @param {ASTNode} node A node to check. This node type is one of + * `Program`, `FunctionDeclaration`, `FunctionExpression`, and + * `ArrowFunctionExpression`. + * @returns {boolean} `true` if the node is a constructor. + */ +function isConstructorFunction(node) { + return ( + node.type === "FunctionExpression" && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor" + ); +} + +/** + * Checks whether a given node can be a constructor or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node can be a constructor. + */ +function isPossibleConstructor(node) { + if (!node) { + return false; + } + + switch (node.type) { + case "ClassExpression": + case "FunctionExpression": + case "ThisExpression": + case "MemberExpression": + case "CallExpression": + case "NewExpression": + case "ChainExpression": + case "YieldExpression": + case "TaggedTemplateExpression": + case "MetaProperty": + return true; + + case "Identifier": + return node.name !== "undefined"; + + case "AssignmentExpression": + if (["=", "&&="].includes(node.operator)) { + return isPossibleConstructor(node.right); + } + + if (["||=", "??="].includes(node.operator)) { + return ( + isPossibleConstructor(node.left) || + isPossibleConstructor(node.right) + ); + } + + /** + * All other assignment operators are mathematical assignment operators (arithmetic or bitwise). + * An assignment expression with a mathematical operator can either evaluate to a primitive value, + * or throw, depending on the operands. Thus, it cannot evaluate to a constructor function. + */ + return false; + + case "LogicalExpression": + + /* + * If the && operator short-circuits, the left side was falsy and therefore not a constructor, and if + * it doesn't short-circuit, it takes the value from the right side, so the right side must always be a + * possible constructor. A future improvement could verify that the left side could be truthy by + * excluding falsy literals. + */ + if (node.operator === "&&") { + return isPossibleConstructor(node.right); + } + + return ( + isPossibleConstructor(node.left) || + isPossibleConstructor(node.right) + ); + + case "ConditionalExpression": + return ( + isPossibleConstructor(node.alternate) || + isPossibleConstructor(node.consequent) + ); + + case "SequenceExpression": { + const lastExpression = node.expressions[node.expressions.length - 1]; + + return isPossibleConstructor(lastExpression); + } + + default: + return false; + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Require `super()` calls in constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/constructor-super" + }, + + schema: [], + + messages: { + missingSome: "Lacked a call of 'super()' in some code paths.", + missingAll: "Expected to call 'super()'.", + + duplicate: "Unexpected duplicate 'super()'.", + badSuper: "Unexpected 'super()' because 'super' is not a constructor.", + unexpected: "Unexpected 'super()'." + } + }, + + create(context) { + + /* + * {{hasExtends: boolean, scope: Scope, codePath: CodePath}[]} + * Information for each constructor. + * - upper: Information of the upper constructor. + * - hasExtends: A flag which shows whether own class has a valid `extends` + * part. + * - scope: The scope of own class. + * - codePath: The code path object of the constructor. + */ + let funcInfo = null; + + /* + * {Map} + * Information for each code path segment. + * - calledInSomePaths: A flag of be called `super()` in some code paths. + * - calledInEveryPaths: A flag of be called `super()` in all code paths. + * - validNodes: + */ + let segInfoMap = Object.create(null); + + /** + * Gets the flag which shows `super()` is called in some paths. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} The flag which shows `super()` is called in some paths + */ + function isCalledInSomePath(segment) { + return segment.reachable && segInfoMap[segment.id].calledInSomePaths; + } + + /** + * Gets the flag which shows `super()` is called in all paths. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} The flag which shows `super()` is called in all paths. + */ + function isCalledInEveryPath(segment) { + + /* + * If specific segment is the looped segment of the current segment, + * skip the segment. + * If not skipped, this never becomes true after a loop. + */ + if (segment.nextSegments.length === 1 && + segment.nextSegments[0].isLoopedPrevSegment(segment) + ) { + return true; + } + return segment.reachable && segInfoMap[segment.id].calledInEveryPaths; + } + + return { + + /** + * Stacks a constructor information. + * @param {CodePath} codePath A code path which was started. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathStart(codePath, node) { + if (isConstructorFunction(node)) { + + // Class > ClassBody > MethodDefinition > FunctionExpression + const classNode = node.parent.parent.parent; + const superClass = classNode.superClass; + + funcInfo = { + upper: funcInfo, + isConstructor: true, + hasExtends: Boolean(superClass), + superIsConstructor: isPossibleConstructor(superClass), + codePath + }; + } else { + funcInfo = { + upper: funcInfo, + isConstructor: false, + hasExtends: false, + superIsConstructor: false, + codePath + }; + } + }, + + /** + * Pops a constructor information. + * And reports if `super()` lacked. + * @param {CodePath} codePath A code path which was ended. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathEnd(codePath, node) { + const hasExtends = funcInfo.hasExtends; + + // Pop. + funcInfo = funcInfo.upper; + + if (!hasExtends) { + return; + } + + // Reports if `super()` lacked. + const segments = codePath.returnedSegments; + const calledInEveryPaths = segments.every(isCalledInEveryPath); + const calledInSomePaths = segments.some(isCalledInSomePath); + + if (!calledInEveryPaths) { + context.report({ + messageId: calledInSomePaths + ? "missingSome" + : "missingAll", + node: node.parent + }); + } + }, + + /** + * Initialize information of a given code path segment. + * @param {CodePathSegment} segment A code path segment to initialize. + * @returns {void} + */ + onCodePathSegmentStart(segment) { + if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Initialize info. + const info = segInfoMap[segment.id] = { + calledInSomePaths: false, + calledInEveryPaths: false, + validNodes: [] + }; + + // When there are previous segments, aggregates these. + const prevSegments = segment.prevSegments; + + if (prevSegments.length > 0) { + info.calledInSomePaths = prevSegments.some(isCalledInSomePath); + info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath); + } + }, + + /** + * Update information of the code path segment when a code path was + * looped. + * @param {CodePathSegment} fromSegment The code path segment of the + * end of a loop. + * @param {CodePathSegment} toSegment A code path segment of the head + * of a loop. + * @returns {void} + */ + onCodePathSegmentLoop(fromSegment, toSegment) { + if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Update information inside of the loop. + const isRealLoop = toSegment.prevSegments.length >= 2; + + funcInfo.codePath.traverseSegments( + { first: toSegment, last: fromSegment }, + segment => { + const info = segInfoMap[segment.id]; + const prevSegments = segment.prevSegments; + + // Updates flags. + info.calledInSomePaths = prevSegments.some(isCalledInSomePath); + info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath); + + // If flags become true anew, reports the valid nodes. + if (info.calledInSomePaths || isRealLoop) { + const nodes = info.validNodes; + + info.validNodes = []; + + for (let i = 0; i < nodes.length; ++i) { + const node = nodes[i]; + + context.report({ + messageId: "duplicate", + node + }); + } + } + } + ); + }, + + /** + * Checks for a call of `super()`. + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + "CallExpression:exit"(node) { + if (!(funcInfo && funcInfo.isConstructor)) { + return; + } + + // Skips except `super()`. + if (node.callee.type !== "Super") { + return; + } + + // Reports if needed. + if (funcInfo.hasExtends) { + const segments = funcInfo.codePath.currentSegments; + let duplicate = false; + let info = null; + + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + if (segment.reachable) { + info = segInfoMap[segment.id]; + + duplicate = duplicate || info.calledInSomePaths; + info.calledInSomePaths = info.calledInEveryPaths = true; + } + } + + if (info) { + if (duplicate) { + context.report({ + messageId: "duplicate", + node + }); + } else if (!funcInfo.superIsConstructor) { + context.report({ + messageId: "badSuper", + node + }); + } else { + info.validNodes.push(node); + } + } + } else if (funcInfo.codePath.currentSegments.some(isReachable)) { + context.report({ + messageId: "unexpected", + node + }); + } + }, + + /** + * Set the mark to the returned path as `super()` was called. + * @param {ASTNode} node A ReturnStatement node to check. + * @returns {void} + */ + ReturnStatement(node) { + if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Skips if no argument. + if (!node.argument) { + return; + } + + // Returning argument is a substitute of 'super()'. + const segments = funcInfo.codePath.currentSegments; + + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + if (segment.reachable) { + const info = segInfoMap[segment.id]; + + info.calledInSomePaths = info.calledInEveryPaths = true; + } + } + }, + + /** + * Resets state. + * @returns {void} + */ + "Program:exit"() { + segInfoMap = Object.create(null); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/curly.js b/node_modules/eslint/lib/rules/curly.js new file mode 100644 index 0000000..3540824 --- /dev/null +++ b/node_modules/eslint/lib/rules/curly.js @@ -0,0 +1,486 @@ +/** + * @fileoverview Rule to flag statements without curly braces + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce consistent brace style for all control statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/curly" + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["all"] + } + ], + minItems: 0, + maxItems: 1 + }, + { + type: "array", + items: [ + { + enum: ["multi", "multi-line", "multi-or-nest"] + }, + { + enum: ["consistent"] + } + ], + minItems: 0, + maxItems: 2 + } + ] + }, + + fixable: "code", + + messages: { + missingCurlyAfter: "Expected { after '{{name}}'.", + missingCurlyAfterCondition: "Expected { after '{{name}}' condition.", + unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.", + unexpectedCurlyAfterCondition: "Unnecessary { after '{{name}}' condition." + } + }, + + create(context) { + + const multiOnly = (context.options[0] === "multi"); + const multiLine = (context.options[0] === "multi-line"); + const multiOrNest = (context.options[0] === "multi-or-nest"); + const consistent = (context.options[1] === "consistent"); + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if a given node is a one-liner that's on the same line as it's preceding code. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code. + * @private + */ + function isCollapsedOneLiner(node) { + const before = sourceCode.getTokenBefore(node); + const last = sourceCode.getLastToken(node); + const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last; + + return before.loc.start.line === lastExcludingSemicolon.loc.end.line; + } + + /** + * Determines if a given node is a one-liner. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a one-liner. + * @private + */ + function isOneLiner(node) { + if (node.type === "EmptyStatement") { + return true; + } + + const first = sourceCode.getFirstToken(node); + const last = sourceCode.getLastToken(node); + const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last; + + return first.loc.start.line === lastExcludingSemicolon.loc.end.line; + } + + /** + * Determines if the given node is a lexical declaration (let, const, function, or class) + * @param {ASTNode} node The node to check + * @returns {boolean} True if the node is a lexical declaration + * @private + */ + function isLexicalDeclaration(node) { + if (node.type === "VariableDeclaration") { + return node.kind === "const" || node.kind === "let"; + } + + return node.type === "FunctionDeclaration" || node.type === "ClassDeclaration"; + } + + /** + * Checks if the given token is an `else` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an `else` token. + */ + function isElseKeywordToken(token) { + return token.value === "else" && token.type === "Keyword"; + } + + /** + * Determines whether the given node has an `else` keyword token as the first token after. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is followed by an `else` keyword token. + */ + function isFollowedByElseKeyword(node) { + const nextToken = sourceCode.getTokenAfter(node); + + return Boolean(nextToken) && isElseKeywordToken(nextToken); + } + + /** + * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError. + * @param {Token} closingBracket The } token + * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block. + */ + function needsSemicolon(closingBracket) { + const tokenBefore = sourceCode.getTokenBefore(closingBracket); + const tokenAfter = sourceCode.getTokenAfter(closingBracket); + const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]); + + if (astUtils.isSemicolonToken(tokenBefore)) { + + // If the last statement already has a semicolon, don't add another one. + return false; + } + + if (!tokenAfter) { + + // If there are no statements after this block, there is no need to add a semicolon. + return false; + } + + if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") { + + /* + * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression), + * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause + * a SyntaxError if it was followed by `else`. + */ + return false; + } + + if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) { + + // If the next token is on the same line, insert a semicolon. + return true; + } + + if (/^[([/`+-]/u.test(tokenAfter.value)) { + + // If the next token starts with a character that would disrupt ASI, insert a semicolon. + return true; + } + + if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) { + + // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI. + return true; + } + + // Otherwise, do not insert a semicolon. + return false; + } + + /** + * Determines whether the code represented by the given node contains an `if` statement + * that would become associated with an `else` keyword directly appended to that code. + * + * Examples where it returns `true`: + * + * if (a) + * foo(); + * + * if (a) { + * foo(); + * } + * + * if (a) + * foo(); + * else if (b) + * bar(); + * + * while (a) + * if (b) + * if(c) + * foo(); + * else + * bar(); + * + * Examples where it returns `false`: + * + * if (a) + * foo(); + * else + * bar(); + * + * while (a) { + * if (b) + * if(c) + * foo(); + * else + * bar(); + * } + * + * while (a) + * if (b) { + * if(c) + * foo(); + * } + * else + * bar(); + * @param {ASTNode} node Node representing the code to check. + * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code. + */ + function hasUnsafeIf(node) { + switch (node.type) { + case "IfStatement": + if (!node.alternate) { + return true; + } + return hasUnsafeIf(node.alternate); + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + case "LabeledStatement": + case "WithStatement": + case "WhileStatement": + return hasUnsafeIf(node.body); + default: + return false; + } + } + + /** + * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code. + * The braces, which make the given block body, are necessary in either of the following situations: + * + * 1. The statement is a lexical declaration. + * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace: + * + * if (a) { + * if (b) + * foo(); + * } + * else + * bar(); + * + * if (a) + * while (b) + * while (c) { + * while (d) + * if (e) + * while(f) + * foo(); + * } + * else + * bar(); + * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements. + * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content) + * would change the semantics of the code or produce a syntax error. + */ + function areBracesNecessary(node) { + const statement = node.body[0]; + + return isLexicalDeclaration(statement) || + hasUnsafeIf(statement) && isFollowedByElseKeyword(node); + } + + /** + * Prepares to check the body of a node to see if it's a block statement. + * @param {ASTNode} node The node to report if there's a problem. + * @param {ASTNode} body The body node to check for blocks. + * @param {string} name The name to report if there's a problem. + * @param {{ condition: boolean }} opts Options to pass to the report functions + * @returns {Object} a prepared check object, with "actual", "expected", "check" properties. + * "actual" will be `true` or `false` whether the body is already a block statement. + * "expected" will be `true` or `false` if the body should be a block statement or not, or + * `null` if it doesn't matter, depending on the rule options. It can be modified to change + * the final behavior of "check". + * "check" will be a function reporting appropriate problems depending on the other + * properties. + */ + function prepareCheck(node, body, name, opts) { + const hasBlock = (body.type === "BlockStatement"); + let expected = null; + + if (hasBlock && (body.body.length !== 1 || areBracesNecessary(body))) { + expected = true; + } else if (multiOnly) { + expected = false; + } else if (multiLine) { + if (!isCollapsedOneLiner(body)) { + expected = true; + } + + // otherwise, the body is allowed to have braces or not to have braces + + } else if (multiOrNest) { + if (hasBlock) { + const statement = body.body[0]; + const leadingCommentsInBlock = sourceCode.getCommentsBefore(statement); + + expected = !isOneLiner(statement) || leadingCommentsInBlock.length > 0; + } else { + expected = !isOneLiner(body); + } + } else { + + // default "all" + expected = true; + } + + return { + actual: hasBlock, + expected, + check() { + if (this.expected !== null && this.expected !== this.actual) { + if (this.expected) { + context.report({ + node, + loc: body.loc, + messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter", + data: { + name + }, + fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`) + }); + } else { + context.report({ + node, + loc: body.loc, + messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter", + data: { + name + }, + fix(fixer) { + + /* + * `do while` expressions sometimes need a space to be inserted after `do`. + * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)` + */ + const needsPrecedingSpace = node.type === "DoWhileStatement" && + sourceCode.getTokenBefore(body).range[1] === body.range[0] && + !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 })); + + const openingBracket = sourceCode.getFirstToken(body); + const closingBracket = sourceCode.getLastToken(body); + const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket); + + if (needsSemicolon(closingBracket)) { + + /* + * If removing braces would cause a SyntaxError due to multiple statements on the same line (or + * change the semantics of the code due to ASI), don't perform a fix. + */ + return null; + } + + const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) + + sourceCode.getText(lastTokenInBlock) + + sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]); + + return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText); + } + }); + } + } + } + }; + } + + /** + * Prepares to check the bodies of a "if", "else if" and "else" chain. + * @param {ASTNode} node The first IfStatement node of the chain. + * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more + * information. + */ + function prepareIfChecks(node) { + const preparedChecks = []; + + for (let currentNode = node; currentNode; currentNode = currentNode.alternate) { + preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true })); + if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") { + preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else")); + break; + } + } + + if (consistent) { + + /* + * If any node should have or already have braces, make sure they + * all have braces. + * If all nodes shouldn't have braces, make sure they don't. + */ + const expected = preparedChecks.some(preparedCheck => { + if (preparedCheck.expected !== null) { + return preparedCheck.expected; + } + return preparedCheck.actual; + }); + + preparedChecks.forEach(preparedCheck => { + preparedCheck.expected = expected; + }); + } + + return preparedChecks; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + IfStatement(node) { + const parent = node.parent; + const isElseIf = parent.type === "IfStatement" && parent.alternate === node; + + if (!isElseIf) { + + // This is a top `if`, check the whole `if-else-if` chain + prepareIfChecks(node).forEach(preparedCheck => { + preparedCheck.check(); + }); + } + + // Skip `else if`, it's already checked (when the top `if` was visited) + }, + + WhileStatement(node) { + prepareCheck(node, node.body, "while", { condition: true }).check(); + }, + + DoWhileStatement(node) { + prepareCheck(node, node.body, "do").check(); + }, + + ForStatement(node) { + prepareCheck(node, node.body, "for", { condition: true }).check(); + }, + + ForInStatement(node) { + prepareCheck(node, node.body, "for-in").check(); + }, + + ForOfStatement(node) { + prepareCheck(node, node.body, "for-of").check(); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/default-case-last.js b/node_modules/eslint/lib/rules/default-case-last.js new file mode 100644 index 0000000..d4a83b5 --- /dev/null +++ b/node_modules/eslint/lib/rules/default-case-last.js @@ -0,0 +1,44 @@ +/** + * @fileoverview Rule to enforce default clauses in switch statements to be last + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce default clauses in switch statements to be last", + recommended: false, + url: "https://eslint.org/docs/latest/rules/default-case-last" + }, + + schema: [], + + messages: { + notLast: "Default clause should be the last clause." + } + }, + + create(context) { + return { + SwitchStatement(node) { + const cases = node.cases, + indexOfDefault = cases.findIndex(c => c.test === null); + + if (indexOfDefault !== -1 && indexOfDefault !== cases.length - 1) { + const defaultClause = cases[indexOfDefault]; + + context.report({ node: defaultClause, messageId: "notLast" }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/default-case.js b/node_modules/eslint/lib/rules/default-case.js new file mode 100644 index 0000000..4f2fad0 --- /dev/null +++ b/node_modules/eslint/lib/rules/default-case.js @@ -0,0 +1,97 @@ +/** + * @fileoverview require default case in switch statements + * @author Aliaksei Shytkin + */ +"use strict"; + +const DEFAULT_COMMENT_PATTERN = /^no default$/iu; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `default` cases in `switch` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/default-case" + }, + + schema: [{ + type: "object", + properties: { + commentPattern: { + type: "string" + } + }, + additionalProperties: false + }], + + messages: { + missingDefaultCase: "Expected a default case." + } + }, + + create(context) { + const options = context.options[0] || {}; + const commentPattern = options.commentPattern + ? new RegExp(options.commentPattern, "u") + : DEFAULT_COMMENT_PATTERN; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Shortcut to get last element of array + * @param {*[]} collection Array + * @returns {any} Last element + */ + function last(collection) { + return collection[collection.length - 1]; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + SwitchStatement(node) { + + if (!node.cases.length) { + + /* + * skip check of empty switch because there is no easy way + * to extract comments inside it now + */ + return; + } + + const hasDefault = node.cases.some(v => v.test === null); + + if (!hasDefault) { + + let comment; + + const lastCase = last(node.cases); + const comments = sourceCode.getCommentsAfter(lastCase); + + if (comments.length) { + comment = last(comments); + } + + if (!comment || !commentPattern.test(comment.value.trim())) { + context.report({ node, messageId: "missingDefaultCase" }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/default-param-last.js b/node_modules/eslint/lib/rules/default-param-last.js new file mode 100644 index 0000000..3254fa8 --- /dev/null +++ b/node_modules/eslint/lib/rules/default-param-last.js @@ -0,0 +1,62 @@ +/** + * @fileoverview enforce default parameters to be last + * @author Chiawen Chen + */ + +"use strict"; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce default parameters to be last", + recommended: false, + url: "https://eslint.org/docs/latest/rules/default-param-last" + }, + + schema: [], + + messages: { + shouldBeLast: "Default parameters should be last." + } + }, + + create(context) { + + /** + * Handler for function contexts. + * @param {ASTNode} node function node + * @returns {void} + */ + function handleFunction(node) { + let hasSeenPlainParam = false; + + for (let i = node.params.length - 1; i >= 0; i -= 1) { + const param = node.params[i]; + + if ( + param.type !== "AssignmentPattern" && + param.type !== "RestElement" + ) { + hasSeenPlainParam = true; + continue; + } + + if (hasSeenPlainParam && param.type === "AssignmentPattern") { + context.report({ + node: param, + messageId: "shouldBeLast" + }); + } + } + } + + return { + FunctionDeclaration: handleFunction, + FunctionExpression: handleFunction, + ArrowFunctionExpression: handleFunction + }; + } +}; diff --git a/node_modules/eslint/lib/rules/dot-location.js b/node_modules/eslint/lib/rules/dot-location.js new file mode 100644 index 0000000..dac98b0 --- /dev/null +++ b/node_modules/eslint/lib/rules/dot-location.js @@ -0,0 +1,105 @@ +/** + * @fileoverview Validates newlines before and after dots + * @author Greg Cochard + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent newlines before and after dots", + recommended: false, + url: "https://eslint.org/docs/latest/rules/dot-location" + }, + + schema: [ + { + enum: ["object", "property"] + } + ], + + fixable: "code", + + messages: { + expectedDotAfterObject: "Expected dot to be on same line as object.", + expectedDotBeforeProperty: "Expected dot to be on same line as property." + } + }, + + create(context) { + + const config = context.options[0]; + + // default to onObject if no preference is passed + const onObject = config === "object" || !config; + + const sourceCode = context.sourceCode; + + /** + * Reports if the dot between object and property is on the correct location. + * @param {ASTNode} node The `MemberExpression` node. + * @returns {void} + */ + function checkDotLocation(node) { + const property = node.property; + const dotToken = sourceCode.getTokenBefore(property); + + if (onObject) { + + // `obj` expression can be parenthesized, but those paren tokens are not a part of the `obj` node. + const tokenBeforeDot = sourceCode.getTokenBefore(dotToken); + + if (!astUtils.isTokenOnSameLine(tokenBeforeDot, dotToken)) { + context.report({ + node, + loc: dotToken.loc, + messageId: "expectedDotAfterObject", + *fix(fixer) { + if (dotToken.value.startsWith(".") && astUtils.isDecimalIntegerNumericToken(tokenBeforeDot)) { + yield fixer.insertTextAfter(tokenBeforeDot, ` ${dotToken.value}`); + } else { + yield fixer.insertTextAfter(tokenBeforeDot, dotToken.value); + } + yield fixer.remove(dotToken); + } + }); + } + } else if (!astUtils.isTokenOnSameLine(dotToken, property)) { + context.report({ + node, + loc: dotToken.loc, + messageId: "expectedDotBeforeProperty", + *fix(fixer) { + yield fixer.remove(dotToken); + yield fixer.insertTextBefore(property, dotToken.value); + } + }); + } + } + + /** + * Checks the spacing of the dot within a member expression. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNode(node) { + if (!node.computed) { + checkDotLocation(node); + } + } + + return { + MemberExpression: checkNode + }; + } +}; diff --git a/node_modules/eslint/lib/rules/dot-notation.js b/node_modules/eslint/lib/rules/dot-notation.js new file mode 100644 index 0000000..21cba54 --- /dev/null +++ b/node_modules/eslint/lib/rules/dot-notation.js @@ -0,0 +1,176 @@ +/** + * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible. + * @author Josh Perez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u; + +// `null` literal must be handled separately. +const literalTypesToCheck = new Set(["string", "boolean"]); + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce dot notation whenever possible", + recommended: false, + url: "https://eslint.org/docs/latest/rules/dot-notation" + }, + + schema: [ + { + type: "object", + properties: { + allowKeywords: { + type: "boolean", + default: true + }, + allowPattern: { + type: "string", + default: "" + } + }, + additionalProperties: false + } + ], + + fixable: "code", + + messages: { + useDot: "[{{key}}] is better written in dot notation.", + useBrackets: ".{{key}} is a syntax error." + } + }, + + create(context) { + const options = context.options[0] || {}; + const allowKeywords = options.allowKeywords === void 0 || options.allowKeywords; + const sourceCode = context.sourceCode; + + let allowPattern; + + if (options.allowPattern) { + allowPattern = new RegExp(options.allowPattern, "u"); + } + + /** + * Check if the property is valid dot notation + * @param {ASTNode} node The dot notation node + * @param {string} value Value which is to be checked + * @returns {void} + */ + function checkComputedProperty(node, value) { + if ( + validIdentifier.test(value) && + (allowKeywords || !keywords.includes(String(value))) && + !(allowPattern && allowPattern.test(value)) + ) { + const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``; + + context.report({ + node: node.property, + messageId: "useDot", + data: { + key: formattedValue + }, + *fix(fixer) { + const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken); + const rightBracket = sourceCode.getLastToken(node); + const nextToken = sourceCode.getTokenAfter(node); + + // Don't perform any fixes if there are comments inside the brackets. + if (sourceCode.commentsExistBetween(leftBracket, rightBracket)) { + return; + } + + // Replace the brackets by an identifier. + if (!node.optional) { + yield fixer.insertTextBefore( + leftBracket, + astUtils.isDecimalInteger(node.object) ? " ." : "." + ); + } + yield fixer.replaceTextRange( + [leftBracket.range[0], rightBracket.range[1]], + value + ); + + // Insert a space after the property if it will be connected to the next token. + if ( + nextToken && + rightBracket.range[1] === nextToken.range[0] && + !astUtils.canTokensBeAdjacent(String(value), nextToken) + ) { + yield fixer.insertTextAfter(node, " "); + } + } + }); + } + } + + return { + MemberExpression(node) { + if ( + node.computed && + node.property.type === "Literal" && + (literalTypesToCheck.has(typeof node.property.value) || astUtils.isNullLiteral(node.property)) + ) { + checkComputedProperty(node, node.property.value); + } + if ( + node.computed && + astUtils.isStaticTemplateLiteral(node.property) + ) { + checkComputedProperty(node, node.property.quasis[0].value.cooked); + } + if ( + !allowKeywords && + !node.computed && + node.property.type === "Identifier" && + keywords.includes(String(node.property.name)) + ) { + context.report({ + node: node.property, + messageId: "useBrackets", + data: { + key: node.property.name + }, + *fix(fixer) { + const dotToken = sourceCode.getTokenBefore(node.property); + + // A statement that starts with `let[` is parsed as a destructuring variable declaration, not a MemberExpression. + if (node.object.type === "Identifier" && node.object.name === "let" && !node.optional) { + return; + } + + // Don't perform any fixes if there are comments between the dot and the property name. + if (sourceCode.commentsExistBetween(dotToken, node.property)) { + return; + } + + // Replace the identifier to brackets. + if (!node.optional) { + yield fixer.remove(dotToken); + } + yield fixer.replaceText(node.property, `["${node.property.name}"]`); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/eol-last.js b/node_modules/eslint/lib/rules/eol-last.js new file mode 100644 index 0000000..1036db1 --- /dev/null +++ b/node_modules/eslint/lib/rules/eol-last.js @@ -0,0 +1,112 @@ +/** + * @fileoverview Require or disallow newline at the end of files + * @author Nodeca Team + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow newline at the end of files", + recommended: false, + url: "https://eslint.org/docs/latest/rules/eol-last" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never", "unix", "windows"] + } + ], + + messages: { + missing: "Newline required at end of file but not found.", + unexpected: "Newline not allowed at end of file." + } + }, + create(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkBadEOF(node) { + const sourceCode = context.sourceCode, + src = sourceCode.getText(), + lastLine = sourceCode.lines[sourceCode.lines.length - 1], + location = { + column: lastLine.length, + line: sourceCode.lines.length + }, + LF = "\n", + CRLF = `\r${LF}`, + endsWithNewline = src.endsWith(LF); + + /* + * Empty source is always valid: No content in file so we don't + * need to lint for a newline on the last line of content. + */ + if (!src.length) { + return; + } + + let mode = context.options[0] || "always", + appendCRLF = false; + + if (mode === "unix") { + + // `"unix"` should behave exactly as `"always"` + mode = "always"; + } + if (mode === "windows") { + + // `"windows"` should behave exactly as `"always"`, but append CRLF in the fixer for backwards compatibility + mode = "always"; + appendCRLF = true; + } + if (mode === "always" && !endsWithNewline) { + + // File is not newline-terminated, but should be + context.report({ + node, + loc: location, + messageId: "missing", + fix(fixer) { + return fixer.insertTextAfterRange([0, src.length], appendCRLF ? CRLF : LF); + } + }); + } else if (mode === "never" && endsWithNewline) { + + const secondLastLine = sourceCode.lines[sourceCode.lines.length - 2]; + + // File is newline-terminated, but shouldn't be + context.report({ + node, + loc: { + start: { line: sourceCode.lines.length - 1, column: secondLastLine.length }, + end: { line: sourceCode.lines.length, column: 0 } + }, + messageId: "unexpected", + fix(fixer) { + const finalEOLs = /(?:\r?\n)+$/u, + match = finalEOLs.exec(sourceCode.text), + start = match.index, + end = sourceCode.text.length; + + return fixer.replaceTextRange([start, end], ""); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/eqeqeq.js b/node_modules/eslint/lib/rules/eqeqeq.js new file mode 100644 index 0000000..12b1e80 --- /dev/null +++ b/node_modules/eslint/lib/rules/eqeqeq.js @@ -0,0 +1,174 @@ +/** + * @fileoverview Rule to flag statements that use != and == instead of !== and === + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require the use of `===` and `!==`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/eqeqeq" + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always"] + }, + { + type: "object", + properties: { + null: { + enum: ["always", "never", "ignore"] + } + }, + additionalProperties: false + } + ], + additionalItems: false + }, + { + type: "array", + items: [ + { + enum: ["smart", "allow-null"] + } + ], + additionalItems: false + } + ] + }, + + fixable: "code", + + messages: { + unexpected: "Expected '{{expectedOperator}}' and instead saw '{{actualOperator}}'." + } + }, + + create(context) { + const config = context.options[0] || "always"; + const options = context.options[1] || {}; + const sourceCode = context.sourceCode; + + const nullOption = (config === "always") + ? options.null || "always" + : "ignore"; + const enforceRuleForNull = (nullOption === "always"); + const enforceInverseRuleForNull = (nullOption === "never"); + + /** + * Checks if an expression is a typeof expression + * @param {ASTNode} node The node to check + * @returns {boolean} if the node is a typeof expression + */ + function isTypeOf(node) { + return node.type === "UnaryExpression" && node.operator === "typeof"; + } + + /** + * Checks if either operand of a binary expression is a typeof operation + * @param {ASTNode} node The node to check + * @returns {boolean} if one of the operands is typeof + * @private + */ + function isTypeOfBinary(node) { + return isTypeOf(node.left) || isTypeOf(node.right); + } + + /** + * Checks if operands are literals of the same type (via typeof) + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are of same type + * @private + */ + function areLiteralsAndSameType(node) { + return node.left.type === "Literal" && node.right.type === "Literal" && + typeof node.left.value === typeof node.right.value; + } + + /** + * Checks if one of the operands is a literal null + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are null + * @private + */ + function isNullCheck(node) { + return astUtils.isNullLiteral(node.right) || astUtils.isNullLiteral(node.left); + } + + /** + * Reports a message for this rule. + * @param {ASTNode} node The binary expression node that was checked + * @param {string} expectedOperator The operator that was expected (either '==', '!=', '===', or '!==') + * @returns {void} + * @private + */ + function report(node, expectedOperator) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator + ); + + context.report({ + node, + loc: operatorToken.loc, + messageId: "unexpected", + data: { expectedOperator, actualOperator: node.operator }, + fix(fixer) { + + // If the comparison is a `typeof` comparison or both sides are literals with the same type, then it's safe to fix. + if (isTypeOfBinary(node) || areLiteralsAndSameType(node)) { + return fixer.replaceText(operatorToken, expectedOperator); + } + return null; + } + }); + } + + return { + BinaryExpression(node) { + const isNull = isNullCheck(node); + + if (node.operator !== "==" && node.operator !== "!=") { + if (enforceInverseRuleForNull && isNull) { + report(node, node.operator.slice(0, -1)); + } + return; + } + + if (config === "smart" && (isTypeOfBinary(node) || + areLiteralsAndSameType(node) || isNull)) { + return; + } + + if (!enforceRuleForNull && isNull) { + return; + } + + report(node, `${node.operator}=`); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/for-direction.js b/node_modules/eslint/lib/rules/for-direction.js new file mode 100644 index 0000000..4ed7350 --- /dev/null +++ b/node_modules/eslint/lib/rules/for-direction.js @@ -0,0 +1,126 @@ +/** + * @fileoverview enforce "for" loop update clause moving the counter in the right direction.(for-direction) + * @author Aladdin-ADD + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Enforce \"for\" loop update clause moving the counter in the right direction", + recommended: true, + url: "https://eslint.org/docs/latest/rules/for-direction" + }, + + fixable: null, + schema: [], + + messages: { + incorrectDirection: "The update clause in this loop moves the variable in the wrong direction." + } + }, + + create(context) { + + /** + * report an error. + * @param {ASTNode} node the node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "incorrectDirection" + }); + } + + /** + * check the right side of the assignment + * @param {ASTNode} update UpdateExpression to check + * @param {int} dir expected direction that could either be turned around or invalidated + * @returns {int} return dir, the negated dir or zero if it's not clear for identifiers + */ + function getRightDirection(update, dir) { + if (update.right.type === "UnaryExpression") { + if (update.right.operator === "-") { + return -dir; + } + } else if (update.right.type === "Identifier") { + return 0; + } + return dir; + } + + /** + * check UpdateExpression add/sub the counter + * @param {ASTNode} update UpdateExpression to check + * @param {string} counter variable name to check + * @returns {int} if add return 1, if sub return -1, if nochange, return 0 + */ + function getUpdateDirection(update, counter) { + if (update.argument.type === "Identifier" && update.argument.name === counter) { + if (update.operator === "++") { + return 1; + } + if (update.operator === "--") { + return -1; + } + } + return 0; + } + + /** + * check AssignmentExpression add/sub the counter + * @param {ASTNode} update AssignmentExpression to check + * @param {string} counter variable name to check + * @returns {int} if add return 1, if sub return -1, if nochange, return 0 + */ + function getAssignmentDirection(update, counter) { + if (update.left.name === counter) { + if (update.operator === "+=") { + return getRightDirection(update, 1); + } + if (update.operator === "-=") { + return getRightDirection(update, -1); + } + } + return 0; + } + return { + ForStatement(node) { + + if (node.test && node.test.type === "BinaryExpression" && node.test.left.type === "Identifier" && node.update) { + const counter = node.test.left.name; + const operator = node.test.operator; + const update = node.update; + + let wrongDirection; + + if (operator === "<" || operator === "<=") { + wrongDirection = -1; + } else if (operator === ">" || operator === ">=") { + wrongDirection = 1; + } else { + return; + } + + if (update.type === "UpdateExpression") { + if (getUpdateDirection(update, counter) === wrongDirection) { + report(node); + } + } else if (update.type === "AssignmentExpression" && getAssignmentDirection(update, counter) === wrongDirection) { + report(node); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/func-call-spacing.js b/node_modules/eslint/lib/rules/func-call-spacing.js new file mode 100644 index 0000000..3d5e538 --- /dev/null +++ b/node_modules/eslint/lib/rules/func-call-spacing.js @@ -0,0 +1,230 @@ +/** + * @fileoverview Rule to control spacing within function calls + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow spacing between function identifiers and their invocations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/func-call-spacing" + }, + + fixable: "whitespace", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["never"] + } + ], + minItems: 0, + maxItems: 1 + }, + { + type: "array", + items: [ + { + enum: ["always"] + }, + { + type: "object", + properties: { + allowNewlines: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + } + ] + }, + + messages: { + unexpectedWhitespace: "Unexpected whitespace between function name and paren.", + unexpectedNewline: "Unexpected newline between function name and paren.", + missing: "Missing space between function name and paren." + } + }, + + create(context) { + + const never = context.options[0] !== "always"; + const allowNewlines = !never && context.options[1] && context.options[1].allowNewlines; + const sourceCode = context.sourceCode; + const text = sourceCode.getText(); + + /** + * Check if open space is present in a function name + * @param {ASTNode} node node to evaluate + * @param {Token} leftToken The last token of the callee. This may be the closing parenthesis that encloses the callee. + * @param {Token} rightToken Tha first token of the arguments. this is the opening parenthesis that encloses the arguments. + * @returns {void} + * @private + */ + function checkSpacing(node, leftToken, rightToken) { + const textBetweenTokens = text.slice(leftToken.range[1], rightToken.range[0]).replace(/\/\*.*?\*\//gu, ""); + const hasWhitespace = /\s/u.test(textBetweenTokens); + const hasNewline = hasWhitespace && astUtils.LINEBREAK_MATCHER.test(textBetweenTokens); + + /* + * never allowNewlines hasWhitespace hasNewline message + * F F F F Missing space between function name and paren. + * F F F T (Invalid `!hasWhitespace && hasNewline`) + * F F T T Unexpected newline between function name and paren. + * F F T F (OK) + * F T T F (OK) + * F T T T (OK) + * F T F T (Invalid `!hasWhitespace && hasNewline`) + * F T F F Missing space between function name and paren. + * T T F F (Invalid `never && allowNewlines`) + * T T F T (Invalid `!hasWhitespace && hasNewline`) + * T T T T (Invalid `never && allowNewlines`) + * T T T F (Invalid `never && allowNewlines`) + * T F T F Unexpected space between function name and paren. + * T F T T Unexpected space between function name and paren. + * T F F T (Invalid `!hasWhitespace && hasNewline`) + * T F F F (OK) + * + * T T Unexpected space between function name and paren. + * F F Missing space between function name and paren. + * F F T Unexpected newline between function name and paren. + */ + + if (never && hasWhitespace) { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: { + line: rightToken.loc.start.line, + column: rightToken.loc.start.column - 1 + } + }, + messageId: "unexpectedWhitespace", + fix(fixer) { + + // Don't remove comments. + if (sourceCode.commentsExistBetween(leftToken, rightToken)) { + return null; + } + + // If `?.` exists, it doesn't hide no-unexpected-multiline errors + if (node.optional) { + return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], "?."); + } + + /* + * Only autofix if there is no newline + * https://github.com/eslint/eslint/issues/7787 + */ + if (hasNewline) { + return null; + } + return fixer.removeRange([leftToken.range[1], rightToken.range[0]]); + } + }); + } else if (!never && !hasWhitespace) { + context.report({ + node, + loc: { + start: { + line: leftToken.loc.end.line, + column: leftToken.loc.end.column - 1 + }, + end: rightToken.loc.start + }, + messageId: "missing", + fix(fixer) { + if (node.optional) { + return null; // Not sure if inserting a space to either before/after `?.` token. + } + return fixer.insertTextBefore(rightToken, " "); + } + }); + } else if (!never && !allowNewlines && hasNewline) { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: rightToken.loc.start + }, + messageId: "unexpectedNewline", + fix(fixer) { + + /* + * Only autofix if there is no newline + * https://github.com/eslint/eslint/issues/7787 + * But if `?.` exists, it doesn't hide no-unexpected-multiline errors + */ + if (!node.optional) { + return null; + } + + // Don't remove comments. + if (sourceCode.commentsExistBetween(leftToken, rightToken)) { + return null; + } + + const range = [leftToken.range[1], rightToken.range[0]]; + const qdToken = sourceCode.getTokenAfter(leftToken); + + if (qdToken.range[0] === leftToken.range[1]) { + return fixer.replaceTextRange(range, "?. "); + } + if (qdToken.range[1] === rightToken.range[0]) { + return fixer.replaceTextRange(range, " ?."); + } + return fixer.replaceTextRange(range, " ?. "); + } + }); + } + } + + return { + "CallExpression, NewExpression"(node) { + const lastToken = sourceCode.getLastToken(node); + const lastCalleeToken = sourceCode.getLastToken(node.callee); + const parenToken = sourceCode.getFirstTokenBetween(lastCalleeToken, lastToken, astUtils.isOpeningParenToken); + const prevToken = parenToken && sourceCode.getTokenBefore(parenToken, astUtils.isNotQuestionDotToken); + + // Parens in NewExpression are optional + if (!(parenToken && parenToken.range[1] < node.range[1])) { + return; + } + + checkSpacing(node, prevToken, parenToken); + }, + + ImportExpression(node) { + const leftToken = sourceCode.getFirstToken(node); + const rightToken = sourceCode.getTokenAfter(leftToken); + + checkSpacing(node, leftToken, rightToken); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/func-name-matching.js b/node_modules/eslint/lib/rules/func-name-matching.js new file mode 100644 index 0000000..b9555d6 --- /dev/null +++ b/node_modules/eslint/lib/rules/func-name-matching.js @@ -0,0 +1,253 @@ +/** + * @fileoverview Rule to require function names to match the name of the variable or property to which they are assigned. + * @author Annie Zhang, Pavel Strashkin + */ + +"use strict"; + +//-------------------------------------------------------------------------- +// Requirements +//-------------------------------------------------------------------------- + +const astUtils = require("./utils/ast-utils"); +const esutils = require("esutils"); + +//-------------------------------------------------------------------------- +// Helpers +//-------------------------------------------------------------------------- + +/** + * Determines if a pattern is `module.exports` or `module["exports"]` + * @param {ASTNode} pattern The left side of the AssignmentExpression + * @returns {boolean} True if the pattern is `module.exports` or `module["exports"]` + */ +function isModuleExports(pattern) { + if (pattern.type === "MemberExpression" && pattern.object.type === "Identifier" && pattern.object.name === "module") { + + // module.exports + if (pattern.property.type === "Identifier" && pattern.property.name === "exports") { + return true; + } + + // module["exports"] + if (pattern.property.type === "Literal" && pattern.property.value === "exports") { + return true; + } + } + return false; +} + +/** + * Determines if a string name is a valid identifier + * @param {string} name The string to be checked + * @param {int} ecmaVersion The ECMAScript version if specified in the parserOptions config + * @returns {boolean} True if the string is a valid identifier + */ +function isIdentifier(name, ecmaVersion) { + if (ecmaVersion >= 2015) { + return esutils.keyword.isIdentifierES6(name); + } + return esutils.keyword.isIdentifierES5(name); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const alwaysOrNever = { enum: ["always", "never"] }; +const optionsObject = { + type: "object", + properties: { + considerPropertyDescriptor: { + type: "boolean" + }, + includeCommonJSModuleExports: { + type: "boolean" + } + }, + additionalProperties: false +}; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require function names to match the name of the variable or property to which they are assigned", + recommended: false, + url: "https://eslint.org/docs/latest/rules/func-name-matching" + }, + + schema: { + anyOf: [{ + type: "array", + additionalItems: false, + items: [alwaysOrNever, optionsObject] + }, { + type: "array", + additionalItems: false, + items: [optionsObject] + }] + }, + + messages: { + matchProperty: "Function name `{{funcName}}` should match property name `{{name}}`.", + matchVariable: "Function name `{{funcName}}` should match variable name `{{name}}`.", + notMatchProperty: "Function name `{{funcName}}` should not match property name `{{name}}`.", + notMatchVariable: "Function name `{{funcName}}` should not match variable name `{{name}}`." + } + }, + + create(context) { + const options = (typeof context.options[0] === "object" ? context.options[0] : context.options[1]) || {}; + const nameMatches = typeof context.options[0] === "string" ? context.options[0] : "always"; + const considerPropertyDescriptor = options.considerPropertyDescriptor; + const includeModuleExports = options.includeCommonJSModuleExports; + const ecmaVersion = context.languageOptions.ecmaVersion; + + /** + * Check whether node is a certain CallExpression. + * @param {string} objName object name + * @param {string} funcName function name + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if node matches CallExpression + */ + function isPropertyCall(objName, funcName, node) { + if (!node) { + return false; + } + return node.type === "CallExpression" && astUtils.isSpecificMemberAccess(node.callee, objName, funcName); + } + + /** + * Compares identifiers based on the nameMatches option + * @param {string} x the first identifier + * @param {string} y the second identifier + * @returns {boolean} whether the two identifiers should warn. + */ + function shouldWarn(x, y) { + return (nameMatches === "always" && x !== y) || (nameMatches === "never" && x === y); + } + + /** + * Reports + * @param {ASTNode} node The node to report + * @param {string} name The variable or property name + * @param {string} funcName The function name + * @param {boolean} isProp True if the reported node is a property assignment + * @returns {void} + */ + function report(node, name, funcName, isProp) { + let messageId; + + if (nameMatches === "always" && isProp) { + messageId = "matchProperty"; + } else if (nameMatches === "always") { + messageId = "matchVariable"; + } else if (isProp) { + messageId = "notMatchProperty"; + } else { + messageId = "notMatchVariable"; + } + context.report({ + node, + messageId, + data: { + name, + funcName + } + }); + } + + /** + * Determines whether a given node is a string literal + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the node is a string literal + */ + function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclarator(node) { + if (!node.init || node.init.type !== "FunctionExpression" || node.id.type !== "Identifier") { + return; + } + if (node.init.id && shouldWarn(node.id.name, node.init.id.name)) { + report(node, node.id.name, node.init.id.name, false); + } + }, + + AssignmentExpression(node) { + if ( + node.right.type !== "FunctionExpression" || + (node.left.computed && node.left.property.type !== "Literal") || + (!includeModuleExports && isModuleExports(node.left)) || + (node.left.type !== "Identifier" && node.left.type !== "MemberExpression") + ) { + return; + } + + const isProp = node.left.type === "MemberExpression"; + const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name; + + if (node.right.id && name && isIdentifier(name) && shouldWarn(name, node.right.id.name)) { + report(node, name, node.right.id.name, isProp); + } + }, + + "Property, PropertyDefinition[value]"(node) { + if (!(node.value.type === "FunctionExpression" && node.value.id)) { + return; + } + + if (node.key.type === "Identifier" && !node.computed) { + const functionName = node.value.id.name; + let propertyName = node.key.name; + + if ( + considerPropertyDescriptor && + propertyName === "value" && + node.parent.type === "ObjectExpression" + ) { + if (isPropertyCall("Object", "defineProperty", node.parent.parent) || isPropertyCall("Reflect", "defineProperty", node.parent.parent)) { + const property = node.parent.parent.arguments[1]; + + if (isStringLiteral(property) && shouldWarn(property.value, functionName)) { + report(node, property.value, functionName, true); + } + } else if (isPropertyCall("Object", "defineProperties", node.parent.parent.parent.parent)) { + propertyName = node.parent.parent.key.name; + if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) { + report(node, propertyName, functionName, true); + } + } else if (isPropertyCall("Object", "create", node.parent.parent.parent.parent)) { + propertyName = node.parent.parent.key.name; + if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) { + report(node, propertyName, functionName, true); + } + } else if (shouldWarn(propertyName, functionName)) { + report(node, propertyName, functionName, true); + } + } else if (shouldWarn(propertyName, functionName)) { + report(node, propertyName, functionName, true); + } + return; + } + + if ( + isStringLiteral(node.key) && + isIdentifier(node.key.value, ecmaVersion) && + shouldWarn(node.key.value, node.value.id.name) + ) { + report(node, node.key.value, node.value.id.name, true); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/func-names.js b/node_modules/eslint/lib/rules/func-names.js new file mode 100644 index 0000000..b180580 --- /dev/null +++ b/node_modules/eslint/lib/rules/func-names.js @@ -0,0 +1,191 @@ +/** + * @fileoverview Rule to warn when a function expression does not have a name. + * @author Kyle T. Nunery + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +/** + * Checks whether or not a given variable is a function name. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is a function name. + */ +function isFunctionName(variable) { + return variable && variable.defs[0].type === "FunctionName"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require or disallow named `function` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/func-names" + }, + + schema: { + definitions: { + value: { + enum: [ + "always", + "as-needed", + "never" + ] + } + }, + items: [ + { + $ref: "#/definitions/value" + }, + { + type: "object", + properties: { + generators: { + $ref: "#/definitions/value" + } + }, + additionalProperties: false + } + ] + }, + + messages: { + unnamed: "Unexpected unnamed {{name}}.", + named: "Unexpected named {{name}}." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Returns the config option for the given node. + * @param {ASTNode} node A node to get the config for. + * @returns {string} The config option. + */ + function getConfigForNode(node) { + if ( + node.generator && + context.options.length > 1 && + context.options[1].generators + ) { + return context.options[1].generators; + } + + return context.options[0] || "always"; + } + + /** + * Determines whether the current FunctionExpression node is a get, set, or + * shorthand method in an object literal or a class. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is a get, set, or shorthand method. + */ + function isObjectOrClassMethod(node) { + const parent = node.parent; + + return (parent.type === "MethodDefinition" || ( + parent.type === "Property" && ( + parent.method || + parent.kind === "get" || + parent.kind === "set" + ) + )); + } + + /** + * Determines whether the current FunctionExpression node has a name that would be + * inferred from context in a conforming ES6 environment. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node would have a name assigned automatically. + */ + function hasInferredName(node) { + const parent = node.parent; + + return isObjectOrClassMethod(node) || + (parent.type === "VariableDeclarator" && parent.id.type === "Identifier" && parent.init === node) || + (parent.type === "Property" && parent.value === node) || + (parent.type === "PropertyDefinition" && parent.value === node) || + (parent.type === "AssignmentExpression" && parent.left.type === "Identifier" && parent.right === node) || + (parent.type === "AssignmentPattern" && parent.left.type === "Identifier" && parent.right === node); + } + + /** + * Reports that an unnamed function should be named + * @param {ASTNode} node The node to report in the event of an error. + * @returns {void} + */ + function reportUnexpectedUnnamedFunction(node) { + context.report({ + node, + messageId: "unnamed", + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + data: { name: astUtils.getFunctionNameWithKind(node) } + }); + } + + /** + * Reports that a named function should be unnamed + * @param {ASTNode} node The node to report in the event of an error. + * @returns {void} + */ + function reportUnexpectedNamedFunction(node) { + context.report({ + node, + messageId: "named", + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + data: { name: astUtils.getFunctionNameWithKind(node) } + }); + } + + /** + * The listener for function nodes. + * @param {ASTNode} node function node + * @returns {void} + */ + function handleFunction(node) { + + // Skip recursive functions. + const nameVar = sourceCode.getDeclaredVariables(node)[0]; + + if (isFunctionName(nameVar) && nameVar.references.length > 0) { + return; + } + + const hasName = Boolean(node.id && node.id.name); + const config = getConfigForNode(node); + + if (config === "never") { + if (hasName && node.type !== "FunctionDeclaration") { + reportUnexpectedNamedFunction(node); + } + } else if (config === "as-needed") { + if (!hasName && !hasInferredName(node)) { + reportUnexpectedUnnamedFunction(node); + } + } else { + if (!hasName && !isObjectOrClassMethod(node)) { + reportUnexpectedUnnamedFunction(node); + } + } + } + + return { + "FunctionExpression:exit": handleFunction, + "ExportDefaultDeclaration > FunctionDeclaration": handleFunction + }; + } +}; diff --git a/node_modules/eslint/lib/rules/func-style.js b/node_modules/eslint/lib/rules/func-style.js new file mode 100644 index 0000000..ab83772 --- /dev/null +++ b/node_modules/eslint/lib/rules/func-style.js @@ -0,0 +1,98 @@ +/** + * @fileoverview Rule to enforce a particular function style + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce the consistent use of either `function` declarations or expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/func-style" + }, + + schema: [ + { + enum: ["declaration", "expression"] + }, + { + type: "object", + properties: { + allowArrowFunctions: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + expression: "Expected a function expression.", + declaration: "Expected a function declaration." + } + }, + + create(context) { + + const style = context.options[0], + allowArrowFunctions = context.options[1] && context.options[1].allowArrowFunctions, + enforceDeclarations = (style === "declaration"), + stack = []; + + const nodesToCheck = { + FunctionDeclaration(node) { + stack.push(false); + + if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") { + context.report({ node, messageId: "expression" }); + } + }, + "FunctionDeclaration:exit"() { + stack.pop(); + }, + + FunctionExpression(node) { + stack.push(false); + + if (enforceDeclarations && node.parent.type === "VariableDeclarator") { + context.report({ node: node.parent, messageId: "declaration" }); + } + }, + "FunctionExpression:exit"() { + stack.pop(); + }, + + ThisExpression() { + if (stack.length > 0) { + stack[stack.length - 1] = true; + } + } + }; + + if (!allowArrowFunctions) { + nodesToCheck.ArrowFunctionExpression = function() { + stack.push(false); + }; + + nodesToCheck["ArrowFunctionExpression:exit"] = function(node) { + const hasThisExpr = stack.pop(); + + if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") { + context.report({ node: node.parent, messageId: "declaration" }); + } + }; + } + + return nodesToCheck; + + } +}; diff --git a/node_modules/eslint/lib/rules/function-call-argument-newline.js b/node_modules/eslint/lib/rules/function-call-argument-newline.js new file mode 100644 index 0000000..4462afd --- /dev/null +++ b/node_modules/eslint/lib/rules/function-call-argument-newline.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Rule to enforce line breaks between arguments of a function call + * @author Alexey Gonchar + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce line breaks between arguments of a function call", + recommended: false, + url: "https://eslint.org/docs/latest/rules/function-call-argument-newline" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never", "consistent"] + } + ], + + messages: { + unexpectedLineBreak: "There should be no line break here.", + missingLineBreak: "There should be a line break after this argument." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + const checkers = { + unexpected: { + messageId: "unexpectedLineBreak", + check: (prevToken, currentToken) => prevToken.loc.end.line !== currentToken.loc.start.line, + createFix: (token, tokenBefore) => fixer => + fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " ") + }, + missing: { + messageId: "missingLineBreak", + check: (prevToken, currentToken) => prevToken.loc.end.line === currentToken.loc.start.line, + createFix: (token, tokenBefore) => fixer => + fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n") + } + }; + + /** + * Check all arguments for line breaks in the CallExpression + * @param {CallExpression} node node to evaluate + * @param {{ messageId: string, check: Function }} checker selected checker + * @returns {void} + * @private + */ + function checkArguments(node, checker) { + for (let i = 1; i < node.arguments.length; i++) { + const prevArgToken = sourceCode.getLastToken(node.arguments[i - 1]); + const currentArgToken = sourceCode.getFirstToken(node.arguments[i]); + + if (checker.check(prevArgToken, currentArgToken)) { + const tokenBefore = sourceCode.getTokenBefore( + currentArgToken, + { includeComments: true } + ); + + const hasLineCommentBefore = tokenBefore.type === "Line"; + + context.report({ + node, + loc: { + start: tokenBefore.loc.end, + end: currentArgToken.loc.start + }, + messageId: checker.messageId, + fix: hasLineCommentBefore ? null : checker.createFix(currentArgToken, tokenBefore) + }); + } + } + } + + /** + * Check if open space is present in a function name + * @param {CallExpression} node node to evaluate + * @returns {void} + * @private + */ + function check(node) { + if (node.arguments.length < 2) { + return; + } + + const option = context.options[0] || "always"; + + if (option === "never") { + checkArguments(node, checkers.unexpected); + } else if (option === "always") { + checkArguments(node, checkers.missing); + } else if (option === "consistent") { + const firstArgToken = sourceCode.getLastToken(node.arguments[0]); + const secondArgToken = sourceCode.getFirstToken(node.arguments[1]); + + if (firstArgToken.loc.end.line === secondArgToken.loc.start.line) { + checkArguments(node, checkers.unexpected); + } else { + checkArguments(node, checkers.missing); + } + } + } + + return { + CallExpression: check, + NewExpression: check + }; + } +}; diff --git a/node_modules/eslint/lib/rules/function-paren-newline.js b/node_modules/eslint/lib/rules/function-paren-newline.js new file mode 100644 index 0000000..8a8714a --- /dev/null +++ b/node_modules/eslint/lib/rules/function-paren-newline.js @@ -0,0 +1,289 @@ +/** + * @fileoverview enforce consistent line breaks inside function parentheses + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent line breaks inside function parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/function-paren-newline" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never", "consistent", "multiline", "multiline-arguments"] + }, + { + type: "object", + properties: { + minItems: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + expectedBefore: "Expected newline before ')'.", + expectedAfter: "Expected newline after '('.", + expectedBetween: "Expected newline between arguments/params.", + unexpectedBefore: "Unexpected newline before ')'.", + unexpectedAfter: "Unexpected newline after '('." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const rawOption = context.options[0] || "multiline"; + const multilineOption = rawOption === "multiline"; + const multilineArgumentsOption = rawOption === "multiline-arguments"; + const consistentOption = rawOption === "consistent"; + let minItems; + + if (typeof rawOption === "object") { + minItems = rawOption.minItems; + } else if (rawOption === "always") { + minItems = 0; + } else if (rawOption === "never") { + minItems = Infinity; + } else { + minItems = null; + } + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Determines whether there should be newlines inside function parens + * @param {ASTNode[]} elements The arguments or parameters in the list + * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code. + * @returns {boolean} `true` if there should be newlines inside the function parens + */ + function shouldHaveNewlines(elements, hasLeftNewline) { + if (multilineArgumentsOption && elements.length === 1) { + return hasLeftNewline; + } + if (multilineOption || multilineArgumentsOption) { + return elements.some((element, index) => index !== elements.length - 1 && element.loc.end.line !== elements[index + 1].loc.start.line); + } + if (consistentOption) { + return hasLeftNewline; + } + return elements.length >= minItems; + } + + /** + * Validates parens + * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token + * @param {ASTNode[]} elements The arguments or parameters in the list + * @returns {void} + */ + function validateParens(parens, elements) { + const leftParen = parens.leftParen; + const rightParen = parens.rightParen; + const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); + const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen); + const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen); + const hasRightNewline = !astUtils.isTokenOnSameLine(tokenBeforeRightParen, rightParen); + const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); + + if (hasLeftNewline && !needsNewlines) { + context.report({ + node: leftParen, + messageId: "unexpectedAfter", + fix(fixer) { + return sourceCode.getText().slice(leftParen.range[1], tokenAfterLeftParen.range[0]).trim() + + // If there is a comment between the ( and the first element, don't do a fix. + ? null + : fixer.removeRange([leftParen.range[1], tokenAfterLeftParen.range[0]]); + } + }); + } else if (!hasLeftNewline && needsNewlines) { + context.report({ + node: leftParen, + messageId: "expectedAfter", + fix: fixer => fixer.insertTextAfter(leftParen, "\n") + }); + } + + if (hasRightNewline && !needsNewlines) { + context.report({ + node: rightParen, + messageId: "unexpectedBefore", + fix(fixer) { + return sourceCode.getText().slice(tokenBeforeRightParen.range[1], rightParen.range[0]).trim() + + // If there is a comment between the last element and the ), don't do a fix. + ? null + : fixer.removeRange([tokenBeforeRightParen.range[1], rightParen.range[0]]); + } + }); + } else if (!hasRightNewline && needsNewlines) { + context.report({ + node: rightParen, + messageId: "expectedBefore", + fix: fixer => fixer.insertTextBefore(rightParen, "\n") + }); + } + } + + /** + * Validates a list of arguments or parameters + * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token + * @param {ASTNode[]} elements The arguments or parameters in the list + * @returns {void} + */ + function validateArguments(parens, elements) { + const leftParen = parens.leftParen; + const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); + const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen); + const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); + + for (let i = 0; i <= elements.length - 2; i++) { + const currentElement = elements[i]; + const nextElement = elements[i + 1]; + const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line; + + if (!hasNewLine && needsNewlines) { + context.report({ + node: currentElement, + messageId: "expectedBetween", + fix: fixer => fixer.insertTextBefore(nextElement, "\n") + }); + } + } + } + + /** + * Gets the left paren and right paren tokens of a node. + * @param {ASTNode} node The node with parens + * @throws {TypeError} Unexpected node type. + * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token. + * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression + * with a single parameter) + */ + function getParenTokens(node) { + switch (node.type) { + case "NewExpression": + if (!node.arguments.length && + !( + astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) && + astUtils.isClosingParenToken(sourceCode.getLastToken(node)) && + node.callee.range[1] < node.range[1] + ) + ) { + + // If the NewExpression does not have parens (e.g. `new Foo`), return null. + return null; + } + + // falls through + + case "CallExpression": + return { + leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken), + rightParen: sourceCode.getLastToken(node) + }; + + case "FunctionDeclaration": + case "FunctionExpression": { + const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken); + const rightParen = node.params.length + ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken) + : sourceCode.getTokenAfter(leftParen); + + return { leftParen, rightParen }; + } + + case "ArrowFunctionExpression": { + const firstToken = sourceCode.getFirstToken(node, { skip: (node.async ? 1 : 0) }); + + if (!astUtils.isOpeningParenToken(firstToken)) { + + // If the ArrowFunctionExpression has a single param without parens, return null. + return null; + } + + const rightParen = node.params.length + ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken) + : sourceCode.getTokenAfter(firstToken); + + return { + leftParen: firstToken, + rightParen + }; + } + + case "ImportExpression": { + const leftParen = sourceCode.getFirstToken(node, 1); + const rightParen = sourceCode.getLastToken(node); + + return { leftParen, rightParen }; + } + + default: + throw new TypeError(`unexpected node with type ${node.type}`); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + [[ + "ArrowFunctionExpression", + "CallExpression", + "FunctionDeclaration", + "FunctionExpression", + "ImportExpression", + "NewExpression" + ]](node) { + const parens = getParenTokens(node); + let params; + + if (node.type === "ImportExpression") { + params = [node.source]; + } else if (astUtils.isFunction(node)) { + params = node.params; + } else { + params = node.arguments; + } + + if (parens) { + validateParens(parens, params); + + if (multilineArgumentsOption) { + validateArguments(parens, params); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/generator-star-spacing.js b/node_modules/eslint/lib/rules/generator-star-spacing.js new file mode 100644 index 0000000..81c0b61 --- /dev/null +++ b/node_modules/eslint/lib/rules/generator-star-spacing.js @@ -0,0 +1,206 @@ +/** + * @fileoverview Rule to check the spacing around the * in generator functions. + * @author Jamund Ferguson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const OVERRIDE_SCHEMA = { + oneOf: [ + { + enum: ["before", "after", "both", "neither"] + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" } + }, + additionalProperties: false + } + ] +}; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing around `*` operators in generator functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/generator-star-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["before", "after", "both", "neither"] + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + named: OVERRIDE_SCHEMA, + anonymous: OVERRIDE_SCHEMA, + method: OVERRIDE_SCHEMA + }, + additionalProperties: false + } + ] + } + ], + + messages: { + missingBefore: "Missing space before *.", + missingAfter: "Missing space after *.", + unexpectedBefore: "Unexpected space before *.", + unexpectedAfter: "Unexpected space after *." + } + }, + + create(context) { + + const optionDefinitions = { + before: { before: true, after: false }, + after: { before: false, after: true }, + both: { before: true, after: true }, + neither: { before: false, after: false } + }; + + /** + * Returns resolved option definitions based on an option and defaults + * @param {any} option The option object or string value + * @param {Object} defaults The defaults to use if options are not present + * @returns {Object} the resolved object definition + */ + function optionToDefinition(option, defaults) { + if (!option) { + return defaults; + } + + return typeof option === "string" + ? optionDefinitions[option] + : Object.assign({}, defaults, option); + } + + const modes = (function(option) { + const defaults = optionToDefinition(option, optionDefinitions.before); + + return { + named: optionToDefinition(option.named, defaults), + anonymous: optionToDefinition(option.anonymous, defaults), + method: optionToDefinition(option.method, defaults) + }; + }(context.options[0] || {})); + + const sourceCode = context.sourceCode; + + /** + * Checks if the given token is a star token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a star token. + */ + function isStarToken(token) { + return token.value === "*" && token.type === "Punctuator"; + } + + /** + * Gets the generator star token of the given function node. + * @param {ASTNode} node The function node to get. + * @returns {Token} Found star token. + */ + function getStarToken(node) { + return sourceCode.getFirstToken( + (node.parent.method || node.parent.type === "MethodDefinition") ? node.parent : node, + isStarToken + ); + } + + /** + * capitalize a given string. + * @param {string} str the given string. + * @returns {string} the capitalized string. + */ + function capitalize(str) { + return str[0].toUpperCase() + str.slice(1); + } + + /** + * Checks the spacing between two tokens before or after the star token. + * @param {string} kind Either "named", "anonymous", or "method" + * @param {string} side Either "before" or "after". + * @param {Token} leftToken `function` keyword token if side is "before", or + * star token if side is "after". + * @param {Token} rightToken Star token if side is "before", or identifier + * token if side is "after". + * @returns {void} + */ + function checkSpacing(kind, side, leftToken, rightToken) { + if (!!(rightToken.range[0] - leftToken.range[1]) !== modes[kind][side]) { + const after = leftToken.value === "*"; + const spaceRequired = modes[kind][side]; + const node = after ? leftToken : rightToken; + const messageId = `${spaceRequired ? "missing" : "unexpected"}${capitalize(side)}`; + + context.report({ + node, + messageId, + fix(fixer) { + if (spaceRequired) { + if (after) { + return fixer.insertTextAfter(node, " "); + } + return fixer.insertTextBefore(node, " "); + } + return fixer.removeRange([leftToken.range[1], rightToken.range[0]]); + } + }); + } + } + + /** + * Enforces the spacing around the star if node is a generator function. + * @param {ASTNode} node A function expression or declaration node. + * @returns {void} + */ + function checkFunction(node) { + if (!node.generator) { + return; + } + + const starToken = getStarToken(node); + const prevToken = sourceCode.getTokenBefore(starToken); + const nextToken = sourceCode.getTokenAfter(starToken); + + let kind = "named"; + + if (node.parent.type === "MethodDefinition" || (node.parent.type === "Property" && node.parent.method)) { + kind = "method"; + } else if (!node.id) { + kind = "anonymous"; + } + + // Only check before when preceded by `function`|`static` keyword + if (!(kind === "method" && starToken === sourceCode.getFirstToken(node.parent))) { + checkSpacing(kind, "before", prevToken, starToken); + } + + checkSpacing(kind, "after", starToken, nextToken); + } + + return { + FunctionDeclaration: checkFunction, + FunctionExpression: checkFunction + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/getter-return.js b/node_modules/eslint/lib/rules/getter-return.js new file mode 100644 index 0000000..622b6a7 --- /dev/null +++ b/node_modules/eslint/lib/rules/getter-return.js @@ -0,0 +1,179 @@ +/** + * @fileoverview Enforces that a return statement is present in property getters. + * @author Aladdin-ADD(hh_2013@foxmail.com) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ +const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u; + +/** + * Checks a given code path segment is reachable. + * @param {CodePathSegment} segment A segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Enforce `return` statements in getters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/getter-return" + }, + + fixable: null, + + schema: [ + { + type: "object", + properties: { + allowImplicit: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + expected: "Expected to return a value in {{name}}.", + expectedAlways: "Expected {{name}} to always return a value." + } + }, + + create(context) { + + const options = context.options[0] || { allowImplicit: false }; + const sourceCode = context.sourceCode; + + let funcInfo = { + upper: null, + codePath: null, + hasReturn: false, + shouldCheck: false, + node: null + }; + + /** + * Checks whether or not the last code path segment is reachable. + * Then reports this function if the segment is reachable. + * + * If the last code path segment is reachable, there are paths which are not + * returned or thrown. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkLastSegment(node) { + if (funcInfo.shouldCheck && + funcInfo.codePath.currentSegments.some(isReachable) + ) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: funcInfo.hasReturn ? "expectedAlways" : "expected", + data: { + name: astUtils.getFunctionNameWithKind(funcInfo.node) + } + }); + } + } + + /** + * Checks whether a node means a getter function. + * @param {ASTNode} node a node to check. + * @returns {boolean} if node means a getter, return true; else return false. + */ + function isGetter(node) { + const parent = node.parent; + + if (TARGET_NODE_TYPE.test(node.type) && node.body.type === "BlockStatement") { + if (parent.kind === "get") { + return true; + } + if (parent.type === "Property" && astUtils.getStaticPropertyName(parent) === "get" && parent.parent.type === "ObjectExpression") { + + // Object.defineProperty() or Reflect.defineProperty() + if (parent.parent.parent.type === "CallExpression") { + const callNode = parent.parent.parent.callee; + + if (astUtils.isSpecificMemberAccess(callNode, "Object", "defineProperty") || + astUtils.isSpecificMemberAccess(callNode, "Reflect", "defineProperty")) { + return true; + } + } + + // Object.defineProperties() or Object.create() + if (parent.parent.parent.type === "Property" && + parent.parent.parent.parent.type === "ObjectExpression" && + parent.parent.parent.parent.parent.type === "CallExpression") { + const callNode = parent.parent.parent.parent.parent.callee; + + return astUtils.isSpecificMemberAccess(callNode, "Object", "defineProperties") || + astUtils.isSpecificMemberAccess(callNode, "Object", "create"); + } + } + } + return false; + } + return { + + // Stacks this function's information. + onCodePathStart(codePath, node) { + funcInfo = { + upper: funcInfo, + codePath, + hasReturn: false, + shouldCheck: isGetter(node), + node + }; + }, + + // Pops this function's information. + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + // Checks the return statement is valid. + ReturnStatement(node) { + if (funcInfo.shouldCheck) { + funcInfo.hasReturn = true; + + // if allowImplicit: false, should also check node.argument + if (!options.allowImplicit && !node.argument) { + context.report({ + node, + messageId: "expected", + data: { + name: astUtils.getFunctionNameWithKind(funcInfo.node) + } + }); + } + } + }, + + // Reports a given function if the last path is reachable. + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment + }; + } +}; diff --git a/node_modules/eslint/lib/rules/global-require.js b/node_modules/eslint/lib/rules/global-require.js new file mode 100644 index 0000000..deae9d2 --- /dev/null +++ b/node_modules/eslint/lib/rules/global-require.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Rule for disallowing require() outside of the top-level module context + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +const ACCEPTABLE_PARENTS = new Set([ + "AssignmentExpression", + "VariableDeclarator", + "MemberExpression", + "ExpressionStatement", + "CallExpression", + "ConditionalExpression", + "Program", + "VariableDeclaration", + "ChainExpression" +]); + +/** + * Finds the eslint-scope reference in the given scope. + * @param {Object} scope The scope to search. + * @param {ASTNode} node The identifier node. + * @returns {Reference|null} Returns the found reference or null if none were found. + */ +function findReference(scope, node) { + const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1]); + + if (references.length === 1) { + return references[0]; + } + + /* c8 ignore next */ + return null; + +} + +/** + * Checks if the given identifier node is shadowed in the given scope. + * @param {Object} scope The current scope. + * @param {ASTNode} node The identifier node to check. + * @returns {boolean} Whether or not the name is shadowed. + */ +function isShadowed(scope, node) { + const reference = findReference(scope, node); + + return reference && reference.resolved && reference.resolved.defs.length > 0; +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Require `require()` calls to be placed at top-level module scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/global-require" + }, + + schema: [], + messages: { + unexpected: "Unexpected require()." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + const currentScope = sourceCode.getScope(node); + + if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) { + const isGoodRequire = sourceCode.getAncestors(node).every(parent => ACCEPTABLE_PARENTS.has(parent.type)); + + if (!isGoodRequire) { + context.report({ node, messageId: "unexpected" }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/grouped-accessor-pairs.js b/node_modules/eslint/lib/rules/grouped-accessor-pairs.js new file mode 100644 index 0000000..9556f47 --- /dev/null +++ b/node_modules/eslint/lib/rules/grouped-accessor-pairs.js @@ -0,0 +1,215 @@ +/** + * @fileoverview Rule to require grouped accessor pairs in object literals and classes + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * Property name if it can be computed statically, otherwise the list of the tokens of the key node. + * @typedef {string|Token[]} Key + */ + +/** + * Accessor nodes with the same key. + * @typedef {Object} AccessorData + * @property {Key} key Accessor's key + * @property {ASTNode[]} getters List of getter nodes. + * @property {ASTNode[]} setters List of setter nodes. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not the given lists represent the equal tokens in the same order. + * Tokens are compared by their properties, not by instance. + * @param {Token[]} left First list of tokens. + * @param {Token[]} right Second list of tokens. + * @returns {boolean} `true` if the lists have same tokens. + */ +function areEqualTokenLists(left, right) { + if (left.length !== right.length) { + return false; + } + + for (let i = 0; i < left.length; i++) { + const leftToken = left[i], + rightToken = right[i]; + + if (leftToken.type !== rightToken.type || leftToken.value !== rightToken.value) { + return false; + } + } + + return true; +} + +/** + * Checks whether or not the given keys are equal. + * @param {Key} left First key. + * @param {Key} right Second key. + * @returns {boolean} `true` if the keys are equal. + */ +function areEqualKeys(left, right) { + if (typeof left === "string" && typeof right === "string") { + + // Statically computed names. + return left === right; + } + if (Array.isArray(left) && Array.isArray(right)) { + + // Token lists. + return areEqualTokenLists(left, right); + } + + return false; +} + +/** + * Checks whether or not a given node is of an accessor kind ('get' or 'set'). + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is of an accessor kind. + */ +function isAccessorKind(node) { + return node.kind === "get" || node.kind === "set"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require grouped accessor pairs in object literals and classes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/grouped-accessor-pairs" + }, + + schema: [ + { + enum: ["anyOrder", "getBeforeSet", "setBeforeGet"] + } + ], + + messages: { + notGrouped: "Accessor pair {{ formerName }} and {{ latterName }} should be grouped.", + invalidOrder: "Expected {{ latterName }} to be before {{ formerName }}." + } + }, + + create(context) { + const order = context.options[0] || "anyOrder"; + const sourceCode = context.sourceCode; + + /** + * Reports the given accessor pair. + * @param {string} messageId messageId to report. + * @param {ASTNode} formerNode getter/setter node that is defined before `latterNode`. + * @param {ASTNode} latterNode getter/setter node that is defined after `formerNode`. + * @returns {void} + * @private + */ + function report(messageId, formerNode, latterNode) { + context.report({ + node: latterNode, + messageId, + loc: astUtils.getFunctionHeadLoc(latterNode.value, sourceCode), + data: { + formerName: astUtils.getFunctionNameWithKind(formerNode.value), + latterName: astUtils.getFunctionNameWithKind(latterNode.value) + } + }); + } + + /** + * Checks accessor pairs in the given list of nodes. + * @param {ASTNode[]} nodes The list to check. + * @param {Function} shouldCheck – Predicate that returns `true` if the node should be checked. + * @returns {void} + * @private + */ + function checkList(nodes, shouldCheck) { + const accessors = []; + let found = false; + + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + + if (shouldCheck(node) && isAccessorKind(node)) { + + // Creates a new `AccessorData` object for the given getter or setter node. + const name = astUtils.getStaticPropertyName(node); + const key = (name !== null) ? name : sourceCode.getTokens(node.key); + + // Merges the given `AccessorData` object into the given accessors list. + for (let j = 0; j < accessors.length; j++) { + const accessor = accessors[j]; + + if (areEqualKeys(accessor.key, key)) { + accessor.getters.push(...node.kind === "get" ? [node] : []); + accessor.setters.push(...node.kind === "set" ? [node] : []); + found = true; + break; + } + } + if (!found) { + accessors.push({ + key, + getters: node.kind === "get" ? [node] : [], + setters: node.kind === "set" ? [node] : [] + }); + } + found = false; + } + } + + for (const { getters, setters } of accessors) { + + // Don't report accessor properties that have duplicate getters or setters. + if (getters.length === 1 && setters.length === 1) { + const [getter] = getters, + [setter] = setters, + getterIndex = nodes.indexOf(getter), + setterIndex = nodes.indexOf(setter), + formerNode = getterIndex < setterIndex ? getter : setter, + latterNode = getterIndex < setterIndex ? setter : getter; + + if (Math.abs(getterIndex - setterIndex) > 1) { + report("notGrouped", formerNode, latterNode); + } else if ( + (order === "getBeforeSet" && getterIndex > setterIndex) || + (order === "setBeforeGet" && getterIndex < setterIndex) + ) { + report("invalidOrder", formerNode, latterNode); + } + } + } + } + + return { + ObjectExpression(node) { + checkList(node.properties, n => n.type === "Property"); + }, + ClassBody(node) { + checkList(node.body, n => n.type === "MethodDefinition" && !n.static); + checkList(node.body, n => n.type === "MethodDefinition" && n.static); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/guard-for-in.js b/node_modules/eslint/lib/rules/guard-for-in.js new file mode 100644 index 0000000..d6e70d0 --- /dev/null +++ b/node_modules/eslint/lib/rules/guard-for-in.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Rule to flag for-in loops without if statements inside + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `for-in` loops to include an `if` statement", + recommended: false, + url: "https://eslint.org/docs/latest/rules/guard-for-in" + }, + + schema: [], + messages: { + wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." + } + }, + + create(context) { + + return { + + ForInStatement(node) { + const body = node.body; + + // empty statement + if (body.type === "EmptyStatement") { + return; + } + + // if statement + if (body.type === "IfStatement") { + return; + } + + // empty block + if (body.type === "BlockStatement" && body.body.length === 0) { + return; + } + + // block with just if statement + if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") { + return; + } + + // block that starts with if statement + if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") { + const i = body.body[0]; + + // ... whose consequent is a continue + if (i.consequent.type === "ContinueStatement") { + return; + } + + // ... whose consequent is a block that contains only a continue + if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") { + return; + } + } + + context.report({ node, messageId: "wrap" }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/handle-callback-err.js b/node_modules/eslint/lib/rules/handle-callback-err.js new file mode 100644 index 0000000..ad84931 --- /dev/null +++ b/node_modules/eslint/lib/rules/handle-callback-err.js @@ -0,0 +1,101 @@ +/** + * @fileoverview Ensure handling of errors when we know they exist. + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Require error handling in callbacks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/handle-callback-err" + }, + + schema: [ + { + type: "string" + } + ], + messages: { + expected: "Expected error to be handled." + } + }, + + create(context) { + + const errorArgument = context.options[0] || "err"; + const sourceCode = context.sourceCode; + + /** + * Checks if the given argument should be interpreted as a regexp pattern. + * @param {string} stringToCheck The string which should be checked. + * @returns {boolean} Whether or not the string should be interpreted as a pattern. + */ + function isPattern(stringToCheck) { + const firstChar = stringToCheck[0]; + + return firstChar === "^"; + } + + /** + * Checks if the given name matches the configured error argument. + * @param {string} name The name which should be compared. + * @returns {boolean} Whether or not the given name matches the configured error variable name. + */ + function matchesConfiguredErrorName(name) { + if (isPattern(errorArgument)) { + const regexp = new RegExp(errorArgument, "u"); + + return regexp.test(name); + } + return name === errorArgument; + } + + /** + * Get the parameters of a given function scope. + * @param {Object} scope The function scope. + * @returns {Array} All parameters of the given scope. + */ + function getParameters(scope) { + return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter"); + } + + /** + * Check to see if we're handling the error object properly. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function checkForError(node) { + const scope = sourceCode.getScope(node), + parameters = getParameters(scope), + firstParameter = parameters[0]; + + if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) { + if (firstParameter.references.length === 0) { + context.report({ node, messageId: "expected" }); + } + } + } + + return { + FunctionDeclaration: checkForError, + FunctionExpression: checkForError, + ArrowFunctionExpression: checkForError + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/id-blacklist.js b/node_modules/eslint/lib/rules/id-blacklist.js new file mode 100644 index 0000000..6b7f561 --- /dev/null +++ b/node_modules/eslint/lib/rules/id-blacklist.js @@ -0,0 +1,246 @@ +/** + * @fileoverview Rule that warns when identifier names that are + * specified in the configuration are used. + * @author Keith Cirkel (http://keithcirkel.co.uk) + * @deprecated in ESLint v7.5.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents assignment target in a normal assignment or destructuring. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is assignment target. + */ +function isAssignmentTarget(node) { + const parent = node.parent; + + return ( + + // normal assignment + ( + parent.type === "AssignmentExpression" && + parent.left === node + ) || + + // destructuring + parent.type === "ArrayPattern" || + parent.type === "RestElement" || + ( + parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern" + ) || + ( + parent.type === "AssignmentPattern" && + parent.left === node + ) + ); +} + +/** + * Checks whether the given node represents an imported name that is renamed in the same import/export specifier. + * + * Examples: + * import { a as b } from 'mod'; // node `a` is renamed import + * export { a as b } from 'mod'; // node `a` is renamed import + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed import. + */ +function isRenamedImport(node) { + const parent = node.parent; + + return ( + ( + parent.type === "ImportSpecifier" && + parent.imported !== parent.local && + parent.imported === node + ) || + ( + parent.type === "ExportSpecifier" && + parent.parent.source && // re-export + parent.local !== parent.exported && + parent.local === node + ) + ); +} + +/** + * Checks whether the given node is a renamed identifier node in an ObjectPattern destructuring. + * + * Examples: + * const { a : b } = foo; // node `a` is renamed node. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed node in an ObjectPattern destructuring. + */ +function isRenamedInDestructuring(node) { + const parent = node.parent; + + return ( + ( + !parent.computed && + parent.type === "Property" && + parent.parent.type === "ObjectPattern" && + parent.value !== node && + parent.key === node + ) + ); +} + +/** + * Checks whether the given node represents shorthand definition of a property in an object literal. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a shorthand property definition. + */ +function isShorthandPropertyDefinition(node) { + const parent = node.parent; + + return ( + parent.type === "Property" && + parent.parent.type === "ObjectExpression" && + parent.shorthand + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + replacedBy: ["id-denylist"], + + type: "suggestion", + + docs: { + description: "Disallow specified identifiers", + recommended: false, + url: "https://eslint.org/docs/latest/rules/id-blacklist" + }, + + schema: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + }, + messages: { + restricted: "Identifier '{{name}}' is restricted." + } + }, + + create(context) { + + const denyList = new Set(context.options); + const reportedNodes = new Set(); + const sourceCode = context.sourceCode; + + let globalScope; + + /** + * Checks whether the given name is restricted. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is restricted. + * @private + */ + function isRestricted(name) { + return denyList.has(name); + } + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return variable && variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node); + } + + /** + * Determines whether the given node should be checked. + * @param {ASTNode} node `Identifier` node. + * @returns {boolean} `true` if the node should be checked. + */ + function shouldCheck(node) { + const parent = node.parent; + + /* + * Member access has special rules for checking property names. + * Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over. + * Write access isn't allowed, because it potentially creates a new property with a restricted name. + */ + if ( + parent.type === "MemberExpression" && + parent.property === node && + !parent.computed + ) { + return isAssignmentTarget(parent); + } + + return ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" && + !isRenamedImport(node) && + !isRenamedInDestructuring(node) && + !( + isReferenceToGlobalVariable(node) && + !isShorthandPropertyDefinition(node) + ) + ); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + context.report({ + node, + messageId: "restricted", + data: { + name: node.name + } + }); + reportedNodes.add(node.range.toString()); + } + + } + + return { + + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + Identifier(node) { + if (isRestricted(node.name) && shouldCheck(node)) { + report(node); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/id-denylist.js b/node_modules/eslint/lib/rules/id-denylist.js new file mode 100644 index 0000000..baaa65f --- /dev/null +++ b/node_modules/eslint/lib/rules/id-denylist.js @@ -0,0 +1,228 @@ +/** + * @fileoverview Rule that warns when identifier names that are + * specified in the configuration are used. + * @author Keith Cirkel (http://keithcirkel.co.uk) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents assignment target in a normal assignment or destructuring. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is assignment target. + */ +function isAssignmentTarget(node) { + const parent = node.parent; + + return ( + + // normal assignment + ( + parent.type === "AssignmentExpression" && + parent.left === node + ) || + + // destructuring + parent.type === "ArrayPattern" || + parent.type === "RestElement" || + ( + parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern" + ) || + ( + parent.type === "AssignmentPattern" && + parent.left === node + ) + ); +} + +/** + * Checks whether the given node represents an imported name that is renamed in the same import/export specifier. + * + * Examples: + * import { a as b } from 'mod'; // node `a` is renamed import + * export { a as b } from 'mod'; // node `a` is renamed import + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed import. + */ +function isRenamedImport(node) { + const parent = node.parent; + + return ( + ( + parent.type === "ImportSpecifier" && + parent.imported !== parent.local && + parent.imported === node + ) || + ( + parent.type === "ExportSpecifier" && + parent.parent.source && // re-export + parent.local !== parent.exported && + parent.local === node + ) + ); +} + +/** + * Checks whether the given node is an ObjectPattern destructuring. + * + * Examples: + * const { a : b } = foo; + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is in an ObjectPattern destructuring. + */ +function isPropertyNameInDestructuring(node) { + const parent = node.parent; + + return ( + ( + !parent.computed && + parent.type === "Property" && + parent.parent.type === "ObjectPattern" && + parent.key === node + ) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified identifiers", + recommended: false, + url: "https://eslint.org/docs/latest/rules/id-denylist" + }, + + schema: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + }, + messages: { + restricted: "Identifier '{{name}}' is restricted.", + restrictedPrivate: "Identifier '#{{name}}' is restricted." + } + }, + + create(context) { + + const denyList = new Set(context.options); + const reportedNodes = new Set(); + const sourceCode = context.sourceCode; + + let globalScope; + + /** + * Checks whether the given name is restricted. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is restricted. + * @private + */ + function isRestricted(name) { + return denyList.has(name); + } + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return variable && variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node); + } + + /** + * Determines whether the given node should be checked. + * @param {ASTNode} node `Identifier` node. + * @returns {boolean} `true` if the node should be checked. + */ + function shouldCheck(node) { + const parent = node.parent; + + /* + * Member access has special rules for checking property names. + * Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over. + * Write access isn't allowed, because it potentially creates a new property with a restricted name. + */ + if ( + parent.type === "MemberExpression" && + parent.property === node && + !parent.computed + ) { + return isAssignmentTarget(parent); + } + + return ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" && + !isRenamedImport(node) && + !isPropertyNameInDestructuring(node) && + !isReferenceToGlobalVariable(node) + ); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + const isPrivate = node.type === "PrivateIdentifier"; + + context.report({ + node, + messageId: isPrivate ? "restrictedPrivate" : "restricted", + data: { + name: node.name + } + }); + reportedNodes.add(node.range.toString()); + } + } + + return { + + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + [[ + "Identifier", + "PrivateIdentifier" + ]](node) { + if (isRestricted(node.name) && shouldCheck(node)) { + report(node); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/id-length.js b/node_modules/eslint/lib/rules/id-length.js new file mode 100644 index 0000000..97bc0e4 --- /dev/null +++ b/node_modules/eslint/lib/rules/id-length.js @@ -0,0 +1,177 @@ +/** + * @fileoverview Rule that warns when identifier names are shorter or longer + * than the values provided in configuration. + * @author Burak Yigit Kaya aka BYK + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getGraphemeCount } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce minimum and maximum identifier lengths", + recommended: false, + url: "https://eslint.org/docs/latest/rules/id-length" + }, + + schema: [ + { + type: "object", + properties: { + min: { + type: "integer", + default: 2 + }, + max: { + type: "integer" + }, + exceptions: { + type: "array", + uniqueItems: true, + items: { + type: "string" + } + }, + exceptionPatterns: { + type: "array", + uniqueItems: true, + items: { + type: "string" + } + }, + properties: { + enum: ["always", "never"] + } + }, + additionalProperties: false + } + ], + messages: { + tooShort: "Identifier name '{{name}}' is too short (< {{min}}).", + tooShortPrivate: "Identifier name '#{{name}}' is too short (< {{min}}).", + tooLong: "Identifier name '{{name}}' is too long (> {{max}}).", + tooLongPrivate: "Identifier name #'{{name}}' is too long (> {{max}})." + } + }, + + create(context) { + const options = context.options[0] || {}; + const minLength = typeof options.min !== "undefined" ? options.min : 2; + const maxLength = typeof options.max !== "undefined" ? options.max : Infinity; + const properties = options.properties !== "never"; + const exceptions = new Set(options.exceptions); + const exceptionPatterns = (options.exceptionPatterns || []).map(pattern => new RegExp(pattern, "u")); + const reportedNodes = new Set(); + + /** + * Checks if a string matches the provided exception patterns + * @param {string} name The string to check. + * @returns {boolean} if the string is a match + * @private + */ + function matchesExceptionPattern(name) { + return exceptionPatterns.some(pattern => pattern.test(name)); + } + + const SUPPORTED_EXPRESSIONS = { + MemberExpression: properties && function(parent) { + return !parent.computed && ( + + // regular property assignment + (parent.parent.left === parent && parent.parent.type === "AssignmentExpression" || + + // or the last identifier in an ObjectPattern destructuring + parent.parent.type === "Property" && parent.parent.value === parent && + parent.parent.parent.type === "ObjectPattern" && parent.parent.parent.parent.left === parent.parent.parent) + ); + }, + AssignmentPattern(parent, node) { + return parent.left === node; + }, + VariableDeclarator(parent, node) { + return parent.id === node; + }, + Property(parent, node) { + + if (parent.parent.type === "ObjectPattern") { + const isKeyAndValueSame = parent.value.name === parent.key.name; + + return ( + !isKeyAndValueSame && parent.value === node || + isKeyAndValueSame && parent.key === node && properties + ); + } + return properties && !parent.computed && parent.key.name === node.name; + }, + ImportDefaultSpecifier: true, + RestElement: true, + FunctionExpression: true, + ArrowFunctionExpression: true, + ClassDeclaration: true, + FunctionDeclaration: true, + MethodDefinition: true, + PropertyDefinition: true, + CatchClause: true, + ArrayPattern: true + }; + + return { + [[ + "Identifier", + "PrivateIdentifier" + ]](node) { + const name = node.name; + const parent = node.parent; + + const nameLength = getGraphemeCount(name); + + const isShort = nameLength < minLength; + const isLong = nameLength > maxLength; + + if (!(isShort || isLong) || exceptions.has(name) || matchesExceptionPattern(name)) { + return; // Nothing to report + } + + const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type]; + + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (isValidExpression && !reportedNodes.has(node.range.toString()) && (isValidExpression === true || isValidExpression(parent, node))) { + reportedNodes.add(node.range.toString()); + + let messageId = isShort ? "tooShort" : "tooLong"; + + if (node.type === "PrivateIdentifier") { + messageId += "Private"; + } + + context.report({ + node, + messageId, + data: { name, min: minLength, max: maxLength } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/id-match.js b/node_modules/eslint/lib/rules/id-match.js new file mode 100644 index 0000000..e225454 --- /dev/null +++ b/node_modules/eslint/lib/rules/id-match.js @@ -0,0 +1,299 @@ +/** + * @fileoverview Rule to flag non-matching identifiers + * @author Matthieu Larcher + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require identifiers to match a specified regular expression", + recommended: false, + url: "https://eslint.org/docs/latest/rules/id-match" + }, + + schema: [ + { + type: "string" + }, + { + type: "object", + properties: { + properties: { + type: "boolean", + default: false + }, + classFields: { + type: "boolean", + default: false + }, + onlyDeclarations: { + type: "boolean", + default: false + }, + ignoreDestructuring: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + messages: { + notMatch: "Identifier '{{name}}' does not match the pattern '{{pattern}}'.", + notMatchPrivate: "Identifier '#{{name}}' does not match the pattern '{{pattern}}'." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Options + //-------------------------------------------------------------------------- + const pattern = context.options[0] || "^.+$", + regexp = new RegExp(pattern, "u"); + + const options = context.options[1] || {}, + checkProperties = !!options.properties, + checkClassFields = !!options.classFields, + onlyDeclarations = !!options.onlyDeclarations, + ignoreDestructuring = !!options.ignoreDestructuring; + + const sourceCode = context.sourceCode; + let globalScope; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // contains reported nodes to avoid reporting twice on destructuring with shorthand notation + const reportedNodes = new Set(); + const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]); + const DECLARATION_TYPES = new Set(["FunctionDeclaration", "VariableDeclarator"]); + const IMPORT_TYPES = new Set(["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"]); + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return variable && variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node); + } + + /** + * Checks if a string matches the provided pattern + * @param {string} name The string to check. + * @returns {boolean} if the string is a match + * @private + */ + function isInvalid(name) { + return !regexp.test(name); + } + + /** + * Checks if a parent of a node is an ObjectPattern. + * @param {ASTNode} node The node to check. + * @returns {boolean} if the node is inside an ObjectPattern + * @private + */ + function isInsideObjectPattern(node) { + let { parent } = node; + + while (parent) { + if (parent.type === "ObjectPattern") { + return true; + } + + parent = parent.parent; + } + + return false; + } + + /** + * Verifies if we should report an error or not based on the effective + * parent node and the identifier name. + * @param {ASTNode} effectiveParent The effective parent node of the node to be reported + * @param {string} name The identifier name of the identifier node + * @returns {boolean} whether an error should be reported or not + */ + function shouldReport(effectiveParent, name) { + return (!onlyDeclarations || DECLARATION_TYPES.has(effectiveParent.type)) && + !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && isInvalid(name); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + + const messageId = (node.type === "PrivateIdentifier") + ? "notMatchPrivate" : "notMatch"; + + context.report({ + node, + messageId, + data: { + name: node.name, + pattern + } + }); + reportedNodes.add(node.range.toString()); + } + } + + return { + + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + Identifier(node) { + const name = node.name, + parent = node.parent, + effectiveParent = (parent.type === "MemberExpression") ? parent.parent : parent; + + if (isReferenceToGlobalVariable(node)) { + return; + } + + if (parent.type === "MemberExpression") { + + if (!checkProperties) { + return; + } + + // Always check object names + if (parent.object.type === "Identifier" && + parent.object.name === name) { + if (isInvalid(name)) { + report(node); + } + + // Report AssignmentExpressions left side's assigned variable id + } else if (effectiveParent.type === "AssignmentExpression" && + effectiveParent.left.type === "MemberExpression" && + effectiveParent.left.property.name === node.name) { + if (isInvalid(name)) { + report(node); + } + + // Report AssignmentExpressions only if they are the left side of the assignment + } else if (effectiveParent.type === "AssignmentExpression" && effectiveParent.right.type !== "MemberExpression") { + if (isInvalid(name)) { + report(node); + } + } + + // For https://github.com/eslint/eslint/issues/15123 + } else if ( + parent.type === "Property" && + parent.parent.type === "ObjectExpression" && + parent.key === node && + !parent.computed + ) { + if (checkProperties && isInvalid(name)) { + report(node); + } + + /* + * Properties have their own rules, and + * AssignmentPattern nodes can be treated like Properties: + * e.g.: const { no_camelcased = false } = bar; + */ + } else if (parent.type === "Property" || parent.type === "AssignmentPattern") { + + if (parent.parent && parent.parent.type === "ObjectPattern") { + if (!ignoreDestructuring && parent.shorthand && parent.value.left && isInvalid(name)) { + report(node); + } + + const assignmentKeyEqualsValue = parent.key.name === parent.value.name; + + // prevent checking righthand side of destructured object + if (!assignmentKeyEqualsValue && parent.key === node) { + return; + } + + const valueIsInvalid = parent.value.name && isInvalid(name); + + // ignore destructuring if the option is set, unless a new identifier is created + if (valueIsInvalid && !(assignmentKeyEqualsValue && ignoreDestructuring)) { + report(node); + } + } + + // never check properties or always ignore destructuring + if ((!checkProperties && !parent.computed) || (ignoreDestructuring && isInsideObjectPattern(node))) { + return; + } + + // don't check right hand side of AssignmentExpression to prevent duplicate warnings + if (parent.right !== node && shouldReport(effectiveParent, name)) { + report(node); + } + + // Check if it's an import specifier + } else if (IMPORT_TYPES.has(parent.type)) { + + // Report only if the local imported identifier is invalid + if (parent.local && parent.local.name === node.name && isInvalid(name)) { + report(node); + } + + } else if (parent.type === "PropertyDefinition") { + + if (checkClassFields && isInvalid(name)) { + report(node); + } + + // Report anything that is invalid that isn't a CallExpression + } else if (shouldReport(effectiveParent, name)) { + report(node); + } + }, + + "PrivateIdentifier"(node) { + + const isClassField = node.parent.type === "PropertyDefinition"; + + if (isClassField && !checkClassFields) { + return; + } + + if (isInvalid(node.name)) { + report(node); + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js b/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js new file mode 100644 index 0000000..30ab1a5 --- /dev/null +++ b/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js @@ -0,0 +1,81 @@ +/** + * @fileoverview enforce the location of arrow function bodies + * @author Sharmila Jesupaul + */ +"use strict"; + +const { isCommentToken, isNotOpeningParenToken } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce the location of arrow function bodies", + recommended: false, + url: "https://eslint.org/docs/latest/rules/implicit-arrow-linebreak" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["beside", "below"] + } + ], + messages: { + expected: "Expected a linebreak before this expression.", + unexpected: "Expected no linebreak before this expression." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "beside"; + + /** + * Validates the location of an arrow function body + * @param {ASTNode} node The arrow function body + * @returns {void} + */ + function validateExpression(node) { + if (node.body.type === "BlockStatement") { + return; + } + + const arrowToken = sourceCode.getTokenBefore(node.body, isNotOpeningParenToken); + const firstTokenOfBody = sourceCode.getTokenAfter(arrowToken); + + if (arrowToken.loc.end.line === firstTokenOfBody.loc.start.line && option === "below") { + context.report({ + node: firstTokenOfBody, + messageId: "expected", + fix: fixer => fixer.insertTextBefore(firstTokenOfBody, "\n") + }); + } else if (arrowToken.loc.end.line !== firstTokenOfBody.loc.start.line && option === "beside") { + context.report({ + node: firstTokenOfBody, + messageId: "unexpected", + fix(fixer) { + if (sourceCode.getFirstTokenBetween(arrowToken, firstTokenOfBody, { includeComments: true, filter: isCommentToken })) { + return null; + } + + return fixer.replaceTextRange([arrowToken.range[1], firstTokenOfBody.range[0]], " "); + } + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + return { + ArrowFunctionExpression: node => validateExpression(node) + }; + } +}; diff --git a/node_modules/eslint/lib/rules/indent-legacy.js b/node_modules/eslint/lib/rules/indent-legacy.js new file mode 100644 index 0000000..78bf965 --- /dev/null +++ b/node_modules/eslint/lib/rules/indent-legacy.js @@ -0,0 +1,1126 @@ +/** + * @fileoverview This option sets a specific tab width for your code + * + * This rule has been ported and modified from nodeca. + * @author Vitaly Puzrin + * @author Gyandeep Singh + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +// this rule has known coverage issues, but it's deprecated and shouldn't be updated in the future anyway. +/* c8 ignore next */ +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent indentation", + recommended: false, + url: "https://eslint.org/docs/latest/rules/indent-legacy" + }, + + deprecated: true, + + replacedBy: ["indent"], + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["tab"] + }, + { + type: "integer", + minimum: 0 + } + ] + }, + { + type: "object", + properties: { + SwitchCase: { + type: "integer", + minimum: 0 + }, + VariableDeclarator: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + type: "object", + properties: { + var: { + type: "integer", + minimum: 0 + }, + let: { + type: "integer", + minimum: 0 + }, + const: { + type: "integer", + minimum: 0 + } + } + } + ] + }, + outerIIFEBody: { + type: "integer", + minimum: 0 + }, + MemberExpression: { + type: "integer", + minimum: 0 + }, + FunctionDeclaration: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + }, + body: { + type: "integer", + minimum: 0 + } + } + }, + FunctionExpression: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + }, + body: { + type: "integer", + minimum: 0 + } + } + }, + CallExpression: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + } + } + }, + ArrayExpression: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + }, + ObjectExpression: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + } + }, + additionalProperties: false + } + ], + messages: { + expected: "Expected indentation of {{expected}} but found {{actual}}." + } + }, + + create(context) { + const DEFAULT_VARIABLE_INDENT = 1; + const DEFAULT_PARAMETER_INDENT = null; // For backwards compatibility, don't check parameter indentation unless specified in the config + const DEFAULT_FUNCTION_BODY_INDENT = 1; + + let indentType = "space"; + let indentSize = 4; + const options = { + SwitchCase: 0, + VariableDeclarator: { + var: DEFAULT_VARIABLE_INDENT, + let: DEFAULT_VARIABLE_INDENT, + const: DEFAULT_VARIABLE_INDENT + }, + outerIIFEBody: null, + FunctionDeclaration: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT + }, + FunctionExpression: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT + }, + CallExpression: { + arguments: DEFAULT_PARAMETER_INDENT + }, + ArrayExpression: 1, + ObjectExpression: 1 + }; + + const sourceCode = context.sourceCode; + + if (context.options.length) { + if (context.options[0] === "tab") { + indentSize = 1; + indentType = "tab"; + } else /* c8 ignore start */ if (typeof context.options[0] === "number") { + indentSize = context.options[0]; + indentType = "space"; + }/* c8 ignore stop */ + + if (context.options[1]) { + const opts = context.options[1]; + + options.SwitchCase = opts.SwitchCase || 0; + const variableDeclaratorRules = opts.VariableDeclarator; + + if (typeof variableDeclaratorRules === "number") { + options.VariableDeclarator = { + var: variableDeclaratorRules, + let: variableDeclaratorRules, + const: variableDeclaratorRules + }; + } else if (typeof variableDeclaratorRules === "object") { + Object.assign(options.VariableDeclarator, variableDeclaratorRules); + } + + if (typeof opts.outerIIFEBody === "number") { + options.outerIIFEBody = opts.outerIIFEBody; + } + + if (typeof opts.MemberExpression === "number") { + options.MemberExpression = opts.MemberExpression; + } + + if (typeof opts.FunctionDeclaration === "object") { + Object.assign(options.FunctionDeclaration, opts.FunctionDeclaration); + } + + if (typeof opts.FunctionExpression === "object") { + Object.assign(options.FunctionExpression, opts.FunctionExpression); + } + + if (typeof opts.CallExpression === "object") { + Object.assign(options.CallExpression, opts.CallExpression); + } + + if (typeof opts.ArrayExpression === "number" || typeof opts.ArrayExpression === "string") { + options.ArrayExpression = opts.ArrayExpression; + } + + if (typeof opts.ObjectExpression === "number" || typeof opts.ObjectExpression === "string") { + options.ObjectExpression = opts.ObjectExpression; + } + } + } + + const caseIndentStore = {}; + + /** + * Creates an error message for a line, given the expected/actual indentation. + * @param {int} expectedAmount The expected amount of indentation characters for this line + * @param {int} actualSpaces The actual number of indentation spaces that were found on this line + * @param {int} actualTabs The actual number of indentation tabs that were found on this line + * @returns {string} An error message for this line + */ + function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) { + const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" + const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" + const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" + let foundStatement; + + if (actualSpaces > 0 && actualTabs > 0) { + foundStatement = `${actualSpaces} ${foundSpacesWord} and ${actualTabs} ${foundTabsWord}`; // e.g. "1 space and 2 tabs" + } else if (actualSpaces > 0) { + + /* + * Abbreviate the message if the expected indentation is also spaces. + * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + */ + foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`; + } else if (actualTabs > 0) { + foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`; + } else { + foundStatement = "0"; + } + return { + expected: expectedStatement, + actual: foundStatement + }; + } + + /** + * Reports a given indent violation + * @param {ASTNode} node Node violating the indent rule + * @param {int} needed Expected indentation character count + * @param {int} gottenSpaces Indentation space count in the actual node/code + * @param {int} gottenTabs Indentation tab count in the actual node/code + * @param {Object} [loc] Error line and column location + * @param {boolean} isLastNodeCheck Is the error for last node check + * @returns {void} + */ + function report(node, needed, gottenSpaces, gottenTabs, loc, isLastNodeCheck) { + if (gottenSpaces && gottenTabs) { + + // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs. + return; + } + + const desiredIndent = (indentType === "space" ? " " : "\t").repeat(needed); + + const textRange = isLastNodeCheck + ? [node.range[1] - node.loc.end.column, node.range[1] - node.loc.end.column + gottenSpaces + gottenTabs] + : [node.range[0] - node.loc.start.column, node.range[0] - node.loc.start.column + gottenSpaces + gottenTabs]; + + context.report({ + node, + loc, + messageId: "expected", + data: createErrorMessageData(needed, gottenSpaces, gottenTabs), + fix: fixer => fixer.replaceTextRange(textRange, desiredIndent) + }); + } + + /** + * Get the actual indent of node + * @param {ASTNode|Token} node Node to examine + * @param {boolean} [byLastLine=false] get indent of node's last line + * @returns {Object} The node's indent. Contains keys `space` and `tab`, representing the indent of each character. Also + * contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and + * `badChar` is the amount of the other indentation character. + */ + function getNodeIndent(node, byLastLine) { + const token = byLastLine ? sourceCode.getLastToken(node) : sourceCode.getFirstToken(node); + const srcCharsBeforeNode = sourceCode.getText(token, token.loc.start.column).split(""); + const indentChars = srcCharsBeforeNode.slice(0, srcCharsBeforeNode.findIndex(char => char !== " " && char !== "\t")); + const spaces = indentChars.filter(char => char === " ").length; + const tabs = indentChars.filter(char => char === "\t").length; + + return { + space: spaces, + tab: tabs, + goodChar: indentType === "space" ? spaces : tabs, + badChar: indentType === "space" ? tabs : spaces + }; + } + + /** + * Checks node is the first in its own start line. By default it looks by start line. + * @param {ASTNode} node The node to check + * @param {boolean} [byEndLocation=false] Lookup based on start position or end + * @returns {boolean} true if its the first in the its start line + */ + function isNodeFirstInLine(node, byEndLocation) { + const firstToken = byEndLocation === true ? sourceCode.getLastToken(node, 1) : sourceCode.getTokenBefore(node), + startLine = byEndLocation === true ? node.loc.end.line : node.loc.start.line, + endLine = firstToken ? firstToken.loc.end.line : -1; + + return startLine !== endLine; + } + + /** + * Check indent for node + * @param {ASTNode} node Node to check + * @param {int} neededIndent needed indent + * @returns {void} + */ + function checkNodeIndent(node, neededIndent) { + const actualIndent = getNodeIndent(node, false); + + if ( + node.type !== "ArrayExpression" && + node.type !== "ObjectExpression" && + (actualIndent.goodChar !== neededIndent || actualIndent.badChar !== 0) && + isNodeFirstInLine(node) + ) { + report(node, neededIndent, actualIndent.space, actualIndent.tab); + } + + if (node.type === "IfStatement" && node.alternate) { + const elseToken = sourceCode.getTokenBefore(node.alternate); + + checkNodeIndent(elseToken, neededIndent); + + if (!isNodeFirstInLine(node.alternate)) { + checkNodeIndent(node.alternate, neededIndent); + } + } + + if (node.type === "TryStatement" && node.handler) { + const catchToken = sourceCode.getFirstToken(node.handler); + + checkNodeIndent(catchToken, neededIndent); + } + + if (node.type === "TryStatement" && node.finalizer) { + const finallyToken = sourceCode.getTokenBefore(node.finalizer); + + checkNodeIndent(finallyToken, neededIndent); + } + + if (node.type === "DoWhileStatement") { + const whileToken = sourceCode.getTokenAfter(node.body); + + checkNodeIndent(whileToken, neededIndent); + } + } + + /** + * Check indent for nodes list + * @param {ASTNode[]} nodes list of node objects + * @param {int} indent needed indent + * @returns {void} + */ + function checkNodesIndent(nodes, indent) { + nodes.forEach(node => checkNodeIndent(node, indent)); + } + + /** + * Check last node line indent this detects, that block closed correctly + * @param {ASTNode} node Node to examine + * @param {int} lastLineIndent needed indent + * @returns {void} + */ + function checkLastNodeLineIndent(node, lastLineIndent) { + const lastToken = sourceCode.getLastToken(node); + const endIndent = getNodeIndent(lastToken, true); + + if ((endIndent.goodChar !== lastLineIndent || endIndent.badChar !== 0) && isNodeFirstInLine(node, true)) { + report( + node, + lastLineIndent, + endIndent.space, + endIndent.tab, + { line: lastToken.loc.start.line, column: lastToken.loc.start.column }, + true + ); + } + } + + /** + * Check last node line indent this detects, that block closed correctly + * This function for more complicated return statement case, where closing parenthesis may be followed by ';' + * @param {ASTNode} node Node to examine + * @param {int} firstLineIndent first line needed indent + * @returns {void} + */ + function checkLastReturnStatementLineIndent(node, firstLineIndent) { + + /* + * in case if return statement ends with ');' we have traverse back to ')' + * otherwise we'll measure indent for ';' and replace ')' + */ + const lastToken = sourceCode.getLastToken(node, astUtils.isClosingParenToken); + const textBeforeClosingParenthesis = sourceCode.getText(lastToken, lastToken.loc.start.column).slice(0, -1); + + if (textBeforeClosingParenthesis.trim()) { + + // There are tokens before the closing paren, don't report this case + return; + } + + const endIndent = getNodeIndent(lastToken, true); + + if (endIndent.goodChar !== firstLineIndent) { + report( + node, + firstLineIndent, + endIndent.space, + endIndent.tab, + { line: lastToken.loc.start.line, column: lastToken.loc.start.column }, + true + ); + } + } + + /** + * Check first node line indent is correct + * @param {ASTNode} node Node to examine + * @param {int} firstLineIndent needed indent + * @returns {void} + */ + function checkFirstNodeLineIndent(node, firstLineIndent) { + const startIndent = getNodeIndent(node, false); + + if ((startIndent.goodChar !== firstLineIndent || startIndent.badChar !== 0) && isNodeFirstInLine(node)) { + report( + node, + firstLineIndent, + startIndent.space, + startIndent.tab, + { line: node.loc.start.line, column: node.loc.start.column } + ); + } + } + + /** + * Returns a parent node of given node based on a specified type + * if not present then return null + * @param {ASTNode} node node to examine + * @param {string} type type that is being looked for + * @param {string} stopAtList end points for the evaluating code + * @returns {ASTNode|void} if found then node otherwise null + */ + function getParentNodeByType(node, type, stopAtList) { + let parent = node.parent; + const stopAtSet = new Set(stopAtList || ["Program"]); + + while (parent.type !== type && !stopAtSet.has(parent.type) && parent.type !== "Program") { + parent = parent.parent; + } + + return parent.type === type ? parent : null; + } + + /** + * Returns the VariableDeclarator based on the current node + * if not present then return null + * @param {ASTNode} node node to examine + * @returns {ASTNode|void} if found then node otherwise null + */ + function getVariableDeclaratorNode(node) { + return getParentNodeByType(node, "VariableDeclarator"); + } + + /** + * Check to see if the node is part of the multi-line variable declaration. + * Also if its on the same line as the varNode + * @param {ASTNode} node node to check + * @param {ASTNode} varNode variable declaration node to check against + * @returns {boolean} True if all the above condition satisfy + */ + function isNodeInVarOnTop(node, varNode) { + return varNode && + varNode.parent.loc.start.line === node.loc.start.line && + varNode.parent.declarations.length > 1; + } + + /** + * Check to see if the argument before the callee node is multi-line and + * there should only be 1 argument before the callee node + * @param {ASTNode} node node to check + * @returns {boolean} True if arguments are multi-line + */ + function isArgBeforeCalleeNodeMultiline(node) { + const parent = node.parent; + + if (parent.arguments.length >= 2 && parent.arguments[1] === node) { + return parent.arguments[0].loc.end.line > parent.arguments[0].loc.start.line; + } + + return false; + } + + /** + * Check to see if the node is a file level IIFE + * @param {ASTNode} node The function node to check. + * @returns {boolean} True if the node is the outer IIFE + */ + function isOuterIIFE(node) { + const parent = node.parent; + let stmt = parent.parent; + + /* + * Verify that the node is an IIEF + */ + if ( + parent.type !== "CallExpression" || + parent.callee !== node) { + + return false; + } + + /* + * Navigate legal ancestors to determine whether this IIEF is outer + */ + while ( + stmt.type === "UnaryExpression" && ( + stmt.operator === "!" || + stmt.operator === "~" || + stmt.operator === "+" || + stmt.operator === "-") || + stmt.type === "AssignmentExpression" || + stmt.type === "LogicalExpression" || + stmt.type === "SequenceExpression" || + stmt.type === "VariableDeclarator") { + + stmt = stmt.parent; + } + + return (( + stmt.type === "ExpressionStatement" || + stmt.type === "VariableDeclaration") && + stmt.parent && stmt.parent.type === "Program" + ); + } + + /** + * Check indent for function block content + * @param {ASTNode} node A BlockStatement node that is inside of a function. + * @returns {void} + */ + function checkIndentInFunctionBlock(node) { + + /* + * Search first caller in chain. + * Ex.: + * + * Models <- Identifier + * .User + * .find() + * .exec(function() { + * // function body + * }); + * + * Looks for 'Models' + */ + const calleeNode = node.parent; // FunctionExpression + let indent; + + if (calleeNode.parent && + (calleeNode.parent.type === "Property" || + calleeNode.parent.type === "ArrayExpression")) { + + // If function is part of array or object, comma can be put at left + indent = getNodeIndent(calleeNode, false).goodChar; + } else { + + // If function is standalone, simple calculate indent + indent = getNodeIndent(calleeNode).goodChar; + } + + if (calleeNode.parent.type === "CallExpression") { + const calleeParent = calleeNode.parent; + + if (calleeNode.type !== "FunctionExpression" && calleeNode.type !== "ArrowFunctionExpression") { + if (calleeParent && calleeParent.loc.start.line < node.loc.start.line) { + indent = getNodeIndent(calleeParent).goodChar; + } + } else { + if (isArgBeforeCalleeNodeMultiline(calleeNode) && + calleeParent.callee.loc.start.line === calleeParent.callee.loc.end.line && + !isNodeFirstInLine(calleeNode)) { + indent = getNodeIndent(calleeParent).goodChar; + } + } + } + + /* + * function body indent should be indent + indent size, unless this + * is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled. + */ + let functionOffset = indentSize; + + if (options.outerIIFEBody !== null && isOuterIIFE(calleeNode)) { + functionOffset = options.outerIIFEBody * indentSize; + } else if (calleeNode.type === "FunctionExpression") { + functionOffset = options.FunctionExpression.body * indentSize; + } else if (calleeNode.type === "FunctionDeclaration") { + functionOffset = options.FunctionDeclaration.body * indentSize; + } + indent += functionOffset; + + // check if the node is inside a variable + const parentVarNode = getVariableDeclaratorNode(node); + + if (parentVarNode && isNodeInVarOnTop(node, parentVarNode)) { + indent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind]; + } + + if (node.body.length > 0) { + checkNodesIndent(node.body, indent); + } + + checkLastNodeLineIndent(node, indent - functionOffset); + } + + + /** + * Checks if the given node starts and ends on the same line + * @param {ASTNode} node The node to check + * @returns {boolean} Whether or not the block starts and ends on the same line. + */ + function isSingleLineNode(node) { + const lastToken = sourceCode.getLastToken(node), + startLine = node.loc.start.line, + endLine = lastToken.loc.end.line; + + return startLine === endLine; + } + + /** + * Check indent for array block content or object block content + * @param {ASTNode} node node to examine + * @returns {void} + */ + function checkIndentInArrayOrObjectBlock(node) { + + // Skip inline + if (isSingleLineNode(node)) { + return; + } + + let elements = (node.type === "ArrayExpression") ? node.elements : node.properties; + + // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null + elements = elements.filter(elem => elem !== null); + + let nodeIndent; + let elementsIndent; + const parentVarNode = getVariableDeclaratorNode(node); + + // TODO - come up with a better strategy in future + if (isNodeFirstInLine(node)) { + const parent = node.parent; + + nodeIndent = getNodeIndent(parent).goodChar; + if (!parentVarNode || parentVarNode.loc.start.line !== node.loc.start.line) { + if (parent.type !== "VariableDeclarator" || parentVarNode === parentVarNode.parent.declarations[0]) { + if (parent.type === "VariableDeclarator" && parentVarNode.loc.start.line === parent.loc.start.line) { + nodeIndent += (indentSize * options.VariableDeclarator[parentVarNode.parent.kind]); + } else if (parent.type === "ObjectExpression" || parent.type === "ArrayExpression") { + const parentElements = node.parent.type === "ObjectExpression" ? node.parent.properties : node.parent.elements; + + if (parentElements[0] && + parentElements[0].loc.start.line === parent.loc.start.line && + parentElements[0].loc.end.line !== parent.loc.start.line) { + + /* + * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest. + * e.g. [{ + * foo: 1 + * }, + * { + * bar: 1 + * }] + * the second object is not indented. + */ + } else if (typeof options[parent.type] === "number") { + nodeIndent += options[parent.type] * indentSize; + } else { + nodeIndent = parentElements[0].loc.start.column; + } + } else if (parent.type === "CallExpression" || parent.type === "NewExpression") { + if (typeof options.CallExpression.arguments === "number") { + nodeIndent += options.CallExpression.arguments * indentSize; + } else if (options.CallExpression.arguments === "first") { + if (parent.arguments.includes(node)) { + nodeIndent = parent.arguments[0].loc.start.column; + } + } else { + nodeIndent += indentSize; + } + } else if (parent.type === "LogicalExpression" || parent.type === "ArrowFunctionExpression") { + nodeIndent += indentSize; + } + } + } + + checkFirstNodeLineIndent(node, nodeIndent); + } else { + nodeIndent = getNodeIndent(node).goodChar; + } + + if (options[node.type] === "first") { + elementsIndent = elements.length ? elements[0].loc.start.column : 0; // If there are no elements, elementsIndent doesn't matter. + } else { + elementsIndent = nodeIndent + indentSize * options[node.type]; + } + + /* + * Check if the node is a multiple variable declaration; if so, then + * make sure indentation takes that into account. + */ + if (isNodeInVarOnTop(node, parentVarNode)) { + elementsIndent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind]; + } + + checkNodesIndent(elements, elementsIndent); + + if (elements.length > 0) { + + // Skip last block line check if last item in same line + if (elements[elements.length - 1].loc.end.line === node.loc.end.line) { + return; + } + } + + checkLastNodeLineIndent(node, nodeIndent + + (isNodeInVarOnTop(node, parentVarNode) ? options.VariableDeclarator[parentVarNode.parent.kind] * indentSize : 0)); + } + + /** + * Check if the node or node body is a BlockStatement or not + * @param {ASTNode} node node to test + * @returns {boolean} True if it or its body is a block statement + */ + function isNodeBodyBlock(node) { + return node.type === "BlockStatement" || node.type === "ClassBody" || (node.body && node.body.type === "BlockStatement") || + (node.consequent && node.consequent.type === "BlockStatement"); + } + + /** + * Check indentation for blocks + * @param {ASTNode} node node to check + * @returns {void} + */ + function blockIndentationCheck(node) { + + // Skip inline blocks + if (isSingleLineNode(node)) { + return; + } + + if (node.parent && ( + node.parent.type === "FunctionExpression" || + node.parent.type === "FunctionDeclaration" || + node.parent.type === "ArrowFunctionExpression") + ) { + checkIndentInFunctionBlock(node); + return; + } + + let indent; + let nodesToCheck = []; + + /* + * For this statements we should check indent from statement beginning, + * not from the beginning of the block. + */ + const statementsWithProperties = [ + "IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration", "TryStatement" + ]; + + if (node.parent && statementsWithProperties.includes(node.parent.type) && isNodeBodyBlock(node)) { + indent = getNodeIndent(node.parent).goodChar; + } else if (node.parent && node.parent.type === "CatchClause") { + indent = getNodeIndent(node.parent.parent).goodChar; + } else { + indent = getNodeIndent(node).goodChar; + } + + if (node.type === "IfStatement" && node.consequent.type !== "BlockStatement") { + nodesToCheck = [node.consequent]; + } else if (Array.isArray(node.body)) { + nodesToCheck = node.body; + } else { + nodesToCheck = [node.body]; + } + + if (nodesToCheck.length > 0) { + checkNodesIndent(nodesToCheck, indent + indentSize); + } + + if (node.type === "BlockStatement") { + checkLastNodeLineIndent(node, indent); + } + } + + /** + * Filter out the elements which are on the same line of each other or the node. + * basically have only 1 elements from each line except the variable declaration line. + * @param {ASTNode} node Variable declaration node + * @returns {ASTNode[]} Filtered elements + */ + function filterOutSameLineVars(node) { + return node.declarations.reduce((finalCollection, elem) => { + const lastElem = finalCollection[finalCollection.length - 1]; + + if ((elem.loc.start.line !== node.loc.start.line && !lastElem) || + (lastElem && lastElem.loc.start.line !== elem.loc.start.line)) { + finalCollection.push(elem); + } + + return finalCollection; + }, []); + } + + /** + * Check indentation for variable declarations + * @param {ASTNode} node node to examine + * @returns {void} + */ + function checkIndentInVariableDeclarations(node) { + const elements = filterOutSameLineVars(node); + const nodeIndent = getNodeIndent(node).goodChar; + const lastElement = elements[elements.length - 1]; + + const elementsIndent = nodeIndent + indentSize * options.VariableDeclarator[node.kind]; + + checkNodesIndent(elements, elementsIndent); + + // Only check the last line if there is any token after the last item + if (sourceCode.getLastToken(node).loc.end.line <= lastElement.loc.end.line) { + return; + } + + const tokenBeforeLastElement = sourceCode.getTokenBefore(lastElement); + + if (tokenBeforeLastElement.value === ",") { + + // Special case for comma-first syntax where the semicolon is indented + checkLastNodeLineIndent(node, getNodeIndent(tokenBeforeLastElement).goodChar); + } else { + checkLastNodeLineIndent(node, elementsIndent - indentSize); + } + } + + /** + * Check and decide whether to check for indentation for blockless nodes + * Scenarios are for or while statements without braces around them + * @param {ASTNode} node node to examine + * @returns {void} + */ + function blockLessNodes(node) { + if (node.body.type !== "BlockStatement") { + blockIndentationCheck(node); + } + } + + /** + * Returns the expected indentation for the case statement + * @param {ASTNode} node node to examine + * @param {int} [providedSwitchIndent] indent for switch statement + * @returns {int} indent size + */ + function expectedCaseIndent(node, providedSwitchIndent) { + const switchNode = (node.type === "SwitchStatement") ? node : node.parent; + const switchIndent = typeof providedSwitchIndent === "undefined" + ? getNodeIndent(switchNode).goodChar + : providedSwitchIndent; + let caseIndent; + + if (caseIndentStore[switchNode.loc.start.line]) { + return caseIndentStore[switchNode.loc.start.line]; + } + + if (switchNode.cases.length > 0 && options.SwitchCase === 0) { + caseIndent = switchIndent; + } else { + caseIndent = switchIndent + (indentSize * options.SwitchCase); + } + + caseIndentStore[switchNode.loc.start.line] = caseIndent; + return caseIndent; + + } + + /** + * Checks whether a return statement is wrapped in () + * @param {ASTNode} node node to examine + * @returns {boolean} the result + */ + function isWrappedInParenthesis(node) { + const regex = /^return\s*?\(\s*?\);*?/u; + + const statementWithoutArgument = sourceCode.getText(node).replace( + sourceCode.getText(node.argument), "" + ); + + return regex.test(statementWithoutArgument); + } + + return { + Program(node) { + if (node.body.length > 0) { + + // Root nodes should have no indent + checkNodesIndent(node.body, getNodeIndent(node).goodChar); + } + }, + + ClassBody: blockIndentationCheck, + + BlockStatement: blockIndentationCheck, + + WhileStatement: blockLessNodes, + + ForStatement: blockLessNodes, + + ForInStatement: blockLessNodes, + + ForOfStatement: blockLessNodes, + + DoWhileStatement: blockLessNodes, + + IfStatement(node) { + if (node.consequent.type !== "BlockStatement" && node.consequent.loc.start.line > node.loc.start.line) { + blockIndentationCheck(node); + } + }, + + VariableDeclaration(node) { + if (node.declarations[node.declarations.length - 1].loc.start.line > node.declarations[0].loc.start.line) { + checkIndentInVariableDeclarations(node); + } + }, + + ObjectExpression(node) { + checkIndentInArrayOrObjectBlock(node); + }, + + ArrayExpression(node) { + checkIndentInArrayOrObjectBlock(node); + }, + + MemberExpression(node) { + + if (typeof options.MemberExpression === "undefined") { + return; + } + + if (isSingleLineNode(node)) { + return; + } + + /* + * The typical layout of variable declarations and assignments + * alter the expectation of correct indentation. Skip them. + * TODO: Add appropriate configuration options for variable + * declarations and assignments. + */ + if (getParentNodeByType(node, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) { + return; + } + + if (getParentNodeByType(node, "AssignmentExpression", ["FunctionExpression"])) { + return; + } + + const propertyIndent = getNodeIndent(node).goodChar + indentSize * options.MemberExpression; + + const checkNodes = [node.property]; + + const dot = sourceCode.getTokenBefore(node.property); + + if (dot.type === "Punctuator" && dot.value === ".") { + checkNodes.push(dot); + } + + checkNodesIndent(checkNodes, propertyIndent); + }, + + SwitchStatement(node) { + + // Switch is not a 'BlockStatement' + const switchIndent = getNodeIndent(node).goodChar; + const caseIndent = expectedCaseIndent(node, switchIndent); + + checkNodesIndent(node.cases, caseIndent); + + + checkLastNodeLineIndent(node, switchIndent); + }, + + SwitchCase(node) { + + // Skip inline cases + if (isSingleLineNode(node)) { + return; + } + const caseIndent = expectedCaseIndent(node); + + checkNodesIndent(node.consequent, caseIndent + indentSize); + }, + + FunctionDeclaration(node) { + if (isSingleLineNode(node)) { + return; + } + if (options.FunctionDeclaration.parameters === "first" && node.params.length) { + checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column); + } else if (options.FunctionDeclaration.parameters !== null) { + checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionDeclaration.parameters); + } + }, + + FunctionExpression(node) { + if (isSingleLineNode(node)) { + return; + } + if (options.FunctionExpression.parameters === "first" && node.params.length) { + checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column); + } else if (options.FunctionExpression.parameters !== null) { + checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionExpression.parameters); + } + }, + + ReturnStatement(node) { + if (isSingleLineNode(node)) { + return; + } + + const firstLineIndent = getNodeIndent(node).goodChar; + + // in case if return statement is wrapped in parenthesis + if (isWrappedInParenthesis(node)) { + checkLastReturnStatementLineIndent(node, firstLineIndent); + } else { + checkNodeIndent(node, firstLineIndent); + } + }, + + CallExpression(node) { + if (isSingleLineNode(node)) { + return; + } + if (options.CallExpression.arguments === "first" && node.arguments.length) { + checkNodesIndent(node.arguments.slice(1), node.arguments[0].loc.start.column); + } else if (options.CallExpression.arguments !== null) { + checkNodesIndent(node.arguments, getNodeIndent(node).goodChar + indentSize * options.CallExpression.arguments); + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/indent.js b/node_modules/eslint/lib/rules/indent.js new file mode 100644 index 0000000..7ea4b3f --- /dev/null +++ b/node_modules/eslint/lib/rules/indent.js @@ -0,0 +1,1800 @@ +/** + * @fileoverview This rule sets a specific indentation style and width for your code + * + * @author Teddy Katz + * @author Vitaly Puzrin + * @author Gyandeep Singh + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const KNOWN_NODES = new Set([ + "AssignmentExpression", + "AssignmentPattern", + "ArrayExpression", + "ArrayPattern", + "ArrowFunctionExpression", + "AwaitExpression", + "BlockStatement", + "BinaryExpression", + "BreakStatement", + "CallExpression", + "CatchClause", + "ChainExpression", + "ClassBody", + "ClassDeclaration", + "ClassExpression", + "ConditionalExpression", + "ContinueStatement", + "DoWhileStatement", + "DebuggerStatement", + "EmptyStatement", + "ExperimentalRestProperty", + "ExperimentalSpreadProperty", + "ExpressionStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "FunctionDeclaration", + "FunctionExpression", + "Identifier", + "IfStatement", + "Literal", + "LabeledStatement", + "LogicalExpression", + "MemberExpression", + "MetaProperty", + "MethodDefinition", + "NewExpression", + "ObjectExpression", + "ObjectPattern", + "PrivateIdentifier", + "Program", + "Property", + "PropertyDefinition", + "RestElement", + "ReturnStatement", + "SequenceExpression", + "SpreadElement", + "StaticBlock", + "Super", + "SwitchCase", + "SwitchStatement", + "TaggedTemplateExpression", + "TemplateElement", + "TemplateLiteral", + "ThisExpression", + "ThrowStatement", + "TryStatement", + "UnaryExpression", + "UpdateExpression", + "VariableDeclaration", + "VariableDeclarator", + "WhileStatement", + "WithStatement", + "YieldExpression", + "JSXFragment", + "JSXOpeningFragment", + "JSXClosingFragment", + "JSXIdentifier", + "JSXNamespacedName", + "JSXMemberExpression", + "JSXEmptyExpression", + "JSXExpressionContainer", + "JSXElement", + "JSXClosingElement", + "JSXOpeningElement", + "JSXAttribute", + "JSXSpreadAttribute", + "JSXText", + "ExportDefaultDeclaration", + "ExportNamedDeclaration", + "ExportAllDeclaration", + "ExportSpecifier", + "ImportDeclaration", + "ImportSpecifier", + "ImportDefaultSpecifier", + "ImportNamespaceSpecifier", + "ImportExpression" +]); + +/* + * General rule strategy: + * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another + * specified token or to the first column. + * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a + * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly + * brace of the BlockStatement. + * 3. After traversing the AST, calculate the expected indentation levels of every token according to the + * OffsetStorage container. + * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file, + * and report the token if the two values are not equal. + */ + + +/** + * A mutable map that stores (key, value) pairs. The keys are numeric indices, and must be unique. + * This is intended to be a generic wrapper around a map with non-negative integer keys, so that the underlying implementation + * can easily be swapped out. + */ +class IndexMap { + + /** + * Creates an empty map + * @param {number} maxKey The maximum key + */ + constructor(maxKey) { + + // Initializing the array with the maximum expected size avoids dynamic reallocations that could degrade performance. + this._values = Array(maxKey + 1); + } + + /** + * Inserts an entry into the map. + * @param {number} key The entry's key + * @param {any} value The entry's value + * @returns {void} + */ + insert(key, value) { + this._values[key] = value; + } + + /** + * Finds the value of the entry with the largest key less than or equal to the provided key + * @param {number} key The provided key + * @returns {*|undefined} The value of the found entry, or undefined if no such entry exists. + */ + findLastNotAfter(key) { + const values = this._values; + + for (let index = key; index >= 0; index--) { + const value = values[index]; + + if (value) { + return value; + } + } + return void 0; + } + + /** + * Deletes all of the keys in the interval [start, end) + * @param {number} start The start of the range + * @param {number} end The end of the range + * @returns {void} + */ + deleteRange(start, end) { + this._values.fill(void 0, start, end); + } +} + +/** + * A helper class to get token-based info related to indentation + */ +class TokenInfo { + + /** + * @param {SourceCode} sourceCode A SourceCode object + */ + constructor(sourceCode) { + this.sourceCode = sourceCode; + this.firstTokensByLineNumber = new Map(); + const tokens = sourceCode.tokensAndComments; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + + if (!this.firstTokensByLineNumber.has(token.loc.start.line)) { + this.firstTokensByLineNumber.set(token.loc.start.line, token); + } + if (!this.firstTokensByLineNumber.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) { + this.firstTokensByLineNumber.set(token.loc.end.line, token); + } + } + } + + /** + * Gets the first token on a given token's line + * @param {Token|ASTNode} token a node or token + * @returns {Token} The first token on the given line + */ + getFirstTokenOfLine(token) { + return this.firstTokensByLineNumber.get(token.loc.start.line); + } + + /** + * Determines whether a token is the first token in its line + * @param {Token} token The token + * @returns {boolean} `true` if the token is the first on its line + */ + isFirstTokenOfLine(token) { + return this.getFirstTokenOfLine(token) === token; + } + + /** + * Get the actual indent of a token + * @param {Token} token Token to examine. This should be the first token on its line. + * @returns {string} The indentation characters that precede the token + */ + getTokenIndent(token) { + return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]); + } +} + +/** + * A class to store information on desired offsets of tokens from each other + */ +class OffsetStorage { + + /** + * @param {TokenInfo} tokenInfo a TokenInfo instance + * @param {number} indentSize The desired size of each indentation level + * @param {string} indentType The indentation character + * @param {number} maxIndex The maximum end index of any token + */ + constructor(tokenInfo, indentSize, indentType, maxIndex) { + this._tokenInfo = tokenInfo; + this._indentSize = indentSize; + this._indentType = indentType; + + this._indexMap = new IndexMap(maxIndex); + this._indexMap.insert(0, { offset: 0, from: null, force: false }); + + this._lockedFirstTokens = new WeakMap(); + this._desiredIndentCache = new WeakMap(); + this._ignoredTokens = new WeakSet(); + } + + _getOffsetDescriptor(token) { + return this._indexMap.findLastNotAfter(token.range[0]); + } + + /** + * Sets the offset column of token B to match the offset column of token A. + * - **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In + * most cases, `setDesiredOffset` should be used instead. + * @param {Token} baseToken The first token + * @param {Token} offsetToken The second token, whose offset should be matched to the first token + * @returns {void} + */ + matchOffsetOf(baseToken, offsetToken) { + + /* + * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to + * the token that it depends on. For example, with the `ArrayExpression: first` option, the first + * token of each element in the array after the first will be mapped to the first token of the first + * element. The desired indentation of each of these tokens is computed based on the desired indentation + * of the "first" element, rather than through the normal offset mechanism. + */ + this._lockedFirstTokens.set(offsetToken, baseToken); + } + + /** + * Sets the desired offset of a token. + * + * This uses a line-based offset collapsing behavior to handle tokens on the same line. + * For example, consider the following two cases: + * + * ( + * [ + * bar + * ] + * ) + * + * ([ + * bar + * ]) + * + * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from + * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is + * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces) + * from the start of its line. + * + * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level + * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the + * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented + * by 1 indent level from the start of the line. + * + * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node, + * without needing to check which lines those tokens are on. + * + * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive + * behavior can occur. For example, consider the following cases: + * + * foo( + * ). + * bar( + * baz + * ) + * + * foo( + * ).bar( + * baz + * ) + * + * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz` + * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz` + * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no + * collapsing would occur). + * + * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and + * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed + * in the second case. + * @param {Token} token The token + * @param {Token} fromToken The token that `token` should be offset from + * @param {number} offset The desired indent level + * @returns {void} + */ + setDesiredOffset(token, fromToken, offset) { + return this.setDesiredOffsets(token.range, fromToken, offset); + } + + /** + * Sets the desired offset of all tokens in a range + * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens. + * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains + * it). This means that the offset of each token is updated O(AST depth) times. + * It would not be performant to store and update the offsets for each token independently, because the rule would end + * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files. + * + * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following + * list could represent the state of the offset tree at a given point: + * + * - Tokens starting in the interval [0, 15) are aligned with the beginning of the file + * - Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token + * - Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token + * - Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token + * - Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token + * + * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using: + * `setDesiredOffsets([30, 43], fooToken, 1);` + * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied. + * @param {Token} fromToken The token that this is offset from + * @param {number} offset The desired indent level + * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false. + * @returns {void} + */ + setDesiredOffsets(range, fromToken, offset, force) { + + /* + * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset + * descriptor. The tree for the example above would have the following nodes: + * + * * key: 0, value: { offset: 0, from: null } + * * key: 15, value: { offset: 1, from: barToken } + * * key: 30, value: { offset: 1, from: fooToken } + * * key: 43, value: { offset: 2, from: barToken } + * * key: 820, value: { offset: 1, from: bazToken } + * + * To find the offset descriptor for any given token, one needs to find the node with the largest key + * which is <= token.start. To make this operation fast, the nodes are stored in a map indexed by key. + */ + + const descriptorToInsert = { offset, from: fromToken, force }; + + const descriptorAfterRange = this._indexMap.findLastNotAfter(range[1]); + + const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1]; + const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken); + + // First, remove any existing nodes in the range from the map. + this._indexMap.deleteRange(range[0] + 1, range[1]); + + // Insert a new node into the map for this range + this._indexMap.insert(range[0], descriptorToInsert); + + /* + * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously, + * even if it's in the current range. + */ + if (fromTokenIsInRange) { + this._indexMap.insert(fromToken.range[0], fromTokenDescriptor); + this._indexMap.insert(fromToken.range[1], descriptorToInsert); + } + + /* + * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following + * tokens the same as it was before. + */ + this._indexMap.insert(range[1], descriptorAfterRange); + } + + /** + * Gets the desired indent of a token + * @param {Token} token The token + * @returns {string} The desired indent of the token + */ + getDesiredIndent(token) { + if (!this._desiredIndentCache.has(token)) { + + if (this._ignoredTokens.has(token)) { + + /* + * If the token is ignored, use the actual indent of the token as the desired indent. + * This ensures that no errors are reported for this token. + */ + this._desiredIndentCache.set( + token, + this._tokenInfo.getTokenIndent(token) + ); + } else if (this._lockedFirstTokens.has(token)) { + const firstToken = this._lockedFirstTokens.get(token); + + this._desiredIndentCache.set( + token, + + // (indentation for the first element's line) + this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) + + + // (space between the start of the first element's line and the first element) + this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column) + ); + } else { + const offsetInfo = this._getOffsetDescriptor(token); + const offset = ( + offsetInfo.from && + offsetInfo.from.loc.start.line === token.loc.start.line && + !/^\s*?\n/u.test(token.value) && + !offsetInfo.force + ) ? 0 : offsetInfo.offset * this._indentSize; + + this._desiredIndentCache.set( + token, + (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset) + ); + } + } + return this._desiredIndentCache.get(token); + } + + /** + * Ignores a token, preventing it from being reported. + * @param {Token} token The token + * @returns {void} + */ + ignoreToken(token) { + if (this._tokenInfo.isFirstTokenOfLine(token)) { + this._ignoredTokens.add(token); + } + } + + /** + * Gets the first token that the given token's indentation is dependent on + * @param {Token} token The token + * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level + */ + getFirstDependency(token) { + return this._getOffsetDescriptor(token).from; + } +} + +const ELEMENT_LIST_SCHEMA = { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first", "off"] + } + ] +}; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent indentation", + recommended: false, + url: "https://eslint.org/docs/latest/rules/indent" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["tab"] + }, + { + type: "integer", + minimum: 0 + } + ] + }, + { + type: "object", + properties: { + SwitchCase: { + type: "integer", + minimum: 0, + default: 0 + }, + VariableDeclarator: { + oneOf: [ + ELEMENT_LIST_SCHEMA, + { + type: "object", + properties: { + var: ELEMENT_LIST_SCHEMA, + let: ELEMENT_LIST_SCHEMA, + const: ELEMENT_LIST_SCHEMA + }, + additionalProperties: false + } + ] + }, + outerIIFEBody: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["off"] + } + ] + }, + MemberExpression: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["off"] + } + ] + }, + FunctionDeclaration: { + type: "object", + properties: { + parameters: ELEMENT_LIST_SCHEMA, + body: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + }, + FunctionExpression: { + type: "object", + properties: { + parameters: ELEMENT_LIST_SCHEMA, + body: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + }, + StaticBlock: { + type: "object", + properties: { + body: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + }, + CallExpression: { + type: "object", + properties: { + arguments: ELEMENT_LIST_SCHEMA + }, + additionalProperties: false + }, + ArrayExpression: ELEMENT_LIST_SCHEMA, + ObjectExpression: ELEMENT_LIST_SCHEMA, + ImportDeclaration: ELEMENT_LIST_SCHEMA, + flatTernaryExpressions: { + type: "boolean", + default: false + }, + offsetTernaryExpressions: { + type: "boolean", + default: false + }, + ignoredNodes: { + type: "array", + items: { + type: "string", + not: { + pattern: ":exit$" + } + } + }, + ignoreComments: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + messages: { + wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}." + } + }, + + create(context) { + const DEFAULT_VARIABLE_INDENT = 1; + const DEFAULT_PARAMETER_INDENT = 1; + const DEFAULT_FUNCTION_BODY_INDENT = 1; + + let indentType = "space"; + let indentSize = 4; + const options = { + SwitchCase: 0, + VariableDeclarator: { + var: DEFAULT_VARIABLE_INDENT, + let: DEFAULT_VARIABLE_INDENT, + const: DEFAULT_VARIABLE_INDENT + }, + outerIIFEBody: 1, + FunctionDeclaration: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT + }, + FunctionExpression: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT + }, + StaticBlock: { + body: DEFAULT_FUNCTION_BODY_INDENT + }, + CallExpression: { + arguments: DEFAULT_PARAMETER_INDENT + }, + MemberExpression: 1, + ArrayExpression: 1, + ObjectExpression: 1, + ImportDeclaration: 1, + flatTernaryExpressions: false, + ignoredNodes: [], + ignoreComments: false + }; + + if (context.options.length) { + if (context.options[0] === "tab") { + indentSize = 1; + indentType = "tab"; + } else { + indentSize = context.options[0]; + indentType = "space"; + } + + if (context.options[1]) { + Object.assign(options, context.options[1]); + + if (typeof options.VariableDeclarator === "number" || options.VariableDeclarator === "first") { + options.VariableDeclarator = { + var: options.VariableDeclarator, + let: options.VariableDeclarator, + const: options.VariableDeclarator + }; + } + } + } + + const sourceCode = context.sourceCode; + const tokenInfo = new TokenInfo(sourceCode); + const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t", sourceCode.text.length); + const parameterParens = new WeakSet(); + + /** + * Creates an error message for a line, given the expected/actual indentation. + * @param {int} expectedAmount The expected amount of indentation characters for this line + * @param {int} actualSpaces The actual number of indentation spaces that were found on this line + * @param {int} actualTabs The actual number of indentation tabs that were found on this line + * @returns {string} An error message for this line + */ + function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) { + const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" + const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" + const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" + let foundStatement; + + if (actualSpaces > 0) { + + /* + * Abbreviate the message if the expected indentation is also spaces. + * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + */ + foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`; + } else if (actualTabs > 0) { + foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`; + } else { + foundStatement = "0"; + } + return { + expected: expectedStatement, + actual: foundStatement + }; + } + + /** + * Reports a given indent violation + * @param {Token} token Token violating the indent rule + * @param {string} neededIndent Expected indentation string + * @returns {void} + */ + function report(token, neededIndent) { + const actualIndent = Array.from(tokenInfo.getTokenIndent(token)); + const numSpaces = actualIndent.filter(char => char === " ").length; + const numTabs = actualIndent.filter(char => char === "\t").length; + + context.report({ + node: token, + messageId: "wrongIndentation", + data: createErrorMessageData(neededIndent.length, numSpaces, numTabs), + loc: { + start: { line: token.loc.start.line, column: 0 }, + end: { line: token.loc.start.line, column: token.loc.start.column } + }, + fix(fixer) { + const range = [token.range[0] - token.loc.start.column, token.range[0]]; + const newText = neededIndent; + + return fixer.replaceTextRange(range, newText); + } + }); + } + + /** + * Checks if a token's indentation is correct + * @param {Token} token Token to examine + * @param {string} desiredIndent Desired indentation of the string + * @returns {boolean} `true` if the token's indentation is correct + */ + function validateTokenIndent(token, desiredIndent) { + const indentation = tokenInfo.getTokenIndent(token); + + return indentation === desiredIndent || + + // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs. + indentation.includes(" ") && indentation.includes("\t"); + } + + /** + * Check to see if the node is a file level IIFE + * @param {ASTNode} node The function node to check. + * @returns {boolean} True if the node is the outer IIFE + */ + function isOuterIIFE(node) { + + /* + * Verify that the node is an IIFE + */ + if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) { + return false; + } + + /* + * Navigate legal ancestors to determine whether this IIFE is outer. + * A "legal ancestor" is an expression or statement that causes the function to get executed immediately. + * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator. + */ + let statement = node.parent && node.parent.parent; + + while ( + statement.type === "UnaryExpression" && ["!", "~", "+", "-"].includes(statement.operator) || + statement.type === "AssignmentExpression" || + statement.type === "LogicalExpression" || + statement.type === "SequenceExpression" || + statement.type === "VariableDeclarator" + ) { + statement = statement.parent; + } + + return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program"; + } + + /** + * Counts the number of linebreaks that follow the last non-whitespace character in a string + * @param {string} string The string to check + * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character, + * or the total number of linebreaks if the string is all whitespace. + */ + function countTrailingLinebreaks(string) { + const trailingWhitespace = string.match(/\s*$/u)[0]; + const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher()); + + return linebreakMatches === null ? 0 : linebreakMatches.length; + } + + /** + * Check indentation for lists of elements (arrays, objects, function params) + * @param {ASTNode[]} elements List of elements that should be offset + * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '[' + * @param {Token} endToken The end token of the list, e.g. ']' + * @param {number|string} offset The amount that the elements should be offset + * @returns {void} + */ + function addElementListIndent(elements, startToken, endToken, offset) { + + /** + * Gets the first token of a given element, including surrounding parentheses. + * @param {ASTNode} element A node in the `elements` list + * @returns {Token} The first token of this element + */ + function getFirstToken(element) { + let token = sourceCode.getTokenBefore(element); + + while (astUtils.isOpeningParenToken(token) && token !== startToken) { + token = sourceCode.getTokenBefore(token); + } + return sourceCode.getTokenAfter(token); + } + + // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden) + offsets.setDesiredOffsets( + [startToken.range[1], endToken.range[0]], + startToken, + typeof offset === "number" ? offset : 1 + ); + offsets.setDesiredOffset(endToken, startToken, 0); + + // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level. + if (offset === "first" && elements.length && !elements[0]) { + return; + } + elements.forEach((element, index) => { + if (!element) { + + // Skip holes in arrays + return; + } + if (offset === "off") { + + // Ignore the first token of every element if the "off" option is used + offsets.ignoreToken(getFirstToken(element)); + } + + // Offset the following elements correctly relative to the first element + if (index === 0) { + return; + } + if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) { + offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element)); + } else { + const previousElement = elements[index - 1]; + const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement); + const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement); + + if ( + previousElement && + previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line + ) { + offsets.setDesiredOffsets( + [previousElement.range[1], element.range[1]], + firstTokenOfPreviousElement, + 0 + ); + } + } + }); + } + + /** + * Check and decide whether to check for indentation for blockless nodes + * Scenarios are for or while statements without braces around them + * @param {ASTNode} node node to examine + * @returns {void} + */ + function addBlocklessNodeIndent(node) { + if (node.type !== "BlockStatement") { + const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken); + + let firstBodyToken = sourceCode.getFirstToken(node); + let lastBodyToken = sourceCode.getLastToken(node); + + while ( + astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) && + astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken)) + ) { + firstBodyToken = sourceCode.getTokenBefore(firstBodyToken); + lastBodyToken = sourceCode.getTokenAfter(lastBodyToken); + } + + offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1); + } + } + + /** + * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`) + * @param {ASTNode} node A CallExpression or NewExpression node + * @returns {void} + */ + function addFunctionCallIndent(node) { + let openingParen; + + if (node.arguments.length) { + openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken); + } else { + openingParen = sourceCode.getLastToken(node, 1); + } + const closingParen = sourceCode.getLastToken(node); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + + /* + * If `?.` token exists, set desired offset for that. + * This logic is copied from `MemberExpression`'s. + */ + if (node.optional) { + const dotToken = sourceCode.getTokenAfter(node.callee, astUtils.isQuestionDotToken); + const calleeParenCount = sourceCode.getTokensBetween(node.callee, dotToken, { filter: astUtils.isClosingParenToken }).length; + const firstTokenOfCallee = calleeParenCount + ? sourceCode.getTokenBefore(node.callee, { skip: calleeParenCount - 1 }) + : sourceCode.getFirstToken(node.callee); + const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken); + const offsetBase = lastTokenOfCallee.loc.end.line === openingParen.loc.start.line + ? lastTokenOfCallee + : firstTokenOfCallee; + + offsets.setDesiredOffset(dotToken, offsetBase, 1); + } + + const offsetAfterToken = node.callee.type === "TaggedTemplateExpression" ? sourceCode.getFirstToken(node.callee.quasi) : openingParen; + const offsetToken = sourceCode.getTokenBefore(offsetAfterToken); + + offsets.setDesiredOffset(openingParen, offsetToken, 0); + + addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments); + } + + /** + * Checks the indentation of parenthesized values, given a list of tokens in a program + * @param {Token[]} tokens A list of tokens + * @returns {void} + */ + function addParensIndent(tokens) { + const parenStack = []; + const parenPairs = []; + + for (let i = 0; i < tokens.length; i++) { + const nextToken = tokens[i]; + + if (astUtils.isOpeningParenToken(nextToken)) { + parenStack.push(nextToken); + } else if (astUtils.isClosingParenToken(nextToken)) { + parenPairs.push({ left: parenStack.pop(), right: nextToken }); + } + } + + for (let i = parenPairs.length - 1; i >= 0; i--) { + const leftParen = parenPairs[i].left; + const rightParen = parenPairs[i].right; + + // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments. + if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) { + const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen)); + + parenthesizedTokens.forEach(token => { + if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) { + offsets.setDesiredOffset(token, leftParen, 1); + } + }); + } + + offsets.setDesiredOffset(rightParen, leftParen, 0); + } + } + + /** + * Ignore all tokens within an unknown node whose offset do not depend + * on another token's offset within the unknown node + * @param {ASTNode} node Unknown Node + * @returns {void} + */ + function ignoreNode(node) { + const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true })); + + unknownNodeTokens.forEach(token => { + if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) { + const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token); + + if (token === firstTokenOfLine) { + offsets.ignoreToken(token); + } else { + offsets.setDesiredOffset(token, firstTokenOfLine, 0); + } + } + }); + } + + /** + * Check whether the given token is on the first line of a statement. + * @param {Token} token The token to check. + * @param {ASTNode} leafNode The expression node that the token belongs directly. + * @returns {boolean} `true` if the token is on the first line of a statement. + */ + function isOnFirstLineOfStatement(token, leafNode) { + let node = leafNode; + + while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) { + node = node.parent; + } + node = node.parent; + + return !node || node.loc.start.line === token.loc.start.line; + } + + /** + * Check whether there are any blank (whitespace-only) lines between + * two tokens on separate lines. + * @param {Token} firstToken The first token. + * @param {Token} secondToken The second token. + * @returns {boolean} `true` if the tokens are on separate lines and + * there exists a blank line between them, `false` otherwise. + */ + function hasBlankLinesBetween(firstToken, secondToken) { + const firstTokenLine = firstToken.loc.end.line; + const secondTokenLine = secondToken.loc.start.line; + + if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) { + return false; + } + + for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) { + if (!tokenInfo.firstTokensByLineNumber.has(line)) { + return true; + } + } + + return false; + } + + const ignoredNodeFirstTokens = new Set(); + + const baseOffsetListeners = { + "ArrayExpression, ArrayPattern"(node) { + const openingBracket = sourceCode.getFirstToken(node); + const closingBracket = sourceCode.getTokenAfter([...node.elements].reverse().find(_ => _) || openingBracket, astUtils.isClosingBracketToken); + + addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression); + }, + + "ObjectExpression, ObjectPattern"(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getTokenAfter( + node.properties.length ? node.properties[node.properties.length - 1] : openingCurly, + astUtils.isClosingBraceToken + ); + + addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression); + }, + + ArrowFunctionExpression(node) { + const maybeOpeningParen = sourceCode.getFirstToken(node, { skip: node.async ? 1 : 0 }); + + if (astUtils.isOpeningParenToken(maybeOpeningParen)) { + const openingParen = maybeOpeningParen; + const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters); + } + + addBlocklessNodeIndent(node.body); + }, + + AssignmentExpression(node) { + const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); + + offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1); + offsets.ignoreToken(operator); + offsets.ignoreToken(sourceCode.getTokenAfter(operator)); + }, + + "BinaryExpression, LogicalExpression"(node) { + const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); + + /* + * For backwards compatibility, don't check BinaryExpression indents, e.g. + * var foo = bar && + * baz; + */ + + const tokenAfterOperator = sourceCode.getTokenAfter(operator); + + offsets.ignoreToken(operator); + offsets.ignoreToken(tokenAfterOperator); + offsets.setDesiredOffset(tokenAfterOperator, operator, 0); + }, + + "BlockStatement, ClassBody"(node) { + let blockIndentLevel; + + if (node.parent && isOuterIIFE(node.parent)) { + blockIndentLevel = options.outerIIFEBody; + } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) { + blockIndentLevel = options.FunctionExpression.body; + } else if (node.parent && node.parent.type === "FunctionDeclaration") { + blockIndentLevel = options.FunctionDeclaration.body; + } else { + blockIndentLevel = 1; + } + + /* + * For blocks that aren't lone statements, ensure that the opening curly brace + * is aligned with the parent. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { + offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0); + } + + addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel); + }, + + CallExpression: addFunctionCallIndent, + + "ClassDeclaration[superClass], ClassExpression[superClass]"(node) { + const classToken = sourceCode.getFirstToken(node); + const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken); + + offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1); + }, + + ConditionalExpression(node) { + const firstToken = sourceCode.getFirstToken(node); + + // `flatTernaryExpressions` option is for the following style: + // var a = + // foo > 0 ? bar : + // foo < 0 ? baz : + // /*else*/ qiz ; + if (!options.flatTernaryExpressions || + !astUtils.isTokenOnSameLine(node.test, node.consequent) || + isOnFirstLineOfStatement(firstToken, node) + ) { + const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?"); + const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":"); + + const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken); + const lastConsequentToken = sourceCode.getTokenBefore(colonToken); + const firstAlternateToken = sourceCode.getTokenAfter(colonToken); + + offsets.setDesiredOffset(questionMarkToken, firstToken, 1); + offsets.setDesiredOffset(colonToken, firstToken, 1); + + offsets.setDesiredOffset(firstConsequentToken, firstToken, firstConsequentToken.type === "Punctuator" && + options.offsetTernaryExpressions ? 2 : 1); + + /* + * The alternate and the consequent should usually have the same indentation. + * If they share part of a line, align the alternate against the first token of the consequent. + * This allows the alternate to be indented correctly in cases like this: + * foo ? ( + * bar + * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo` + * baz // as a result, `baz` is offset by 1 rather than 2 + * ) + */ + if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) { + offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0); + } else { + + /** + * If the alternate and consequent do not share part of a line, offset the alternate from the first + * token of the conditional expression. For example: + * foo ? bar + * : baz + * + * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up + * having no expected indentation. + */ + offsets.setDesiredOffset(firstAlternateToken, firstToken, firstAlternateToken.type === "Punctuator" && + options.offsetTernaryExpressions ? 2 : 1); + } + } + }, + + "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement": node => addBlocklessNodeIndent(node.body), + + ExportNamedDeclaration(node) { + if (node.declaration === null) { + const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken); + + // Indent the specifiers in `export {foo, bar, baz}` + addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1); + + if (node.source) { + + // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'` + offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1); + } + } + }, + + ForStatement(node) { + const forOpeningParen = sourceCode.getFirstToken(node, 1); + + if (node.init) { + offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1); + } + if (node.test) { + offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1); + } + if (node.update) { + offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1); + } + addBlocklessNodeIndent(node.body); + }, + + "FunctionDeclaration, FunctionExpression"(node) { + const closingParen = sourceCode.getTokenBefore(node.body); + const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters); + }, + + IfStatement(node) { + addBlocklessNodeIndent(node.consequent); + if (node.alternate) { + addBlocklessNodeIndent(node.alternate); + } + }, + + /* + * For blockless nodes with semicolon-first style, don't indent the semicolon. + * e.g. + * if (foo) + * bar() + * ; [1, 2, 3].map(foo) + * + * Traversal into the node sets indentation of the semicolon, so we need to override it on exit. + */ + ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"(node) { + let nodesToCheck; + + if (node.type === "IfStatement") { + nodesToCheck = [node.consequent]; + if (node.alternate) { + nodesToCheck.push(node.alternate); + } + } else { + nodesToCheck = [node.body]; + } + + for (const nodeToCheck of nodesToCheck) { + const lastToken = sourceCode.getLastToken(nodeToCheck); + + if (astUtils.isSemicolonToken(lastToken)) { + const tokenBeforeLast = sourceCode.getTokenBefore(lastToken); + const tokenAfterLast = sourceCode.getTokenAfter(lastToken); + + // override indentation of `;` only if its line looks like a semicolon-first style line + if ( + !astUtils.isTokenOnSameLine(tokenBeforeLast, lastToken) && + tokenAfterLast && + astUtils.isTokenOnSameLine(lastToken, tokenAfterLast) + ) { + offsets.setDesiredOffset( + lastToken, + sourceCode.getFirstToken(node), + 0 + ); + } + } + } + }, + + ImportDeclaration(node) { + if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) { + const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken); + const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken); + + addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration); + } + + const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from"); + const sourceToken = sourceCode.getLastToken(node, token => token.type === "String"); + const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";"); + + if (fromToken) { + const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1]; + + offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1); + } + }, + + ImportExpression(node) { + const openingParen = sourceCode.getFirstToken(node, 1); + const closingParen = sourceCode.getLastToken(node); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0); + + addElementListIndent([node.source], openingParen, closingParen, options.CallExpression.arguments); + }, + + "MemberExpression, JSXMemberExpression, MetaProperty"(node) { + const object = node.type === "MetaProperty" ? node.meta : node.object; + const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken); + const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken); + + const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length; + const firstObjectToken = objectParenCount + ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 }) + : sourceCode.getFirstToken(object); + const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken); + const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken; + + if (node.computed) { + + // For computed MemberExpressions, match the closing bracket with the opening bracket. + offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0); + offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1); + } + + /* + * If the object ends on the same line that the property starts, match against the last token + * of the object, to ensure that the MemberExpression is not indented. + * + * Otherwise, match against the first token of the object, e.g. + * foo + * .bar + * .baz // <-- offset by 1 from `foo` + */ + const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line + ? lastObjectToken + : firstObjectToken; + + if (typeof options.MemberExpression === "number") { + + // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object. + offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression); + + /* + * For computed MemberExpressions, match the first token of the property against the opening bracket. + * Otherwise, match the first token of the property against the object. + */ + offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression); + } else { + + // If the MemberExpression option is off, ignore the dot and the first token of the property. + offsets.ignoreToken(firstNonObjectToken); + offsets.ignoreToken(secondNonObjectToken); + + // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens. + offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0); + offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0); + } + }, + + NewExpression(node) { + + // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo` + if (node.arguments.length > 0 || + astUtils.isClosingParenToken(sourceCode.getLastToken(node)) && + astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) { + addFunctionCallIndent(node); + } + }, + + Property(node) { + if (!node.shorthand && !node.method && node.kind === "init") { + const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken); + + offsets.ignoreToken(sourceCode.getTokenAfter(colon)); + } + }, + + PropertyDefinition(node) { + const firstToken = sourceCode.getFirstToken(node); + const maybeSemicolonToken = sourceCode.getLastToken(node); + let keyLastToken = null; + + // Indent key. + if (node.computed) { + const bracketTokenL = sourceCode.getTokenBefore(node.key, astUtils.isOpeningBracketToken); + const bracketTokenR = keyLastToken = sourceCode.getTokenAfter(node.key, astUtils.isClosingBracketToken); + const keyRange = [bracketTokenL.range[1], bracketTokenR.range[0]]; + + if (bracketTokenL !== firstToken) { + offsets.setDesiredOffset(bracketTokenL, firstToken, 0); + } + offsets.setDesiredOffsets(keyRange, bracketTokenL, 1); + offsets.setDesiredOffset(bracketTokenR, bracketTokenL, 0); + } else { + const idToken = keyLastToken = sourceCode.getFirstToken(node.key); + + if (idToken !== firstToken) { + offsets.setDesiredOffset(idToken, firstToken, 1); + } + } + + // Indent initializer. + if (node.value) { + const eqToken = sourceCode.getTokenBefore(node.value, astUtils.isEqToken); + const valueToken = sourceCode.getTokenAfter(eqToken); + + offsets.setDesiredOffset(eqToken, keyLastToken, 1); + offsets.setDesiredOffset(valueToken, eqToken, 1); + if (astUtils.isSemicolonToken(maybeSemicolonToken)) { + offsets.setDesiredOffset(maybeSemicolonToken, eqToken, 1); + } + } else if (astUtils.isSemicolonToken(maybeSemicolonToken)) { + offsets.setDesiredOffset(maybeSemicolonToken, keyLastToken, 1); + } + }, + + StaticBlock(node) { + const openingCurly = sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token + const closingCurly = sourceCode.getLastToken(node); + + addElementListIndent(node.body, openingCurly, closingCurly, options.StaticBlock.body); + }, + + SwitchStatement(node) { + const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase); + + if (node.cases.length) { + sourceCode.getTokensBetween( + node.cases[node.cases.length - 1], + closingCurly, + { includeComments: true, filter: astUtils.isCommentToken } + ).forEach(token => offsets.ignoreToken(token)); + } + }, + + SwitchCase(node) { + if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) { + const caseKeyword = sourceCode.getFirstToken(node); + const tokenAfterCurrentCase = sourceCode.getTokenAfter(node); + + offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1); + } + }, + + TemplateLiteral(node) { + node.expressions.forEach((expression, index) => { + const previousQuasi = node.quasis[index]; + const nextQuasi = node.quasis[index + 1]; + const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line + ? sourceCode.getFirstToken(previousQuasi) + : null; + + offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1); + offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0); + }); + }, + + VariableDeclaration(node) { + let variableIndent = Object.prototype.hasOwnProperty.call(options.VariableDeclarator, node.kind) + ? options.VariableDeclarator[node.kind] + : DEFAULT_VARIABLE_INDENT; + + const firstToken = sourceCode.getFirstToken(node), + lastToken = sourceCode.getLastToken(node); + + if (options.VariableDeclarator[node.kind] === "first") { + if (node.declarations.length > 1) { + addElementListIndent( + node.declarations, + firstToken, + lastToken, + "first" + ); + return; + } + + variableIndent = DEFAULT_VARIABLE_INDENT; + } + + if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) { + + /* + * VariableDeclarator indentation is a bit different from other forms of indentation, in that the + * indentation of an opening bracket sometimes won't match that of a closing bracket. For example, + * the following indentations are correct: + * + * var foo = { + * ok: true + * }; + * + * var foo = { + * ok: true, + * }, + * bar = 1; + * + * Account for when exiting the AST (after indentations have already been set for the nodes in + * the declaration) by manually increasing the indentation level of the tokens in this declarator + * on the same line as the start of the declaration, provided that there are declarators that + * follow this one. + */ + offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true); + } else { + offsets.setDesiredOffsets(node.range, firstToken, variableIndent); + } + + if (astUtils.isSemicolonToken(lastToken)) { + offsets.ignoreToken(lastToken); + } + }, + + VariableDeclarator(node) { + if (node.init) { + const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken); + const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator); + + offsets.ignoreToken(equalOperator); + offsets.ignoreToken(tokenAfterOperator); + offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1); + offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0); + } + }, + + "JSXAttribute[value]"(node) { + const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "="); + + offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1); + }, + + JSXElement(node) { + if (node.closingElement) { + addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1); + } + }, + + JSXOpeningElement(node) { + const firstToken = sourceCode.getFirstToken(node); + let closingToken; + + if (node.selfClosing) { + closingToken = sourceCode.getLastToken(node, { skip: 1 }); + offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0); + } else { + closingToken = sourceCode.getLastToken(node); + } + offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node)); + addElementListIndent(node.attributes, firstToken, closingToken, 1); + }, + + JSXClosingElement(node) { + const firstToken = sourceCode.getFirstToken(node); + + offsets.setDesiredOffsets(node.name.range, firstToken, 1); + }, + + JSXFragment(node) { + const firstOpeningToken = sourceCode.getFirstToken(node.openingFragment); + const firstClosingToken = sourceCode.getFirstToken(node.closingFragment); + + addElementListIndent(node.children, firstOpeningToken, firstClosingToken, 1); + }, + + JSXOpeningFragment(node) { + const firstToken = sourceCode.getFirstToken(node); + const closingToken = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets(node.range, firstToken, 1); + offsets.matchOffsetOf(firstToken, closingToken); + }, + + JSXClosingFragment(node) { + const firstToken = sourceCode.getFirstToken(node); + const slashToken = sourceCode.getLastToken(node, { skip: 1 }); + const closingToken = sourceCode.getLastToken(node); + const tokenToMatch = astUtils.isTokenOnSameLine(slashToken, closingToken) ? slashToken : closingToken; + + offsets.setDesiredOffsets(node.range, firstToken, 1); + offsets.matchOffsetOf(firstToken, tokenToMatch); + }, + + JSXExpressionContainer(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets( + [openingCurly.range[1], closingCurly.range[0]], + openingCurly, + 1 + ); + }, + + JSXSpreadAttribute(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets( + [openingCurly.range[1], closingCurly.range[0]], + openingCurly, + 1 + ); + }, + + "*"(node) { + const firstToken = sourceCode.getFirstToken(node); + + // Ensure that the children of every node are indented at least as much as the first token. + if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) { + offsets.setDesiredOffsets(node.range, firstToken, 0); + } + } + }; + + const listenerCallQueue = []; + + /* + * To ignore the indentation of a node: + * 1. Don't call the node's listener when entering it (if it has a listener) + * 2. Don't set any offsets against the first token of the node. + * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets. + */ + const offsetListeners = {}; + + for (const [selector, listener] of Object.entries(baseOffsetListeners)) { + + /* + * Offset listener calls are deferred until traversal is finished, and are called as + * part of the final `Program:exit` listener. This is necessary because a node might + * be matched by multiple selectors. + * + * Example: Suppose there is an offset listener for `Identifier`, and the user has + * specified in configuration that `MemberExpression > Identifier` should be ignored. + * Due to selector specificity rules, the `Identifier` listener will get called first. However, + * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener + * should not have been called at all. Without doing extra selector matching, we don't know + * whether the Identifier matches the `MemberExpression > Identifier` selector until the + * `MemberExpression > Identifier` listener is called. + * + * To avoid this, the `Identifier` listener isn't called until traversal finishes and all + * ignored nodes are known. + */ + offsetListeners[selector] = node => listenerCallQueue.push({ listener, node }); + } + + // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set. + const ignoredNodes = new Set(); + + /** + * Ignores a node + * @param {ASTNode} node The node to ignore + * @returns {void} + */ + function addToIgnoredNodes(node) { + ignoredNodes.add(node); + ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node)); + } + + const ignoredNodeListeners = options.ignoredNodes.reduce( + (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }), + {} + ); + + /* + * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation + * at the end. + * + * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears + * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored, + * so those listeners wouldn't be called anyway. + */ + return Object.assign( + offsetListeners, + ignoredNodeListeners, + { + "*:exit"(node) { + + // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it. + if (!KNOWN_NODES.has(node.type)) { + addToIgnoredNodes(node); + } + }, + "Program:exit"() { + + // If ignoreComments option is enabled, ignore all comment tokens. + if (options.ignoreComments) { + sourceCode.getAllComments() + .forEach(comment => offsets.ignoreToken(comment)); + } + + // Invoke the queued offset listeners for the nodes that aren't ignored. + for (let i = 0; i < listenerCallQueue.length; i++) { + const nodeInfo = listenerCallQueue[i]; + + if (!ignoredNodes.has(nodeInfo.node)) { + nodeInfo.listener(nodeInfo.node); + } + } + + // Update the offsets for ignored nodes to prevent their child tokens from being reported. + ignoredNodes.forEach(ignoreNode); + + addParensIndent(sourceCode.ast.tokens); + + /* + * Create a Map from (tokenOrComment) => (precedingToken). + * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly. + */ + const precedingTokens = new WeakMap(); + + for (let i = 0; i < sourceCode.ast.comments.length; i++) { + const comment = sourceCode.ast.comments[i]; + + const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); + const hasToken = precedingTokens.has(tokenOrCommentBefore) ? precedingTokens.get(tokenOrCommentBefore) : tokenOrCommentBefore; + + precedingTokens.set(comment, hasToken); + } + + for (let i = 1; i < sourceCode.lines.length + 1; i++) { + + if (!tokenInfo.firstTokensByLineNumber.has(i)) { + + // Don't check indentation on blank lines + continue; + } + + const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(i); + + if (firstTokenOfLine.loc.start.line !== i) { + + // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice. + continue; + } + + if (astUtils.isCommentToken(firstTokenOfLine)) { + const tokenBefore = precedingTokens.get(firstTokenOfLine); + const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0]; + const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine); + const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter); + + /* + * If a comment precedes a line that begins with a semicolon token, align to that token, i.e. + * + * let foo + * // comment + * ;(async () => {})() + */ + if (tokenAfter && astUtils.isSemicolonToken(tokenAfter) && !astUtils.isTokenOnSameLine(firstTokenOfLine, tokenAfter)) { + offsets.setDesiredOffset(firstTokenOfLine, tokenAfter, 0); + } + + // If a comment matches the expected indentation of the token immediately before or after, don't report it. + if ( + mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) || + mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter)) + ) { + continue; + } + } + + // If the token matches the expected indentation, don't report it. + if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) { + continue; + } + + // Otherwise, report the token/comment. + report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine)); + } + } + } + ); + } +}; diff --git a/node_modules/eslint/lib/rules/index.js b/node_modules/eslint/lib/rules/index.js new file mode 100644 index 0000000..e426396 --- /dev/null +++ b/node_modules/eslint/lib/rules/index.js @@ -0,0 +1,305 @@ +/** + * @fileoverview Collects the built-in rules into a map structure so that they can be imported all at once and without + * using the file-system directly. + * @author Peter (Somogyvari) Metz + */ + +"use strict"; + +/* eslint sort-keys: ["error", "asc"] -- More readable for long list */ + +const { LazyLoadingRuleMap } = require("./utils/lazy-loading-rule-map"); + +/** @type {Map} */ +module.exports = new LazyLoadingRuleMap(Object.entries({ + "accessor-pairs": () => require("./accessor-pairs"), + "array-bracket-newline": () => require("./array-bracket-newline"), + "array-bracket-spacing": () => require("./array-bracket-spacing"), + "array-callback-return": () => require("./array-callback-return"), + "array-element-newline": () => require("./array-element-newline"), + "arrow-body-style": () => require("./arrow-body-style"), + "arrow-parens": () => require("./arrow-parens"), + "arrow-spacing": () => require("./arrow-spacing"), + "block-scoped-var": () => require("./block-scoped-var"), + "block-spacing": () => require("./block-spacing"), + "brace-style": () => require("./brace-style"), + "callback-return": () => require("./callback-return"), + camelcase: () => require("./camelcase"), + "capitalized-comments": () => require("./capitalized-comments"), + "class-methods-use-this": () => require("./class-methods-use-this"), + "comma-dangle": () => require("./comma-dangle"), + "comma-spacing": () => require("./comma-spacing"), + "comma-style": () => require("./comma-style"), + complexity: () => require("./complexity"), + "computed-property-spacing": () => require("./computed-property-spacing"), + "consistent-return": () => require("./consistent-return"), + "consistent-this": () => require("./consistent-this"), + "constructor-super": () => require("./constructor-super"), + curly: () => require("./curly"), + "default-case": () => require("./default-case"), + "default-case-last": () => require("./default-case-last"), + "default-param-last": () => require("./default-param-last"), + "dot-location": () => require("./dot-location"), + "dot-notation": () => require("./dot-notation"), + "eol-last": () => require("./eol-last"), + eqeqeq: () => require("./eqeqeq"), + "for-direction": () => require("./for-direction"), + "func-call-spacing": () => require("./func-call-spacing"), + "func-name-matching": () => require("./func-name-matching"), + "func-names": () => require("./func-names"), + "func-style": () => require("./func-style"), + "function-call-argument-newline": () => require("./function-call-argument-newline"), + "function-paren-newline": () => require("./function-paren-newline"), + "generator-star-spacing": () => require("./generator-star-spacing"), + "getter-return": () => require("./getter-return"), + "global-require": () => require("./global-require"), + "grouped-accessor-pairs": () => require("./grouped-accessor-pairs"), + "guard-for-in": () => require("./guard-for-in"), + "handle-callback-err": () => require("./handle-callback-err"), + "id-blacklist": () => require("./id-blacklist"), + "id-denylist": () => require("./id-denylist"), + "id-length": () => require("./id-length"), + "id-match": () => require("./id-match"), + "implicit-arrow-linebreak": () => require("./implicit-arrow-linebreak"), + indent: () => require("./indent"), + "indent-legacy": () => require("./indent-legacy"), + "init-declarations": () => require("./init-declarations"), + "jsx-quotes": () => require("./jsx-quotes"), + "key-spacing": () => require("./key-spacing"), + "keyword-spacing": () => require("./keyword-spacing"), + "line-comment-position": () => require("./line-comment-position"), + "linebreak-style": () => require("./linebreak-style"), + "lines-around-comment": () => require("./lines-around-comment"), + "lines-around-directive": () => require("./lines-around-directive"), + "lines-between-class-members": () => require("./lines-between-class-members"), + "logical-assignment-operators": () => require("./logical-assignment-operators"), + "max-classes-per-file": () => require("./max-classes-per-file"), + "max-depth": () => require("./max-depth"), + "max-len": () => require("./max-len"), + "max-lines": () => require("./max-lines"), + "max-lines-per-function": () => require("./max-lines-per-function"), + "max-nested-callbacks": () => require("./max-nested-callbacks"), + "max-params": () => require("./max-params"), + "max-statements": () => require("./max-statements"), + "max-statements-per-line": () => require("./max-statements-per-line"), + "multiline-comment-style": () => require("./multiline-comment-style"), + "multiline-ternary": () => require("./multiline-ternary"), + "new-cap": () => require("./new-cap"), + "new-parens": () => require("./new-parens"), + "newline-after-var": () => require("./newline-after-var"), + "newline-before-return": () => require("./newline-before-return"), + "newline-per-chained-call": () => require("./newline-per-chained-call"), + "no-alert": () => require("./no-alert"), + "no-array-constructor": () => require("./no-array-constructor"), + "no-async-promise-executor": () => require("./no-async-promise-executor"), + "no-await-in-loop": () => require("./no-await-in-loop"), + "no-bitwise": () => require("./no-bitwise"), + "no-buffer-constructor": () => require("./no-buffer-constructor"), + "no-caller": () => require("./no-caller"), + "no-case-declarations": () => require("./no-case-declarations"), + "no-catch-shadow": () => require("./no-catch-shadow"), + "no-class-assign": () => require("./no-class-assign"), + "no-compare-neg-zero": () => require("./no-compare-neg-zero"), + "no-cond-assign": () => require("./no-cond-assign"), + "no-confusing-arrow": () => require("./no-confusing-arrow"), + "no-console": () => require("./no-console"), + "no-const-assign": () => require("./no-const-assign"), + "no-constant-binary-expression": () => require("./no-constant-binary-expression"), + "no-constant-condition": () => require("./no-constant-condition"), + "no-constructor-return": () => require("./no-constructor-return"), + "no-continue": () => require("./no-continue"), + "no-control-regex": () => require("./no-control-regex"), + "no-debugger": () => require("./no-debugger"), + "no-delete-var": () => require("./no-delete-var"), + "no-div-regex": () => require("./no-div-regex"), + "no-dupe-args": () => require("./no-dupe-args"), + "no-dupe-class-members": () => require("./no-dupe-class-members"), + "no-dupe-else-if": () => require("./no-dupe-else-if"), + "no-dupe-keys": () => require("./no-dupe-keys"), + "no-duplicate-case": () => require("./no-duplicate-case"), + "no-duplicate-imports": () => require("./no-duplicate-imports"), + "no-else-return": () => require("./no-else-return"), + "no-empty": () => require("./no-empty"), + "no-empty-character-class": () => require("./no-empty-character-class"), + "no-empty-function": () => require("./no-empty-function"), + "no-empty-pattern": () => require("./no-empty-pattern"), + "no-empty-static-block": () => require("./no-empty-static-block"), + "no-eq-null": () => require("./no-eq-null"), + "no-eval": () => require("./no-eval"), + "no-ex-assign": () => require("./no-ex-assign"), + "no-extend-native": () => require("./no-extend-native"), + "no-extra-bind": () => require("./no-extra-bind"), + "no-extra-boolean-cast": () => require("./no-extra-boolean-cast"), + "no-extra-label": () => require("./no-extra-label"), + "no-extra-parens": () => require("./no-extra-parens"), + "no-extra-semi": () => require("./no-extra-semi"), + "no-fallthrough": () => require("./no-fallthrough"), + "no-floating-decimal": () => require("./no-floating-decimal"), + "no-func-assign": () => require("./no-func-assign"), + "no-global-assign": () => require("./no-global-assign"), + "no-implicit-coercion": () => require("./no-implicit-coercion"), + "no-implicit-globals": () => require("./no-implicit-globals"), + "no-implied-eval": () => require("./no-implied-eval"), + "no-import-assign": () => require("./no-import-assign"), + "no-inline-comments": () => require("./no-inline-comments"), + "no-inner-declarations": () => require("./no-inner-declarations"), + "no-invalid-regexp": () => require("./no-invalid-regexp"), + "no-invalid-this": () => require("./no-invalid-this"), + "no-irregular-whitespace": () => require("./no-irregular-whitespace"), + "no-iterator": () => require("./no-iterator"), + "no-label-var": () => require("./no-label-var"), + "no-labels": () => require("./no-labels"), + "no-lone-blocks": () => require("./no-lone-blocks"), + "no-lonely-if": () => require("./no-lonely-if"), + "no-loop-func": () => require("./no-loop-func"), + "no-loss-of-precision": () => require("./no-loss-of-precision"), + "no-magic-numbers": () => require("./no-magic-numbers"), + "no-misleading-character-class": () => require("./no-misleading-character-class"), + "no-mixed-operators": () => require("./no-mixed-operators"), + "no-mixed-requires": () => require("./no-mixed-requires"), + "no-mixed-spaces-and-tabs": () => require("./no-mixed-spaces-and-tabs"), + "no-multi-assign": () => require("./no-multi-assign"), + "no-multi-spaces": () => require("./no-multi-spaces"), + "no-multi-str": () => require("./no-multi-str"), + "no-multiple-empty-lines": () => require("./no-multiple-empty-lines"), + "no-native-reassign": () => require("./no-native-reassign"), + "no-negated-condition": () => require("./no-negated-condition"), + "no-negated-in-lhs": () => require("./no-negated-in-lhs"), + "no-nested-ternary": () => require("./no-nested-ternary"), + "no-new": () => require("./no-new"), + "no-new-func": () => require("./no-new-func"), + "no-new-native-nonconstructor": () => require("./no-new-native-nonconstructor"), + "no-new-object": () => require("./no-new-object"), + "no-new-require": () => require("./no-new-require"), + "no-new-symbol": () => require("./no-new-symbol"), + "no-new-wrappers": () => require("./no-new-wrappers"), + "no-nonoctal-decimal-escape": () => require("./no-nonoctal-decimal-escape"), + "no-obj-calls": () => require("./no-obj-calls"), + "no-octal": () => require("./no-octal"), + "no-octal-escape": () => require("./no-octal-escape"), + "no-param-reassign": () => require("./no-param-reassign"), + "no-path-concat": () => require("./no-path-concat"), + "no-plusplus": () => require("./no-plusplus"), + "no-process-env": () => require("./no-process-env"), + "no-process-exit": () => require("./no-process-exit"), + "no-promise-executor-return": () => require("./no-promise-executor-return"), + "no-proto": () => require("./no-proto"), + "no-prototype-builtins": () => require("./no-prototype-builtins"), + "no-redeclare": () => require("./no-redeclare"), + "no-regex-spaces": () => require("./no-regex-spaces"), + "no-restricted-exports": () => require("./no-restricted-exports"), + "no-restricted-globals": () => require("./no-restricted-globals"), + "no-restricted-imports": () => require("./no-restricted-imports"), + "no-restricted-modules": () => require("./no-restricted-modules"), + "no-restricted-properties": () => require("./no-restricted-properties"), + "no-restricted-syntax": () => require("./no-restricted-syntax"), + "no-return-assign": () => require("./no-return-assign"), + "no-return-await": () => require("./no-return-await"), + "no-script-url": () => require("./no-script-url"), + "no-self-assign": () => require("./no-self-assign"), + "no-self-compare": () => require("./no-self-compare"), + "no-sequences": () => require("./no-sequences"), + "no-setter-return": () => require("./no-setter-return"), + "no-shadow": () => require("./no-shadow"), + "no-shadow-restricted-names": () => require("./no-shadow-restricted-names"), + "no-spaced-func": () => require("./no-spaced-func"), + "no-sparse-arrays": () => require("./no-sparse-arrays"), + "no-sync": () => require("./no-sync"), + "no-tabs": () => require("./no-tabs"), + "no-template-curly-in-string": () => require("./no-template-curly-in-string"), + "no-ternary": () => require("./no-ternary"), + "no-this-before-super": () => require("./no-this-before-super"), + "no-throw-literal": () => require("./no-throw-literal"), + "no-trailing-spaces": () => require("./no-trailing-spaces"), + "no-undef": () => require("./no-undef"), + "no-undef-init": () => require("./no-undef-init"), + "no-undefined": () => require("./no-undefined"), + "no-underscore-dangle": () => require("./no-underscore-dangle"), + "no-unexpected-multiline": () => require("./no-unexpected-multiline"), + "no-unmodified-loop-condition": () => require("./no-unmodified-loop-condition"), + "no-unneeded-ternary": () => require("./no-unneeded-ternary"), + "no-unreachable": () => require("./no-unreachable"), + "no-unreachable-loop": () => require("./no-unreachable-loop"), + "no-unsafe-finally": () => require("./no-unsafe-finally"), + "no-unsafe-negation": () => require("./no-unsafe-negation"), + "no-unsafe-optional-chaining": () => require("./no-unsafe-optional-chaining"), + "no-unused-expressions": () => require("./no-unused-expressions"), + "no-unused-labels": () => require("./no-unused-labels"), + "no-unused-private-class-members": () => require("./no-unused-private-class-members"), + "no-unused-vars": () => require("./no-unused-vars"), + "no-use-before-define": () => require("./no-use-before-define"), + "no-useless-backreference": () => require("./no-useless-backreference"), + "no-useless-call": () => require("./no-useless-call"), + "no-useless-catch": () => require("./no-useless-catch"), + "no-useless-computed-key": () => require("./no-useless-computed-key"), + "no-useless-concat": () => require("./no-useless-concat"), + "no-useless-constructor": () => require("./no-useless-constructor"), + "no-useless-escape": () => require("./no-useless-escape"), + "no-useless-rename": () => require("./no-useless-rename"), + "no-useless-return": () => require("./no-useless-return"), + "no-var": () => require("./no-var"), + "no-void": () => require("./no-void"), + "no-warning-comments": () => require("./no-warning-comments"), + "no-whitespace-before-property": () => require("./no-whitespace-before-property"), + "no-with": () => require("./no-with"), + "nonblock-statement-body-position": () => require("./nonblock-statement-body-position"), + "object-curly-newline": () => require("./object-curly-newline"), + "object-curly-spacing": () => require("./object-curly-spacing"), + "object-property-newline": () => require("./object-property-newline"), + "object-shorthand": () => require("./object-shorthand"), + "one-var": () => require("./one-var"), + "one-var-declaration-per-line": () => require("./one-var-declaration-per-line"), + "operator-assignment": () => require("./operator-assignment"), + "operator-linebreak": () => require("./operator-linebreak"), + "padded-blocks": () => require("./padded-blocks"), + "padding-line-between-statements": () => require("./padding-line-between-statements"), + "prefer-arrow-callback": () => require("./prefer-arrow-callback"), + "prefer-const": () => require("./prefer-const"), + "prefer-destructuring": () => require("./prefer-destructuring"), + "prefer-exponentiation-operator": () => require("./prefer-exponentiation-operator"), + "prefer-named-capture-group": () => require("./prefer-named-capture-group"), + "prefer-numeric-literals": () => require("./prefer-numeric-literals"), + "prefer-object-has-own": () => require("./prefer-object-has-own"), + "prefer-object-spread": () => require("./prefer-object-spread"), + "prefer-promise-reject-errors": () => require("./prefer-promise-reject-errors"), + "prefer-reflect": () => require("./prefer-reflect"), + "prefer-regex-literals": () => require("./prefer-regex-literals"), + "prefer-rest-params": () => require("./prefer-rest-params"), + "prefer-spread": () => require("./prefer-spread"), + "prefer-template": () => require("./prefer-template"), + "quote-props": () => require("./quote-props"), + quotes: () => require("./quotes"), + radix: () => require("./radix"), + "require-atomic-updates": () => require("./require-atomic-updates"), + "require-await": () => require("./require-await"), + "require-jsdoc": () => require("./require-jsdoc"), + "require-unicode-regexp": () => require("./require-unicode-regexp"), + "require-yield": () => require("./require-yield"), + "rest-spread-spacing": () => require("./rest-spread-spacing"), + semi: () => require("./semi"), + "semi-spacing": () => require("./semi-spacing"), + "semi-style": () => require("./semi-style"), + "sort-imports": () => require("./sort-imports"), + "sort-keys": () => require("./sort-keys"), + "sort-vars": () => require("./sort-vars"), + "space-before-blocks": () => require("./space-before-blocks"), + "space-before-function-paren": () => require("./space-before-function-paren"), + "space-in-parens": () => require("./space-in-parens"), + "space-infix-ops": () => require("./space-infix-ops"), + "space-unary-ops": () => require("./space-unary-ops"), + "spaced-comment": () => require("./spaced-comment"), + strict: () => require("./strict"), + "switch-colon-spacing": () => require("./switch-colon-spacing"), + "symbol-description": () => require("./symbol-description"), + "template-curly-spacing": () => require("./template-curly-spacing"), + "template-tag-spacing": () => require("./template-tag-spacing"), + "unicode-bom": () => require("./unicode-bom"), + "use-isnan": () => require("./use-isnan"), + "valid-jsdoc": () => require("./valid-jsdoc"), + "valid-typeof": () => require("./valid-typeof"), + "vars-on-top": () => require("./vars-on-top"), + "wrap-iife": () => require("./wrap-iife"), + "wrap-regex": () => require("./wrap-regex"), + "yield-star-spacing": () => require("./yield-star-spacing"), + yoda: () => require("./yoda") +})); diff --git a/node_modules/eslint/lib/rules/init-declarations.js b/node_modules/eslint/lib/rules/init-declarations.js new file mode 100644 index 0000000..3abe107 --- /dev/null +++ b/node_modules/eslint/lib/rules/init-declarations.js @@ -0,0 +1,139 @@ +/** + * @fileoverview A rule to control the style of variable initializations. + * @author Colin Ihrig + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a for loop. + * @param {ASTNode} block A node to check. + * @returns {boolean} `true` when the node is a for loop. + */ +function isForLoop(block) { + return block.type === "ForInStatement" || + block.type === "ForOfStatement" || + block.type === "ForStatement"; +} + +/** + * Checks whether or not a given declarator node has its initializer. + * @param {ASTNode} node A declarator node to check. + * @returns {boolean} `true` when the node has its initializer. + */ +function isInitialized(node) { + const declaration = node.parent; + const block = declaration.parent; + + if (isForLoop(block)) { + if (block.type === "ForStatement") { + return block.init === declaration; + } + return block.left === declaration; + } + return Boolean(node.init); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require or disallow initialization in variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/init-declarations" + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always"] + } + ], + minItems: 0, + maxItems: 1 + }, + { + type: "array", + items: [ + { + enum: ["never"] + }, + { + type: "object", + properties: { + ignoreForLoopInit: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + } + ] + }, + messages: { + initialized: "Variable '{{idName}}' should be initialized on declaration.", + notInitialized: "Variable '{{idName}}' should not be initialized on declaration." + } + }, + + create(context) { + + const MODE_ALWAYS = "always", + MODE_NEVER = "never"; + + const mode = context.options[0] || MODE_ALWAYS; + const params = context.options[1] || {}; + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration:exit"(node) { + + const kind = node.kind, + declarations = node.declarations; + + for (let i = 0; i < declarations.length; ++i) { + const declaration = declarations[i], + id = declaration.id, + initialized = isInitialized(declaration), + isIgnoredForLoop = params.ignoreForLoopInit && isForLoop(node.parent); + let messageId = ""; + + if (mode === MODE_ALWAYS && !initialized) { + messageId = "initialized"; + } else if (mode === MODE_NEVER && kind !== "const" && initialized && !isIgnoredForLoop) { + messageId = "notInitialized"; + } + + if (id.type === "Identifier" && messageId) { + context.report({ + node: declaration, + messageId, + data: { + idName: id.name + } + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/jsx-quotes.js b/node_modules/eslint/lib/rules/jsx-quotes.js new file mode 100644 index 0000000..a41c851 --- /dev/null +++ b/node_modules/eslint/lib/rules/jsx-quotes.js @@ -0,0 +1,95 @@ +/** + * @fileoverview A rule to ensure consistent quotes used in jsx syntax. + * @author Mathias Schreck + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const QUOTE_SETTINGS = { + "prefer-double": { + quote: "\"", + description: "singlequote", + convert(str) { + return str.replace(/'/gu, "\""); + } + }, + "prefer-single": { + quote: "'", + description: "doublequote", + convert(str) { + return str.replace(/"/gu, "'"); + } + } +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce the consistent use of either double or single quotes in JSX attributes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/jsx-quotes" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["prefer-single", "prefer-double"] + } + ], + messages: { + unexpected: "Unexpected usage of {{description}}." + } + }, + + create(context) { + const quoteOption = context.options[0] || "prefer-double", + setting = QUOTE_SETTINGS[quoteOption]; + + /** + * Checks if the given string literal node uses the expected quotes + * @param {ASTNode} node A string literal node. + * @returns {boolean} Whether or not the string literal used the expected quotes. + * @public + */ + function usesExpectedQuotes(node) { + return node.value.includes(setting.quote) || astUtils.isSurroundedBy(node.raw, setting.quote); + } + + return { + JSXAttribute(node) { + const attributeValue = node.value; + + if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) { + context.report({ + node: attributeValue, + messageId: "unexpected", + data: { + description: setting.description + }, + fix(fixer) { + return fixer.replaceText(attributeValue, setting.convert(attributeValue.raw)); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/key-spacing.js b/node_modules/eslint/lib/rules/key-spacing.js new file mode 100644 index 0000000..0b51eb3 --- /dev/null +++ b/node_modules/eslint/lib/rules/key-spacing.js @@ -0,0 +1,684 @@ +/** + * @fileoverview Rule to specify spacing of object literal keys and values + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { getGraphemeCount } = require("../shared/string-utils"); + +/** + * Checks whether a string contains a line terminator as defined in + * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3 + * @param {string} str String to test. + * @returns {boolean} True if str contains a line terminator. + */ +function containsLineTerminator(str) { + return astUtils.LINEBREAK_MATCHER.test(str); +} + +/** + * Gets the last element of an array. + * @param {Array} arr An array. + * @returns {any} Last element of arr. + */ +function last(arr) { + return arr[arr.length - 1]; +} + +/** + * Checks whether a node is contained on a single line. + * @param {ASTNode} node AST Node being evaluated. + * @returns {boolean} True if the node is a single line. + */ +function isSingleLine(node) { + return (node.loc.end.line === node.loc.start.line); +} + +/** + * Checks whether the properties on a single line. + * @param {ASTNode[]} properties List of Property AST nodes. + * @returns {boolean} True if all properties is on a single line. + */ +function isSingleLineProperties(properties) { + const [firstProp] = properties, + lastProp = last(properties); + + return firstProp.loc.start.line === lastProp.loc.end.line; +} + +/** + * Initializes a single option property from the configuration with defaults for undefined values + * @param {Object} toOptions Object to be initialized + * @param {Object} fromOptions Object to be initialized from + * @returns {Object} The object with correctly initialized options and values + */ +function initOptionProperty(toOptions, fromOptions) { + toOptions.mode = fromOptions.mode || "strict"; + + // Set value of beforeColon + if (typeof fromOptions.beforeColon !== "undefined") { + toOptions.beforeColon = +fromOptions.beforeColon; + } else { + toOptions.beforeColon = 0; + } + + // Set value of afterColon + if (typeof fromOptions.afterColon !== "undefined") { + toOptions.afterColon = +fromOptions.afterColon; + } else { + toOptions.afterColon = 1; + } + + // Set align if exists + if (typeof fromOptions.align !== "undefined") { + if (typeof fromOptions.align === "object") { + toOptions.align = fromOptions.align; + } else { // "string" + toOptions.align = { + on: fromOptions.align, + mode: toOptions.mode, + beforeColon: toOptions.beforeColon, + afterColon: toOptions.afterColon + }; + } + } + + return toOptions; +} + +/** + * Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values + * @param {Object} toOptions Object to be initialized + * @param {Object} fromOptions Object to be initialized from + * @returns {Object} The object with correctly initialized options and values + */ +function initOptions(toOptions, fromOptions) { + if (typeof fromOptions.align === "object") { + + // Initialize the alignment configuration + toOptions.align = initOptionProperty({}, fromOptions.align); + toOptions.align.on = fromOptions.align.on || "colon"; + toOptions.align.mode = fromOptions.align.mode || "strict"; + + toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions)); + toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions)); + + } else { // string or undefined + toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions)); + toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions)); + + // If alignment options are defined in multiLine, pull them out into the general align configuration + if (toOptions.multiLine.align) { + toOptions.align = { + on: toOptions.multiLine.align.on, + mode: toOptions.multiLine.align.mode || toOptions.multiLine.mode, + beforeColon: toOptions.multiLine.align.beforeColon, + afterColon: toOptions.multiLine.align.afterColon + }; + } + } + + return toOptions; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing between keys and values in object literal properties", + recommended: false, + url: "https://eslint.org/docs/latest/rules/key-spacing" + }, + + fixable: "whitespace", + + schema: [{ + anyOf: [ + { + type: "object", + properties: { + align: { + anyOf: [ + { + enum: ["colon", "value"] + }, + { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"] + }, + on: { + enum: ["colon", "value"] + }, + beforeColon: { + type: "boolean" + }, + afterColon: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + }, + mode: { + enum: ["strict", "minimum"] + }, + beforeColon: { + type: "boolean" + }, + afterColon: { + type: "boolean" + } + }, + additionalProperties: false + }, + { + type: "object", + properties: { + singleLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"] + }, + beforeColon: { + type: "boolean" + }, + afterColon: { + type: "boolean" + } + }, + additionalProperties: false + }, + multiLine: { + type: "object", + properties: { + align: { + anyOf: [ + { + enum: ["colon", "value"] + }, + { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"] + }, + on: { + enum: ["colon", "value"] + }, + beforeColon: { + type: "boolean" + }, + afterColon: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + }, + mode: { + enum: ["strict", "minimum"] + }, + beforeColon: { + type: "boolean" + }, + afterColon: { + type: "boolean" + } + }, + additionalProperties: false + } + }, + additionalProperties: false + }, + { + type: "object", + properties: { + singleLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"] + }, + beforeColon: { + type: "boolean" + }, + afterColon: { + type: "boolean" + } + }, + additionalProperties: false + }, + multiLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"] + }, + beforeColon: { + type: "boolean" + }, + afterColon: { + type: "boolean" + } + }, + additionalProperties: false + }, + align: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"] + }, + on: { + enum: ["colon", "value"] + }, + beforeColon: { + type: "boolean" + }, + afterColon: { + type: "boolean" + } + }, + additionalProperties: false + } + }, + additionalProperties: false + } + ] + }], + messages: { + extraKey: "Extra space after {{computed}}key '{{key}}'.", + extraValue: "Extra space before value for {{computed}}key '{{key}}'.", + missingKey: "Missing space after {{computed}}key '{{key}}'.", + missingValue: "Missing space before value for {{computed}}key '{{key}}'." + } + }, + + create(context) { + + /** + * OPTIONS + * "key-spacing": [2, { + * beforeColon: false, + * afterColon: true, + * align: "colon" // Optional, or "value" + * } + */ + const options = context.options[0] || {}, + ruleOptions = initOptions({}, options), + multiLineOptions = ruleOptions.multiLine, + singleLineOptions = ruleOptions.singleLine, + alignmentOptions = ruleOptions.align || null; + + const sourceCode = context.sourceCode; + + /** + * Determines if the given property is key-value property. + * @param {ASTNode} property Property node to check. + * @returns {boolean} Whether the property is a key-value property. + */ + function isKeyValueProperty(property) { + return !( + (property.method || + property.shorthand || + property.kind !== "init" || property.type !== "Property") // Could be "ExperimentalSpreadProperty" or "SpreadElement" + ); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The colon punctuator. + */ + function getNextColon(node) { + return sourceCode.getTokenAfter(node, astUtils.isColonToken); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the last token before a colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The last token before a colon punctuator. + */ + function getLastTokenBeforeColon(node) { + const colonToken = getNextColon(node); + + return sourceCode.getTokenBefore(colonToken); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the first token after a colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The first token after a colon punctuator. + */ + function getFirstTokenAfterColon(node) { + const colonToken = getNextColon(node); + + return sourceCode.getTokenAfter(colonToken); + } + + /** + * Checks whether a property is a member of the property group it follows. + * @param {ASTNode} lastMember The last Property known to be in the group. + * @param {ASTNode} candidate The next Property that might be in the group. + * @returns {boolean} True if the candidate property is part of the group. + */ + function continuesPropertyGroup(lastMember, candidate) { + const groupEndLine = lastMember.loc.start.line, + candidateValueStartLine = (isKeyValueProperty(candidate) ? getFirstTokenAfterColon(candidate.key) : candidate).loc.start.line; + + if (candidateValueStartLine - groupEndLine <= 1) { + return true; + } + + /* + * Check that the first comment is adjacent to the end of the group, the + * last comment is adjacent to the candidate property, and that successive + * comments are adjacent to each other. + */ + const leadingComments = sourceCode.getCommentsBefore(candidate); + + if ( + leadingComments.length && + leadingComments[0].loc.start.line - groupEndLine <= 1 && + candidateValueStartLine - last(leadingComments).loc.end.line <= 1 + ) { + for (let i = 1; i < leadingComments.length; i++) { + if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) { + return false; + } + } + return true; + } + + return false; + } + + /** + * Gets an object literal property's key as the identifier name or string value. + * @param {ASTNode} property Property node whose key to retrieve. + * @returns {string} The property's key. + */ + function getKey(property) { + const key = property.key; + + if (property.computed) { + return sourceCode.getText().slice(key.range[0], key.range[1]); + } + return astUtils.getStaticPropertyName(property); + } + + /** + * Reports an appropriately-formatted error if spacing is incorrect on one + * side of the colon. + * @param {ASTNode} property Key-value pair in an object literal. + * @param {string} side Side being verified - either "key" or "value". + * @param {string} whitespace Actual whitespace string. + * @param {int} expected Expected whitespace length. + * @param {string} mode Value of the mode as "strict" or "minimum" + * @returns {void} + */ + function report(property, side, whitespace, expected, mode) { + const diff = whitespace.length - expected; + + if (( + diff && mode === "strict" || + diff < 0 && mode === "minimum" || + diff > 0 && !expected && mode === "minimum") && + !(expected && containsLineTerminator(whitespace)) + ) { + const nextColon = getNextColon(property.key), + tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }), + tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }), + isKeySide = side === "key", + isExtra = diff > 0, + diffAbs = Math.abs(diff), + spaces = Array(diffAbs + 1).join(" "); + + const locStart = isKeySide ? tokenBeforeColon.loc.end : nextColon.loc.start; + const locEnd = isKeySide ? nextColon.loc.start : tokenAfterColon.loc.start; + const missingLoc = isKeySide ? tokenBeforeColon.loc : tokenAfterColon.loc; + const loc = isExtra ? { start: locStart, end: locEnd } : missingLoc; + + let fix; + + if (isExtra) { + let range; + + // Remove whitespace + if (isKeySide) { + range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs]; + } else { + range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]]; + } + fix = function(fixer) { + return fixer.removeRange(range); + }; + } else { + + // Add whitespace + if (isKeySide) { + fix = function(fixer) { + return fixer.insertTextAfter(tokenBeforeColon, spaces); + }; + } else { + fix = function(fixer) { + return fixer.insertTextBefore(tokenAfterColon, spaces); + }; + } + } + + let messageId = ""; + + if (isExtra) { + messageId = side === "key" ? "extraKey" : "extraValue"; + } else { + messageId = side === "key" ? "missingKey" : "missingValue"; + } + + context.report({ + node: property[side], + loc, + messageId, + data: { + computed: property.computed ? "computed " : "", + key: getKey(property) + }, + fix + }); + } + } + + /** + * Gets the number of characters in a key, including quotes around string + * keys and braces around computed property keys. + * @param {ASTNode} property Property of on object literal. + * @returns {int} Width of the key. + */ + function getKeyWidth(property) { + const startToken = sourceCode.getFirstToken(property); + const endToken = getLastTokenBeforeColon(property.key); + + return getGraphemeCount(sourceCode.getText().slice(startToken.range[0], endToken.range[1])); + } + + /** + * Gets the whitespace around the colon in an object literal property. + * @param {ASTNode} property Property node from an object literal. + * @returns {Object} Whitespace before and after the property's colon. + */ + function getPropertyWhitespace(property) { + const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice( + property.key.range[1], property.value.range[0] + )); + + if (whitespace) { + return { + beforeColon: whitespace[1], + afterColon: whitespace[2] + }; + } + return null; + } + + /** + * Creates groups of properties. + * @param {ASTNode} node ObjectExpression node being evaluated. + * @returns {Array} Groups of property AST node lists. + */ + function createGroups(node) { + if (node.properties.length === 1) { + return [node.properties]; + } + + return node.properties.reduce((groups, property) => { + const currentGroup = last(groups), + prev = last(currentGroup); + + if (!prev || continuesPropertyGroup(prev, property)) { + currentGroup.push(property); + } else { + groups.push([property]); + } + + return groups; + }, [ + [] + ]); + } + + /** + * Verifies correct vertical alignment of a group of properties. + * @param {ASTNode[]} properties List of Property AST nodes. + * @returns {void} + */ + function verifyGroupAlignment(properties) { + const length = properties.length, + widths = properties.map(getKeyWidth), // Width of keys, including quotes + align = alignmentOptions.on; // "value" or "colon" + let targetWidth = Math.max(...widths), + beforeColon, afterColon, mode; + + if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration. + beforeColon = alignmentOptions.beforeColon; + afterColon = alignmentOptions.afterColon; + mode = alignmentOptions.mode; + } else { + beforeColon = multiLineOptions.beforeColon; + afterColon = multiLineOptions.afterColon; + mode = alignmentOptions.mode; + } + + // Conditionally include one space before or after colon + targetWidth += (align === "colon" ? beforeColon : afterColon); + + for (let i = 0; i < length; i++) { + const property = properties[i]; + const whitespace = getPropertyWhitespace(property); + + if (whitespace) { // Object literal getters/setters lack a colon + const width = widths[i]; + + if (align === "value") { + report(property, "key", whitespace.beforeColon, beforeColon, mode); + report(property, "value", whitespace.afterColon, targetWidth - width, mode); + } else { // align = "colon" + report(property, "key", whitespace.beforeColon, targetWidth - width, mode); + report(property, "value", whitespace.afterColon, afterColon, mode); + } + } + } + } + + /** + * Verifies spacing of property conforms to specified options. + * @param {ASTNode} node Property node being evaluated. + * @param {Object} lineOptions Configured singleLine or multiLine options + * @returns {void} + */ + function verifySpacing(node, lineOptions) { + const actual = getPropertyWhitespace(node); + + if (actual) { // Object literal getters/setters lack colons + report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode); + report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode); + } + } + + /** + * Verifies spacing of each property in a list. + * @param {ASTNode[]} properties List of Property AST nodes. + * @param {Object} lineOptions Configured singleLine or multiLine options + * @returns {void} + */ + function verifyListSpacing(properties, lineOptions) { + const length = properties.length; + + for (let i = 0; i < length; i++) { + verifySpacing(properties[i], lineOptions); + } + } + + /** + * Verifies vertical alignment, taking into account groups of properties. + * @param {ASTNode} node ObjectExpression node being evaluated. + * @returns {void} + */ + function verifyAlignment(node) { + createGroups(node).forEach(group => { + const properties = group.filter(isKeyValueProperty); + + if (properties.length > 0 && isSingleLineProperties(properties)) { + verifyListSpacing(properties, multiLineOptions); + } else { + verifyGroupAlignment(properties); + } + }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + if (alignmentOptions) { // Verify vertical alignment + + return { + ObjectExpression(node) { + if (isSingleLine(node)) { + verifyListSpacing(node.properties.filter(isKeyValueProperty), singleLineOptions); + } else { + verifyAlignment(node); + } + } + }; + + } + + // Obey beforeColon and afterColon in each property as configured + return { + Property(node) { + verifySpacing(node, isSingleLine(node.parent) ? singleLineOptions : multiLineOptions); + } + }; + + + } +}; diff --git a/node_modules/eslint/lib/rules/keyword-spacing.js b/node_modules/eslint/lib/rules/keyword-spacing.js new file mode 100644 index 0000000..8ed8219 --- /dev/null +++ b/node_modules/eslint/lib/rules/keyword-spacing.js @@ -0,0 +1,637 @@ +/** + * @fileoverview Rule to enforce spacing before and after keywords. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const PREV_TOKEN = /^[)\]}>]$/u; +const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/u; +const PREV_TOKEN_M = /^[)\]}>*]$/u; +const NEXT_TOKEN_M = /^[{*]$/u; +const TEMPLATE_OPEN_PAREN = /\$\{$/u; +const TEMPLATE_CLOSE_PAREN = /^\}/u; +const CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template|PrivateIdentifier)$/u; +const KEYS = keywords.concat(["as", "async", "await", "from", "get", "let", "of", "set", "yield"]); + +// check duplications. +(function() { + KEYS.sort(); + for (let i = 1; i < KEYS.length; ++i) { + if (KEYS[i] === KEYS[i - 1]) { + throw new Error(`Duplication was found in the keyword list: ${KEYS[i]}`); + } + } +}()); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given token is a "Template" token ends with "${". + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is a "Template" token ends with "${". + */ +function isOpenParenOfTemplate(token) { + return token.type === "Template" && TEMPLATE_OPEN_PAREN.test(token.value); +} + +/** + * Checks whether or not a given token is a "Template" token starts with "}". + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is a "Template" token starts with "}". + */ +function isCloseParenOfTemplate(token) { + return token.type === "Template" && TEMPLATE_CLOSE_PAREN.test(token.value); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing before and after keywords", + recommended: false, + url: "https://eslint.org/docs/latest/rules/keyword-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { type: "boolean", default: true }, + after: { type: "boolean", default: true }, + overrides: { + type: "object", + properties: KEYS.reduce((retv, key) => { + retv[key] = { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" } + }, + additionalProperties: false + }; + return retv; + }, {}), + additionalProperties: false + } + }, + additionalProperties: false + } + ], + messages: { + expectedBefore: "Expected space(s) before \"{{value}}\".", + expectedAfter: "Expected space(s) after \"{{value}}\".", + unexpectedBefore: "Unexpected space(s) before \"{{value}}\".", + unexpectedAfter: "Unexpected space(s) after \"{{value}}\"." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + const tokensToIgnore = new WeakSet(); + + /** + * Reports a given token if there are not space(s) before the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the previous token to check. + * @returns {void} + */ + function expectSpaceBefore(token, pattern) { + const prevToken = sourceCode.getTokenBefore(token); + + if (prevToken && + (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && + !isOpenParenOfTemplate(prevToken) && + !tokensToIgnore.has(prevToken) && + astUtils.isTokenOnSameLine(prevToken, token) && + !sourceCode.isSpaceBetweenTokens(prevToken, token) + ) { + context.report({ + loc: token.loc, + messageId: "expectedBefore", + data: token, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + } + }); + } + } + + /** + * Reports a given token if there are space(s) before the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the previous token to check. + * @returns {void} + */ + function unexpectSpaceBefore(token, pattern) { + const prevToken = sourceCode.getTokenBefore(token); + + if (prevToken && + (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && + !isOpenParenOfTemplate(prevToken) && + !tokensToIgnore.has(prevToken) && + astUtils.isTokenOnSameLine(prevToken, token) && + sourceCode.isSpaceBetweenTokens(prevToken, token) + ) { + context.report({ + loc: { start: prevToken.loc.end, end: token.loc.start }, + messageId: "unexpectedBefore", + data: token, + fix(fixer) { + return fixer.removeRange([prevToken.range[1], token.range[0]]); + } + }); + } + } + + /** + * Reports a given token if there are not space(s) after the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the next token to check. + * @returns {void} + */ + function expectSpaceAfter(token, pattern) { + const nextToken = sourceCode.getTokenAfter(token); + + if (nextToken && + (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && + !isCloseParenOfTemplate(nextToken) && + !tokensToIgnore.has(nextToken) && + astUtils.isTokenOnSameLine(token, nextToken) && + !sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + context.report({ + loc: token.loc, + messageId: "expectedAfter", + data: token, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + } + }); + } + } + + /** + * Reports a given token if there are space(s) after the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the next token to check. + * @returns {void} + */ + function unexpectSpaceAfter(token, pattern) { + const nextToken = sourceCode.getTokenAfter(token); + + if (nextToken && + (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && + !isCloseParenOfTemplate(nextToken) && + !tokensToIgnore.has(nextToken) && + astUtils.isTokenOnSameLine(token, nextToken) && + sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + + context.report({ + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedAfter", + data: token, + fix(fixer) { + return fixer.removeRange([token.range[1], nextToken.range[0]]); + } + }); + } + } + + /** + * Parses the option object and determines check methods for each keyword. + * @param {Object|undefined} options The option object to parse. + * @returns {Object} - Normalized option object. + * Keys are keywords (there are for every keyword). + * Values are instances of `{"before": function, "after": function}`. + */ + function parseOptions(options = {}) { + const before = options.before !== false; + const after = options.after !== false; + const defaultValue = { + before: before ? expectSpaceBefore : unexpectSpaceBefore, + after: after ? expectSpaceAfter : unexpectSpaceAfter + }; + const overrides = (options && options.overrides) || {}; + const retv = Object.create(null); + + for (let i = 0; i < KEYS.length; ++i) { + const key = KEYS[i]; + const override = overrides[key]; + + if (override) { + const thisBefore = ("before" in override) ? override.before : before; + const thisAfter = ("after" in override) ? override.after : after; + + retv[key] = { + before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore, + after: thisAfter ? expectSpaceAfter : unexpectSpaceAfter + }; + } else { + retv[key] = defaultValue; + } + } + + return retv; + } + + const checkMethodMap = parseOptions(context.options[0]); + + /** + * Reports a given token if usage of spacing followed by the token is + * invalid. + * @param {Token} token A token to report. + * @param {RegExp} [pattern] Optional. A pattern of the previous + * token to check. + * @returns {void} + */ + function checkSpacingBefore(token, pattern) { + checkMethodMap[token.value].before(token, pattern || PREV_TOKEN); + } + + /** + * Reports a given token if usage of spacing preceded by the token is + * invalid. + * @param {Token} token A token to report. + * @param {RegExp} [pattern] Optional. A pattern of the next + * token to check. + * @returns {void} + */ + function checkSpacingAfter(token, pattern) { + checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN); + } + + /** + * Reports a given token if usage of spacing around the token is invalid. + * @param {Token} token A token to report. + * @returns {void} + */ + function checkSpacingAround(token) { + checkSpacingBefore(token); + checkSpacingAfter(token); + } + + /** + * Reports the first token of a given node if the first token is a keyword + * and usage of spacing around the token is invalid. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingAroundFirstToken(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if (firstToken && firstToken.type === "Keyword") { + checkSpacingAround(firstToken); + } + } + + /** + * Reports the first token of a given node if the first token is a keyword + * and usage of spacing followed by the token is invalid. + * + * This is used for unary operators (e.g. `typeof`), `function`, and `super`. + * Other rules are handling usage of spacing preceded by those keywords. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingBeforeFirstToken(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if (firstToken && firstToken.type === "Keyword") { + checkSpacingBefore(firstToken); + } + } + + /** + * Reports the previous token of a given node if the token is a keyword and + * usage of spacing around the token is invalid. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingAroundTokenBefore(node) { + if (node) { + const token = sourceCode.getTokenBefore(node, astUtils.isKeywordToken); + + checkSpacingAround(token); + } + } + + /** + * Reports `async` or `function` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForFunction(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if (firstToken && + ((firstToken.type === "Keyword" && firstToken.value === "function") || + firstToken.value === "async") + ) { + checkSpacingBefore(firstToken); + } + } + + /** + * Reports `class` and `extends` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForClass(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.superClass); + } + + /** + * Reports `if` and `else` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForIfStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.alternate); + } + + /** + * Reports `try`, `catch`, and `finally` keywords of a given node if usage + * of spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForTryStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundFirstToken(node.handler); + checkSpacingAroundTokenBefore(node.finalizer); + } + + /** + * Reports `do` and `while` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForDoWhileStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.test); + } + + /** + * Reports `for` and `in` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForForInStatement(node) { + checkSpacingAroundFirstToken(node); + + const inToken = sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken); + const previousToken = sourceCode.getTokenBefore(inToken); + + if (previousToken.type !== "PrivateIdentifier") { + checkSpacingBefore(inToken); + } + + checkSpacingAfter(inToken); + } + + /** + * Reports `for` and `of` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForForOfStatement(node) { + if (node.await) { + checkSpacingBefore(sourceCode.getFirstToken(node, 0)); + checkSpacingAfter(sourceCode.getFirstToken(node, 1)); + } else { + checkSpacingAroundFirstToken(node); + } + + const ofToken = sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken); + const previousToken = sourceCode.getTokenBefore(ofToken); + + if (previousToken.type !== "PrivateIdentifier") { + checkSpacingBefore(ofToken); + } + + checkSpacingAfter(ofToken); + } + + /** + * Reports `import`, `export`, `as`, and `from` keywords of a given node if + * usage of spacing around those keywords is invalid. + * + * This rule handles the `*` token in module declarations. + * + * import*as A from "./a"; /*error Expected space(s) after "import". + * error Expected space(s) before "as". + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForModuleDeclaration(node) { + const firstToken = sourceCode.getFirstToken(node); + + checkSpacingBefore(firstToken, PREV_TOKEN_M); + checkSpacingAfter(firstToken, NEXT_TOKEN_M); + + if (node.type === "ExportDefaultDeclaration") { + checkSpacingAround(sourceCode.getTokenAfter(firstToken)); + } + + if (node.type === "ExportAllDeclaration" && node.exported) { + const asToken = sourceCode.getTokenBefore(node.exported); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + checkSpacingAfter(asToken, NEXT_TOKEN_M); + } + + if (node.source) { + const fromToken = sourceCode.getTokenBefore(node.source); + + checkSpacingBefore(fromToken, PREV_TOKEN_M); + checkSpacingAfter(fromToken, NEXT_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node An `ImportSpecifier` node to check. + * @returns {void} + */ + function checkSpacingForImportSpecifier(node) { + if (node.imported.range[0] !== node.local.range[0]) { + const asToken = sourceCode.getTokenBefore(node.local); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node An `ExportSpecifier` node to check. + * @returns {void} + */ + function checkSpacingForExportSpecifier(node) { + if (node.local.range[0] !== node.exported.range[0]) { + const asToken = sourceCode.getTokenBefore(node.exported); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + checkSpacingAfter(asToken, NEXT_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForImportNamespaceSpecifier(node) { + const asToken = sourceCode.getFirstToken(node, 1); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + } + + /** + * Reports `static`, `get`, and `set` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @throws {Error} If unable to find token get, set, or async beside method name. + * @returns {void} + */ + function checkSpacingForProperty(node) { + if (node.static) { + checkSpacingAroundFirstToken(node); + } + if (node.kind === "get" || + node.kind === "set" || + ( + (node.method || node.type === "MethodDefinition") && + node.value.async + ) + ) { + const token = sourceCode.getTokenBefore( + node.key, + tok => { + switch (tok.value) { + case "get": + case "set": + case "async": + return true; + default: + return false; + } + } + ); + + if (!token) { + throw new Error("Failed to find token get, set, or async beside method name"); + } + + + checkSpacingAround(token); + } + } + + /** + * Reports `await` keyword of a given node if usage of spacing before + * this keyword is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForAwaitExpression(node) { + checkSpacingBefore(sourceCode.getFirstToken(node)); + } + + return { + + // Statements + DebuggerStatement: checkSpacingAroundFirstToken, + WithStatement: checkSpacingAroundFirstToken, + + // Statements - Control flow + BreakStatement: checkSpacingAroundFirstToken, + ContinueStatement: checkSpacingAroundFirstToken, + ReturnStatement: checkSpacingAroundFirstToken, + ThrowStatement: checkSpacingAroundFirstToken, + TryStatement: checkSpacingForTryStatement, + + // Statements - Choice + IfStatement: checkSpacingForIfStatement, + SwitchStatement: checkSpacingAroundFirstToken, + SwitchCase: checkSpacingAroundFirstToken, + + // Statements - Loops + DoWhileStatement: checkSpacingForDoWhileStatement, + ForInStatement: checkSpacingForForInStatement, + ForOfStatement: checkSpacingForForOfStatement, + ForStatement: checkSpacingAroundFirstToken, + WhileStatement: checkSpacingAroundFirstToken, + + // Statements - Declarations + ClassDeclaration: checkSpacingForClass, + ExportNamedDeclaration: checkSpacingForModuleDeclaration, + ExportDefaultDeclaration: checkSpacingForModuleDeclaration, + ExportAllDeclaration: checkSpacingForModuleDeclaration, + FunctionDeclaration: checkSpacingForFunction, + ImportDeclaration: checkSpacingForModuleDeclaration, + VariableDeclaration: checkSpacingAroundFirstToken, + + // Expressions + ArrowFunctionExpression: checkSpacingForFunction, + AwaitExpression: checkSpacingForAwaitExpression, + ClassExpression: checkSpacingForClass, + FunctionExpression: checkSpacingForFunction, + NewExpression: checkSpacingBeforeFirstToken, + Super: checkSpacingBeforeFirstToken, + ThisExpression: checkSpacingBeforeFirstToken, + UnaryExpression: checkSpacingBeforeFirstToken, + YieldExpression: checkSpacingBeforeFirstToken, + + // Others + ImportSpecifier: checkSpacingForImportSpecifier, + ExportSpecifier: checkSpacingForExportSpecifier, + ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier, + MethodDefinition: checkSpacingForProperty, + PropertyDefinition: checkSpacingForProperty, + StaticBlock: checkSpacingAroundFirstToken, + Property: checkSpacingForProperty, + + // To avoid conflicts with `space-infix-ops`, e.g. `a > this.b` + "BinaryExpression[operator='>']"(node) { + const operatorToken = sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken); + + tokensToIgnore.add(operatorToken); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/line-comment-position.js b/node_modules/eslint/lib/rules/line-comment-position.js new file mode 100644 index 0000000..314fac1 --- /dev/null +++ b/node_modules/eslint/lib/rules/line-comment-position.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Rule to enforce the position of line comments + * @author Alberto Rodríguez + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce position of line comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/line-comment-position" + }, + + schema: [ + { + oneOf: [ + { + enum: ["above", "beside"] + }, + { + type: "object", + properties: { + position: { + enum: ["above", "beside"] + }, + ignorePattern: { + type: "string" + }, + applyDefaultPatterns: { + type: "boolean" + }, + applyDefaultIgnorePatterns: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + } + ], + messages: { + above: "Expected comment to be above code.", + beside: "Expected comment to be beside code." + } + }, + + create(context) { + const options = context.options[0]; + + let above, + ignorePattern, + applyDefaultIgnorePatterns = true; + + if (!options || typeof options === "string") { + above = !options || options === "above"; + + } else { + above = !options.position || options.position === "above"; + ignorePattern = options.ignorePattern; + + if (Object.prototype.hasOwnProperty.call(options, "applyDefaultIgnorePatterns")) { + applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns; + } else { + applyDefaultIgnorePatterns = options.applyDefaultPatterns !== false; + } + } + + const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; + const fallThroughRegExp = /^\s*falls?\s?through/u; + const customIgnoreRegExp = new RegExp(ignorePattern, "u"); + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments.filter(token => token.type === "Line").forEach(node => { + if (applyDefaultIgnorePatterns && (defaultIgnoreRegExp.test(node.value) || fallThroughRegExp.test(node.value))) { + return; + } + + if (ignorePattern && customIgnoreRegExp.test(node.value)) { + return; + } + + const previous = sourceCode.getTokenBefore(node, { includeComments: true }); + const isOnSameLine = previous && previous.loc.end.line === node.loc.start.line; + + if (above) { + if (isOnSameLine) { + context.report({ + node, + messageId: "above" + }); + } + } else { + if (!isOnSameLine) { + context.report({ + node, + messageId: "beside" + }); + } + } + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/linebreak-style.js b/node_modules/eslint/lib/rules/linebreak-style.js new file mode 100644 index 0000000..d8f3609 --- /dev/null +++ b/node_modules/eslint/lib/rules/linebreak-style.js @@ -0,0 +1,105 @@ +/** + * @fileoverview Rule to enforce a single linebreak style. + * @author Erik Mueller + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent linebreak style", + recommended: false, + url: "https://eslint.org/docs/latest/rules/linebreak-style" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["unix", "windows"] + } + ], + messages: { + expectedLF: "Expected linebreaks to be 'LF' but found 'CRLF'.", + expectedCRLF: "Expected linebreaks to be 'CRLF' but found 'LF'." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Builds a fix function that replaces text at the specified range in the source text. + * @param {int[]} range The range to replace + * @param {string} text The text to insert. + * @returns {Function} Fixer function + * @private + */ + function createFix(range, text) { + return function(fixer) { + return fixer.replaceTextRange(range, text); + }; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkForLinebreakStyle(node) { + const linebreakStyle = context.options[0] || "unix", + expectedLF = linebreakStyle === "unix", + expectedLFChars = expectedLF ? "\n" : "\r\n", + source = sourceCode.getText(), + pattern = astUtils.createGlobalLinebreakMatcher(); + let match; + + let i = 0; + + while ((match = pattern.exec(source)) !== null) { + i++; + if (match[0] === expectedLFChars) { + continue; + } + + const index = match.index; + const range = [index, index + match[0].length]; + + context.report({ + node, + loc: { + start: { + line: i, + column: sourceCode.lines[i - 1].length + }, + end: { + line: i + 1, + column: 0 + } + }, + messageId: expectedLF ? "expectedLF" : "expectedCRLF", + fix: createFix(range, expectedLFChars) + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/lines-around-comment.js b/node_modules/eslint/lib/rules/lines-around-comment.js new file mode 100644 index 0000000..10aeba3 --- /dev/null +++ b/node_modules/eslint/lib/rules/lines-around-comment.js @@ -0,0 +1,468 @@ +/** + * @fileoverview Enforces empty lines around comments. + * @author Jamund Ferguson + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Return an array with any line numbers that are empty. + * @param {Array} lines An array of each line of the file. + * @returns {Array} An array of line numbers. + */ +function getEmptyLineNums(lines) { + const emptyLines = lines.map((line, i) => ({ + code: line.trim(), + num: i + 1 + })).filter(line => !line.code).map(line => line.num); + + return emptyLines; +} + +/** + * Return an array with any line numbers that contain comments. + * @param {Array} comments An array of comment tokens. + * @returns {Array} An array of line numbers. + */ +function getCommentLineNums(comments) { + const lines = []; + + comments.forEach(token => { + const start = token.loc.start.line; + const end = token.loc.end.line; + + lines.push(start, end); + }); + return lines; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require empty lines around comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-around-comment" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + beforeBlockComment: { + type: "boolean", + default: true + }, + afterBlockComment: { + type: "boolean", + default: false + }, + beforeLineComment: { + type: "boolean", + default: false + }, + afterLineComment: { + type: "boolean", + default: false + }, + allowBlockStart: { + type: "boolean", + default: false + }, + allowBlockEnd: { + type: "boolean", + default: false + }, + allowClassStart: { + type: "boolean" + }, + allowClassEnd: { + type: "boolean" + }, + allowObjectStart: { + type: "boolean" + }, + allowObjectEnd: { + type: "boolean" + }, + allowArrayStart: { + type: "boolean" + }, + allowArrayEnd: { + type: "boolean" + }, + ignorePattern: { + type: "string" + }, + applyDefaultIgnorePatterns: { + type: "boolean" + }, + afterHashbangComment: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + messages: { + after: "Expected line after comment.", + before: "Expected line before comment." + } + }, + + create(context) { + + const options = Object.assign({}, context.options[0]); + const ignorePattern = options.ignorePattern; + const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; + const customIgnoreRegExp = new RegExp(ignorePattern, "u"); + const applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false; + + options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true; + + const sourceCode = context.sourceCode; + + const lines = sourceCode.lines, + numLines = lines.length + 1, + comments = sourceCode.getAllComments(), + commentLines = getCommentLineNums(comments), + emptyLines = getEmptyLineNums(lines), + commentAndEmptyLines = new Set(commentLines.concat(emptyLines)); + + /** + * Returns whether or not comments are on lines starting with or ending with code + * @param {token} token The comment token to check. + * @returns {boolean} True if the comment is not alone. + */ + function codeAroundComment(token) { + let currentToken = token; + + do { + currentToken = sourceCode.getTokenBefore(currentToken, { includeComments: true }); + } while (currentToken && astUtils.isCommentToken(currentToken)); + + if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) { + return true; + } + + currentToken = token; + do { + currentToken = sourceCode.getTokenAfter(currentToken, { includeComments: true }); + } while (currentToken && astUtils.isCommentToken(currentToken)); + + if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) { + return true; + } + + return false; + } + + /** + * Returns whether or not comments are inside a node type or not. + * @param {ASTNode} parent The Comment parent node. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is inside nodeType. + */ + function isParentNodeType(parent, nodeType) { + return parent.type === nodeType || + (parent.body && parent.body.type === nodeType) || + (parent.consequent && parent.consequent.type === nodeType); + } + + /** + * Returns the parent node that contains the given token. + * @param {token} token The token to check. + * @returns {ASTNode|null} The parent node that contains the given token. + */ + function getParentNodeOfToken(token) { + const node = sourceCode.getNodeByRangeIndex(token.range[0]); + + /* + * For the purpose of this rule, the comment token is in a `StaticBlock` node only + * if it's inside the braces of that `StaticBlock` node. + * + * Example where this function returns `null`: + * + * static + * // comment + * { + * } + * + * Example where this function returns `StaticBlock` node: + * + * static + * { + * // comment + * } + * + */ + if (node && node.type === "StaticBlock") { + const openingBrace = sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token + + return token.range[0] >= openingBrace.range[0] + ? node + : null; + } + + return node; + } + + /** + * Returns whether or not comments are at the parent start or not. + * @param {token} token The Comment token. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is at parent start. + */ + function isCommentAtParentStart(token, nodeType) { + const parent = getParentNodeOfToken(token); + + if (parent && isParentNodeType(parent, nodeType)) { + let parentStartNodeOrToken = parent; + + if (parent.type === "StaticBlock") { + parentStartNodeOrToken = sourceCode.getFirstToken(parent, { skip: 1 }); // opening brace of the static block + } else if (parent.type === "SwitchStatement") { + parentStartNodeOrToken = sourceCode.getTokenAfter(parent.discriminant, { + filter: astUtils.isOpeningBraceToken + }); // opening brace of the switch statement + } + + return token.loc.start.line - parentStartNodeOrToken.loc.start.line === 1; + } + + return false; + } + + /** + * Returns whether or not comments are at the parent end or not. + * @param {token} token The Comment token. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is at parent end. + */ + function isCommentAtParentEnd(token, nodeType) { + const parent = getParentNodeOfToken(token); + + return !!parent && isParentNodeType(parent, nodeType) && + parent.loc.end.line - token.loc.end.line === 1; + } + + /** + * Returns whether or not comments are at the block start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at block start. + */ + function isCommentAtBlockStart(token) { + return ( + isCommentAtParentStart(token, "ClassBody") || + isCommentAtParentStart(token, "BlockStatement") || + isCommentAtParentStart(token, "StaticBlock") || + isCommentAtParentStart(token, "SwitchCase") || + isCommentAtParentStart(token, "SwitchStatement") + ); + } + + /** + * Returns whether or not comments are at the block end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at block end. + */ + function isCommentAtBlockEnd(token) { + return ( + isCommentAtParentEnd(token, "ClassBody") || + isCommentAtParentEnd(token, "BlockStatement") || + isCommentAtParentEnd(token, "StaticBlock") || + isCommentAtParentEnd(token, "SwitchCase") || + isCommentAtParentEnd(token, "SwitchStatement") + ); + } + + /** + * Returns whether or not comments are at the class start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at class start. + */ + function isCommentAtClassStart(token) { + return isCommentAtParentStart(token, "ClassBody"); + } + + /** + * Returns whether or not comments are at the class end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at class end. + */ + function isCommentAtClassEnd(token) { + return isCommentAtParentEnd(token, "ClassBody"); + } + + /** + * Returns whether or not comments are at the object start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at object start. + */ + function isCommentAtObjectStart(token) { + return isCommentAtParentStart(token, "ObjectExpression") || isCommentAtParentStart(token, "ObjectPattern"); + } + + /** + * Returns whether or not comments are at the object end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at object end. + */ + function isCommentAtObjectEnd(token) { + return isCommentAtParentEnd(token, "ObjectExpression") || isCommentAtParentEnd(token, "ObjectPattern"); + } + + /** + * Returns whether or not comments are at the array start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at array start. + */ + function isCommentAtArrayStart(token) { + return isCommentAtParentStart(token, "ArrayExpression") || isCommentAtParentStart(token, "ArrayPattern"); + } + + /** + * Returns whether or not comments are at the array end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at array end. + */ + function isCommentAtArrayEnd(token) { + return isCommentAtParentEnd(token, "ArrayExpression") || isCommentAtParentEnd(token, "ArrayPattern"); + } + + /** + * Checks if a comment token has lines around it (ignores inline comments) + * @param {token} token The Comment token. + * @param {Object} opts Options to determine the newline. + * @param {boolean} opts.after Should have a newline after this line. + * @param {boolean} opts.before Should have a newline before this line. + * @returns {void} + */ + function checkForEmptyLine(token, opts) { + if (applyDefaultIgnorePatterns && defaultIgnoreRegExp.test(token.value)) { + return; + } + + if (ignorePattern && customIgnoreRegExp.test(token.value)) { + return; + } + + let after = opts.after, + before = opts.before; + + const prevLineNum = token.loc.start.line - 1, + nextLineNum = token.loc.end.line + 1, + commentIsNotAlone = codeAroundComment(token); + + const blockStartAllowed = options.allowBlockStart && + isCommentAtBlockStart(token) && + !(options.allowClassStart === false && + isCommentAtClassStart(token)), + blockEndAllowed = options.allowBlockEnd && isCommentAtBlockEnd(token) && !(options.allowClassEnd === false && isCommentAtClassEnd(token)), + classStartAllowed = options.allowClassStart && isCommentAtClassStart(token), + classEndAllowed = options.allowClassEnd && isCommentAtClassEnd(token), + objectStartAllowed = options.allowObjectStart && isCommentAtObjectStart(token), + objectEndAllowed = options.allowObjectEnd && isCommentAtObjectEnd(token), + arrayStartAllowed = options.allowArrayStart && isCommentAtArrayStart(token), + arrayEndAllowed = options.allowArrayEnd && isCommentAtArrayEnd(token); + + const exceptionStartAllowed = blockStartAllowed || classStartAllowed || objectStartAllowed || arrayStartAllowed; + const exceptionEndAllowed = blockEndAllowed || classEndAllowed || objectEndAllowed || arrayEndAllowed; + + // ignore top of the file and bottom of the file + if (prevLineNum < 1) { + before = false; + } + if (nextLineNum >= numLines) { + after = false; + } + + // we ignore all inline comments + if (commentIsNotAlone) { + return; + } + + const previousTokenOrComment = sourceCode.getTokenBefore(token, { includeComments: true }); + const nextTokenOrComment = sourceCode.getTokenAfter(token, { includeComments: true }); + + // check for newline before + if (!exceptionStartAllowed && before && !commentAndEmptyLines.has(prevLineNum) && + !(astUtils.isCommentToken(previousTokenOrComment) && astUtils.isTokenOnSameLine(previousTokenOrComment, token))) { + const lineStart = token.range[0] - token.loc.start.column; + const range = [lineStart, lineStart]; + + context.report({ + node: token, + messageId: "before", + fix(fixer) { + return fixer.insertTextBeforeRange(range, "\n"); + } + }); + } + + // check for newline after + if (!exceptionEndAllowed && after && !commentAndEmptyLines.has(nextLineNum) && + !(astUtils.isCommentToken(nextTokenOrComment) && astUtils.isTokenOnSameLine(token, nextTokenOrComment))) { + context.report({ + node: token, + messageId: "after", + fix(fixer) { + return fixer.insertTextAfter(token, "\n"); + } + }); + } + + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + comments.forEach(token => { + if (token.type === "Line") { + if (options.beforeLineComment || options.afterLineComment) { + checkForEmptyLine(token, { + after: options.afterLineComment, + before: options.beforeLineComment + }); + } + } else if (token.type === "Block") { + if (options.beforeBlockComment || options.afterBlockComment) { + checkForEmptyLine(token, { + after: options.afterBlockComment, + before: options.beforeBlockComment + }); + } + } else if (token.type === "Shebang") { + if (options.afterHashbangComment) { + checkForEmptyLine(token, { + after: options.afterHashbangComment, + before: false + }); + } + } + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/lines-around-directive.js b/node_modules/eslint/lib/rules/lines-around-directive.js new file mode 100644 index 0000000..1c82d8f --- /dev/null +++ b/node_modules/eslint/lib/rules/lines-around-directive.js @@ -0,0 +1,201 @@ +/** + * @fileoverview Require or disallow newlines around directives. + * @author Kai Cataldo + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow newlines around directives", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-around-directive" + }, + + schema: [{ + oneOf: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + before: { + enum: ["always", "never"] + }, + after: { + enum: ["always", "never"] + } + }, + additionalProperties: false, + minProperties: 2 + } + ] + }], + + fixable: "whitespace", + messages: { + expected: "Expected newline {{location}} \"{{value}}\" directive.", + unexpected: "Unexpected newline {{location}} \"{{value}}\" directive." + }, + deprecated: true, + replacedBy: ["padding-line-between-statements"] + }, + + create(context) { + const sourceCode = context.sourceCode; + const config = context.options[0] || "always"; + const expectLineBefore = typeof config === "string" ? config : config.before; + const expectLineAfter = typeof config === "string" ? config : config.after; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if node is preceded by a blank newline. + * @param {ASTNode} node Node to check. + * @returns {boolean} Whether or not the passed in node is preceded by a blank newline. + */ + function hasNewlineBefore(node) { + const tokenBefore = sourceCode.getTokenBefore(node, { includeComments: true }); + const tokenLineBefore = tokenBefore ? tokenBefore.loc.end.line : 0; + + return node.loc.start.line - tokenLineBefore >= 2; + } + + /** + * Gets the last token of a node that is on the same line as the rest of the node. + * This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing + * semicolon on a different line. + * @param {ASTNode} node A directive node + * @returns {Token} The last token of the node on the line + */ + function getLastTokenOnLine(node) { + const lastToken = sourceCode.getLastToken(node); + const secondToLastToken = sourceCode.getTokenBefore(lastToken); + + return astUtils.isSemicolonToken(lastToken) && lastToken.loc.start.line > secondToLastToken.loc.end.line + ? secondToLastToken + : lastToken; + } + + /** + * Check if node is followed by a blank newline. + * @param {ASTNode} node Node to check. + * @returns {boolean} Whether or not the passed in node is followed by a blank newline. + */ + function hasNewlineAfter(node) { + const lastToken = getLastTokenOnLine(node); + const tokenAfter = sourceCode.getTokenAfter(lastToken, { includeComments: true }); + + return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; + } + + /** + * Report errors for newlines around directives. + * @param {ASTNode} node Node to check. + * @param {string} location Whether the error was found before or after the directive. + * @param {boolean} expected Whether or not a newline was expected or unexpected. + * @returns {void} + */ + function reportError(node, location, expected) { + context.report({ + node, + messageId: expected ? "expected" : "unexpected", + data: { + value: node.expression.value, + location + }, + fix(fixer) { + const lastToken = getLastTokenOnLine(node); + + if (expected) { + return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(lastToken, "\n"); + } + return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [lastToken.range[1], lastToken.range[1] + 1]); + } + }); + } + + /** + * Check lines around directives in node + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkDirectives(node) { + const directives = astUtils.getDirectivePrologue(node); + + if (!directives.length) { + return; + } + + const firstDirective = directives[0]; + const leadingComments = sourceCode.getCommentsBefore(firstDirective); + + /* + * Only check before the first directive if it is preceded by a comment or if it is at the top of + * the file and expectLineBefore is set to "never". This is to not force a newline at the top of + * the file if there are no comments as well as for compatibility with padded-blocks. + */ + if (leadingComments.length) { + if (expectLineBefore === "always" && !hasNewlineBefore(firstDirective)) { + reportError(firstDirective, "before", true); + } + + if (expectLineBefore === "never" && hasNewlineBefore(firstDirective)) { + reportError(firstDirective, "before", false); + } + } else if ( + node.type === "Program" && + expectLineBefore === "never" && + !leadingComments.length && + hasNewlineBefore(firstDirective) + ) { + reportError(firstDirective, "before", false); + } + + const lastDirective = directives[directives.length - 1]; + const statements = node.type === "Program" ? node.body : node.body.body; + + /* + * Do not check after the last directive if the body only + * contains a directive prologue and isn't followed by a comment to ensure + * this rule behaves well with padded-blocks. + */ + if (lastDirective === statements[statements.length - 1] && !lastDirective.trailingComments) { + return; + } + + if (expectLineAfter === "always" && !hasNewlineAfter(lastDirective)) { + reportError(lastDirective, "after", true); + } + + if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) { + reportError(lastDirective, "after", false); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: checkDirectives, + FunctionDeclaration: checkDirectives, + FunctionExpression: checkDirectives, + ArrowFunctionExpression: checkDirectives + }; + } +}; diff --git a/node_modules/eslint/lib/rules/lines-between-class-members.js b/node_modules/eslint/lib/rules/lines-between-class-members.js new file mode 100644 index 0000000..dee4bab --- /dev/null +++ b/node_modules/eslint/lib/rules/lines-between-class-members.js @@ -0,0 +1,181 @@ +/** + * @fileoverview Rule to check empty newline between class members + * @author 薛定谔的猫 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow an empty line between class members", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-between-class-members" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + exceptAfterSingleLine: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + messages: { + never: "Unexpected blank line between class members.", + always: "Expected blank line between class members." + } + }, + + create(context) { + + const options = []; + + options[0] = context.options[0] || "always"; + options[1] = context.options[1] || { exceptAfterSingleLine: false }; + + const sourceCode = context.sourceCode; + + /** + * Gets a pair of tokens that should be used to check lines between two class member nodes. + * + * In most cases, this returns the very last token of the current node and + * the very first token of the next node. + * For example: + * + * class C { + * x = 1; // curLast: `;` nextFirst: `in` + * in = 2 + * } + * + * There is only one exception. If the given node ends with a semicolon, and it looks like + * a semicolon-less style's semicolon - one that is not on the same line as the preceding + * token, but is on the line where the next class member starts - this returns the preceding + * token and the semicolon as boundary tokens. + * For example: + * + * class C { + * x = 1 // curLast: `1` nextFirst: `;` + * ;in = 2 + * } + * When determining the desired layout of the code, we should treat this semicolon as + * a part of the next class member node instead of the one it technically belongs to. + * @param {ASTNode} curNode Current class member node. + * @param {ASTNode} nextNode Next class member node. + * @returns {Token} The actual last token of `node`. + * @private + */ + function getBoundaryTokens(curNode, nextNode) { + const lastToken = sourceCode.getLastToken(curNode); + const prevToken = sourceCode.getTokenBefore(lastToken); + const nextToken = sourceCode.getFirstToken(nextNode); // skip possible lone `;` between nodes + + const isSemicolonLessStyle = ( + astUtils.isSemicolonToken(lastToken) && + !astUtils.isTokenOnSameLine(prevToken, lastToken) && + astUtils.isTokenOnSameLine(lastToken, nextToken) + ); + + return isSemicolonLessStyle + ? { curLast: prevToken, nextFirst: lastToken } + : { curLast: lastToken, nextFirst: nextToken }; + } + + /** + * Return the last token among the consecutive tokens that have no exceed max line difference in between, before the first token in the next member. + * @param {Token} prevLastToken The last token in the previous member node. + * @param {Token} nextFirstToken The first token in the next member node. + * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens. + * @returns {Token} The last token among the consecutive tokens. + */ + function findLastConsecutiveTokenAfter(prevLastToken, nextFirstToken, maxLine) { + const after = sourceCode.getTokenAfter(prevLastToken, { includeComments: true }); + + if (after !== nextFirstToken && after.loc.start.line - prevLastToken.loc.end.line <= maxLine) { + return findLastConsecutiveTokenAfter(after, nextFirstToken, maxLine); + } + return prevLastToken; + } + + /** + * Return the first token among the consecutive tokens that have no exceed max line difference in between, after the last token in the previous member. + * @param {Token} nextFirstToken The first token in the next member node. + * @param {Token} prevLastToken The last token in the previous member node. + * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens. + * @returns {Token} The first token among the consecutive tokens. + */ + function findFirstConsecutiveTokenBefore(nextFirstToken, prevLastToken, maxLine) { + const before = sourceCode.getTokenBefore(nextFirstToken, { includeComments: true }); + + if (before !== prevLastToken && nextFirstToken.loc.start.line - before.loc.end.line <= maxLine) { + return findFirstConsecutiveTokenBefore(before, prevLastToken, maxLine); + } + return nextFirstToken; + } + + /** + * Checks if there is a token or comment between two tokens. + * @param {Token} before The token before. + * @param {Token} after The token after. + * @returns {boolean} True if there is a token or comment between two tokens. + */ + function hasTokenOrCommentBetween(before, after) { + return sourceCode.getTokensBetween(before, after, { includeComments: true }).length !== 0; + } + + return { + ClassBody(node) { + const body = node.body; + + for (let i = 0; i < body.length - 1; i++) { + const curFirst = sourceCode.getFirstToken(body[i]); + const { curLast, nextFirst } = getBoundaryTokens(body[i], body[i + 1]); + const isMulti = !astUtils.isTokenOnSameLine(curFirst, curLast); + const skip = !isMulti && options[1].exceptAfterSingleLine; + const beforePadding = findLastConsecutiveTokenAfter(curLast, nextFirst, 1); + const afterPadding = findFirstConsecutiveTokenBefore(nextFirst, curLast, 1); + const isPadded = afterPadding.loc.start.line - beforePadding.loc.end.line > 1; + const hasTokenInPadding = hasTokenOrCommentBetween(beforePadding, afterPadding); + const curLineLastToken = findLastConsecutiveTokenAfter(curLast, nextFirst, 0); + + if ((options[0] === "always" && !skip && !isPadded) || + (options[0] === "never" && isPadded)) { + context.report({ + node: body[i + 1], + messageId: isPadded ? "never" : "always", + fix(fixer) { + if (hasTokenInPadding) { + return null; + } + return isPadded + ? fixer.replaceTextRange([beforePadding.range[1], afterPadding.range[0]], "\n") + : fixer.insertTextAfter(curLineLastToken, "\n"); + } + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/logical-assignment-operators.js b/node_modules/eslint/lib/rules/logical-assignment-operators.js new file mode 100644 index 0000000..27ca585 --- /dev/null +++ b/node_modules/eslint/lib/rules/logical-assignment-operators.js @@ -0,0 +1,476 @@ +/** + * @fileoverview Rule to replace assignment expressions with logical operator assignment + * @author Daniel Martens + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const baseTypes = new Set(["Identifier", "Super", "ThisExpression"]); + +/** + * Returns true iff either "undefined" or a void expression (eg. "void 0") + * @param {ASTNode} expression Expression to check + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff "undefined" or "void ..." + */ +function isUndefined(expression, scope) { + if (expression.type === "Identifier" && expression.name === "undefined") { + return astUtils.isReferenceToGlobalVariable(scope, expression); + } + + return expression.type === "UnaryExpression" && + expression.operator === "void" && + expression.argument.type === "Literal" && + expression.argument.value === 0; +} + +/** + * Returns true iff the reference is either an identifier or member expression + * @param {ASTNode} expression Expression to check + * @returns {boolean} True for identifiers and member expressions + */ +function isReference(expression) { + return (expression.type === "Identifier" && expression.name !== "undefined") || + expression.type === "MemberExpression"; +} + +/** + * Returns true iff the expression checks for nullish with loose equals. + * Examples: value == null, value == void 0 + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff implicit nullish comparison + */ +function isImplicitNullishComparison(expression, scope) { + if (expression.type !== "BinaryExpression" || expression.operator !== "==") { + return false; + } + + const reference = isReference(expression.left) ? "left" : "right"; + const nullish = reference === "left" ? "right" : "left"; + + return isReference(expression[reference]) && + (astUtils.isNullLiteral(expression[nullish]) || isUndefined(expression[nullish], scope)); +} + +/** + * Condition with two equal comparisons. + * @param {ASTNode} expression Condition + * @returns {boolean} True iff matches ? === ? || ? === ? + */ +function isDoubleComparison(expression) { + return expression.type === "LogicalExpression" && + expression.operator === "||" && + expression.left.type === "BinaryExpression" && + expression.left.operator === "===" && + expression.right.type === "BinaryExpression" && + expression.right.operator === "==="; +} + +/** + * Returns true iff the expression checks for undefined and null. + * Example: value === null || value === undefined + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff explicit nullish comparison + */ +function isExplicitNullishComparison(expression, scope) { + if (!isDoubleComparison(expression)) { + return false; + } + const leftReference = isReference(expression.left.left) ? "left" : "right"; + const leftNullish = leftReference === "left" ? "right" : "left"; + const rightReference = isReference(expression.right.left) ? "left" : "right"; + const rightNullish = rightReference === "left" ? "right" : "left"; + + return astUtils.isSameReference(expression.left[leftReference], expression.right[rightReference]) && + ((astUtils.isNullLiteral(expression.left[leftNullish]) && isUndefined(expression.right[rightNullish], scope)) || + (isUndefined(expression.left[leftNullish], scope) && astUtils.isNullLiteral(expression.right[rightNullish]))); +} + +/** + * Returns true for Boolean(arg) calls + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} Whether the expression is a boolean cast + */ +function isBooleanCast(expression, scope) { + return expression.type === "CallExpression" && + expression.callee.name === "Boolean" && + expression.arguments.length === 1 && + astUtils.isReferenceToGlobalVariable(scope, expression.callee); +} + +/** + * Returns true for: + * truthiness checks: value, Boolean(value), !!value + * falsiness checks: !value, !Boolean(value) + * nullish checks: value == null, value === undefined || value === null + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {?{ reference: ASTNode, operator: '??'|'||'|'&&'}} Null if not a known existence + */ +function getExistence(expression, scope) { + const isNegated = expression.type === "UnaryExpression" && expression.operator === "!"; + const base = isNegated ? expression.argument : expression; + + switch (true) { + case isReference(base): + return { reference: base, operator: isNegated ? "||" : "&&" }; + case base.type === "UnaryExpression" && base.operator === "!" && isReference(base.argument): + return { reference: base.argument, operator: "&&" }; + case isBooleanCast(base, scope) && isReference(base.arguments[0]): + return { reference: base.arguments[0], operator: isNegated ? "||" : "&&" }; + case isImplicitNullishComparison(expression, scope): + return { reference: isReference(expression.left) ? expression.left : expression.right, operator: "??" }; + case isExplicitNullishComparison(expression, scope): + return { reference: isReference(expression.left.left) ? expression.left.left : expression.left.right, operator: "??" }; + default: return null; + } +} + +/** + * Returns true iff the node is inside a with block + * @param {ASTNode} node Node to check + * @returns {boolean} True iff passed node is inside a with block + */ +function isInsideWithBlock(node) { + if (node.type === "Program") { + return false; + } + + return node.parent.type === "WithStatement" && node.parent.body === node ? true : isInsideWithBlock(node.parent); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require or disallow logical assignment operator shorthand", + recommended: false, + url: "https://eslint.org/docs/latest/rules/logical-assignment-operators" + }, + + schema: { + type: "array", + oneOf: [{ + items: [ + { const: "always" }, + { + type: "object", + properties: { + enforceForIfStatements: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + minItems: 0, // 0 for allowing passing no options + maxItems: 2 + }, { + items: [{ const: "never" }], + minItems: 1, + maxItems: 1 + }] + }, + fixable: "code", + hasSuggestions: true, + messages: { + assignment: "Assignment (=) can be replaced with operator assignment ({{operator}}).", + useLogicalOperator: "Convert this assignment to use the operator {{ operator }}.", + logical: "Logical expression can be replaced with an assignment ({{ operator }}).", + convertLogical: "Replace this logical expression with an assignment with the operator {{ operator }}.", + if: "'if' statement can be replaced with a logical operator assignment with operator {{ operator }}.", + convertIf: "Replace this 'if' statement with a logical assignment with operator {{ operator }}.", + unexpected: "Unexpected logical operator assignment ({{operator}}) shorthand.", + separate: "Separate the logical assignment into an assignment with a logical operator." + } + }, + + create(context) { + const mode = context.options[0] === "never" ? "never" : "always"; + const checkIf = mode === "always" && context.options.length > 1 && context.options[1].enforceForIfStatements; + const sourceCode = context.sourceCode; + const isStrict = sourceCode.getScope(sourceCode.ast).isStrict; + + /** + * Returns false if the access could be a getter + * @param {ASTNode} node Assignment expression + * @returns {boolean} True iff the fix is safe + */ + function cannotBeGetter(node) { + return node.type === "Identifier" && + (isStrict || !isInsideWithBlock(node)); + } + + /** + * Check whether only a single property is accessed + * @param {ASTNode} node reference + * @returns {boolean} True iff a single property is accessed + */ + function accessesSingleProperty(node) { + if (!isStrict && isInsideWithBlock(node)) { + return node.type === "Identifier"; + } + + return node.type === "MemberExpression" && + baseTypes.has(node.object.type) && + (!node.computed || (node.property.type !== "MemberExpression" && node.property.type !== "ChainExpression")); + } + + /** + * Adds a fixer or suggestion whether on the fix is safe. + * @param {{ messageId: string, node: ASTNode }} descriptor Report descriptor without fix or suggest + * @param {{ messageId: string, fix: Function }} suggestion Adds the fix or the whole suggestion as only element in "suggest" to suggestion + * @param {boolean} shouldBeFixed Fix iff the condition is true + * @returns {Object} Descriptor with either an added fix or suggestion + */ + function createConditionalFixer(descriptor, suggestion, shouldBeFixed) { + if (shouldBeFixed) { + return { + ...descriptor, + fix: suggestion.fix + }; + } + + return { + ...descriptor, + suggest: [suggestion] + }; + } + + + /** + * Returns the operator token for assignments and binary expressions + * @param {ASTNode} node AssignmentExpression or BinaryExpression + * @returns {import('eslint').AST.Token} Operator token between the left and right expression + */ + function getOperatorToken(node) { + return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); + } + + if (mode === "never") { + return { + + // foo ||= bar + "AssignmentExpression"(assignment) { + if (!astUtils.isLogicalAssignmentOperator(assignment.operator)) { + return; + } + + const descriptor = { + messageId: "unexpected", + node: assignment, + data: { operator: assignment.operator } + }; + const suggestion = { + messageId: "separate", + *fix(ruleFixer) { + if (sourceCode.getCommentsInside(assignment).length > 0) { + return; + } + + const operatorToken = getOperatorToken(assignment); + + // -> foo = bar + yield ruleFixer.replaceText(operatorToken, "="); + + const assignmentText = sourceCode.getText(assignment.left); + const operator = assignment.operator.slice(0, -1); + + // -> foo = foo || bar + yield ruleFixer.insertTextAfter(operatorToken, ` ${assignmentText} ${operator}`); + + const precedence = astUtils.getPrecedence(assignment.right) <= astUtils.getPrecedence({ type: "LogicalExpression", operator }); + + // ?? and || / && cannot be mixed but have same precedence + const mixed = assignment.operator === "??=" && astUtils.isLogicalExpression(assignment.right); + + if (!astUtils.isParenthesised(sourceCode, assignment.right) && (precedence || mixed)) { + + // -> foo = foo || (bar) + yield ruleFixer.insertTextBefore(assignment.right, "("); + yield ruleFixer.insertTextAfter(assignment.right, ")"); + } + } + }; + + context.report(createConditionalFixer(descriptor, suggestion, cannotBeGetter(assignment.left))); + } + }; + } + + return { + + // foo = foo || bar + "AssignmentExpression[operator='='][right.type='LogicalExpression']"(assignment) { + if (!astUtils.isSameReference(assignment.left, assignment.right.left)) { + return; + } + + const descriptor = { + messageId: "assignment", + node: assignment, + data: { operator: `${assignment.right.operator}=` } + }; + const suggestion = { + messageId: "useLogicalOperator", + data: { operator: `${assignment.right.operator}=` }, + *fix(ruleFixer) { + if (sourceCode.getCommentsInside(assignment).length > 0) { + return; + } + + // No need for parenthesis around the assignment based on precedence as the precedence stays the same even with changed operator + const assignmentOperatorToken = getOperatorToken(assignment); + + // -> foo ||= foo || bar + yield ruleFixer.insertTextBefore(assignmentOperatorToken, assignment.right.operator); + + // -> foo ||= bar + const logicalOperatorToken = getOperatorToken(assignment.right); + const firstRightOperandToken = sourceCode.getTokenAfter(logicalOperatorToken); + + yield ruleFixer.removeRange([assignment.right.range[0], firstRightOperandToken.range[0]]); + } + }; + + context.report(createConditionalFixer(descriptor, suggestion, cannotBeGetter(assignment.left))); + }, + + // foo || (foo = bar) + 'LogicalExpression[right.type="AssignmentExpression"][right.operator="="]'(logical) { + + // Right side has to be parenthesized, otherwise would be parsed as (foo || foo) = bar which is illegal + if (isReference(logical.left) && astUtils.isSameReference(logical.left, logical.right.left)) { + const descriptor = { + messageId: "logical", + node: logical, + data: { operator: `${logical.operator}=` } + }; + const suggestion = { + messageId: "convertLogical", + data: { operator: `${logical.operator}=` }, + *fix(ruleFixer) { + if (sourceCode.getCommentsInside(logical).length > 0) { + return; + } + + const parentPrecedence = astUtils.getPrecedence(logical.parent); + const requiresOuterParenthesis = logical.parent.type !== "ExpressionStatement" && ( + parentPrecedence === -1 || + astUtils.getPrecedence({ type: "AssignmentExpression" }) < parentPrecedence + ); + + if (!astUtils.isParenthesised(sourceCode, logical) && requiresOuterParenthesis) { + yield ruleFixer.insertTextBefore(logical, "("); + yield ruleFixer.insertTextAfter(logical, ")"); + } + + // Also removes all opening parenthesis + yield ruleFixer.removeRange([logical.range[0], logical.right.range[0]]); // -> foo = bar) + + // Also removes all ending parenthesis + yield ruleFixer.removeRange([logical.right.range[1], logical.range[1]]); // -> foo = bar + + const operatorToken = getOperatorToken(logical.right); + + yield ruleFixer.insertTextBefore(operatorToken, logical.operator); // -> foo ||= bar + } + }; + const fix = cannotBeGetter(logical.left) || accessesSingleProperty(logical.left); + + context.report(createConditionalFixer(descriptor, suggestion, fix)); + } + }, + + // if (foo) foo = bar + "IfStatement[alternate=null]"(ifNode) { + if (!checkIf) { + return; + } + + const hasBody = ifNode.consequent.type === "BlockStatement"; + + if (hasBody && ifNode.consequent.body.length !== 1) { + return; + } + + const body = hasBody ? ifNode.consequent.body[0] : ifNode.consequent; + const scope = sourceCode.getScope(ifNode); + const existence = getExistence(ifNode.test, scope); + + if ( + body.type === "ExpressionStatement" && + body.expression.type === "AssignmentExpression" && + body.expression.operator === "=" && + existence !== null && + astUtils.isSameReference(existence.reference, body.expression.left) + ) { + const descriptor = { + messageId: "if", + node: ifNode, + data: { operator: `${existence.operator}=` } + }; + const suggestion = { + messageId: "convertIf", + data: { operator: `${existence.operator}=` }, + *fix(ruleFixer) { + if (sourceCode.getCommentsInside(ifNode).length > 0) { + return; + } + + const firstBodyToken = sourceCode.getFirstToken(body); + const prevToken = sourceCode.getTokenBefore(ifNode); + + if ( + prevToken !== null && + prevToken.value !== ";" && + prevToken.value !== "{" && + firstBodyToken.type !== "Identifier" && + firstBodyToken.type !== "Keyword" + ) { + + // Do not fix if the fixed statement could be part of the previous statement (eg. fn() if (a == null) (a) = b --> fn()(a) ??= b) + return; + } + + + const operatorToken = getOperatorToken(body.expression); + + yield ruleFixer.insertTextBefore(operatorToken, existence.operator); // -> if (foo) foo ||= bar + + yield ruleFixer.removeRange([ifNode.range[0], body.range[0]]); // -> foo ||= bar + + yield ruleFixer.removeRange([body.range[1], ifNode.range[1]]); // -> foo ||= bar, only present if "if" had a body + + const nextToken = sourceCode.getTokenAfter(body.expression); + + if (hasBody && (nextToken !== null && nextToken.value !== ";")) { + yield ruleFixer.insertTextAfter(ifNode, ";"); + } + } + }; + const shouldBeFixed = cannotBeGetter(existence.reference) || + (ifNode.test.type !== "LogicalExpression" && accessesSingleProperty(existence.reference)); + + context.report(createConditionalFixer(descriptor, suggestion, shouldBeFixed)); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/max-classes-per-file.js b/node_modules/eslint/lib/rules/max-classes-per-file.js new file mode 100644 index 0000000..241e060 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-classes-per-file.js @@ -0,0 +1,89 @@ +/** + * @fileoverview Enforce a maximum number of classes per file + * @author James Garbutt + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of classes per file", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-classes-per-file" + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 1 + }, + { + type: "object", + properties: { + ignoreExpressions: { + type: "boolean" + }, + max: { + type: "integer", + minimum: 1 + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + maximumExceeded: "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}." + } + }, + create(context) { + const [option = {}] = context.options; + const [ignoreExpressions, max] = typeof option === "number" + ? [false, option || 1] + : [option.ignoreExpressions, option.max || 1]; + + let classCount = 0; + + return { + Program() { + classCount = 0; + }, + "Program:exit"(node) { + if (classCount > max) { + context.report({ + node, + messageId: "maximumExceeded", + data: { + classCount, + max + } + }); + } + }, + "ClassDeclaration"() { + classCount++; + }, + "ClassExpression"() { + if (!ignoreExpressions) { + classCount++; + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/max-depth.js b/node_modules/eslint/lib/rules/max-depth.js new file mode 100644 index 0000000..7a8e9f9 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-depth.js @@ -0,0 +1,156 @@ +/** + * @fileoverview A rule to set the maximum depth block can be nested in a function. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum depth that blocks can be nested", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-depth" + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0 + }, + max: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + } + ] + } + ], + messages: { + tooDeeply: "Blocks are nested too deeply ({{depth}}). Maximum allowed is {{maxDepth}}." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = [], + option = context.options[0]; + let maxDepth = 4; + + if ( + typeof option === "object" && + (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) + ) { + maxDepth = option.maximum || option.max; + } + if (typeof option === "number") { + maxDepth = option; + } + + /** + * When parsing a new function, store it in our function stack + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push(0); + } + + /** + * When parsing is done then pop out the reference + * @returns {void} + * @private + */ + function endFunction() { + functionStack.pop(); + } + + /** + * Save the block and Evaluate the node + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function pushBlock(node) { + const len = ++functionStack[functionStack.length - 1]; + + if (len > maxDepth) { + context.report({ node, messageId: "tooDeeply", data: { depth: len, maxDepth } }); + } + } + + /** + * Pop the saved block + * @returns {void} + * @private + */ + function popBlock() { + functionStack[functionStack.length - 1]--; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: startFunction, + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, + + IfStatement(node) { + if (node.parent.type !== "IfStatement") { + pushBlock(node); + } + }, + SwitchStatement: pushBlock, + TryStatement: pushBlock, + DoWhileStatement: pushBlock, + WhileStatement: pushBlock, + WithStatement: pushBlock, + ForStatement: pushBlock, + ForInStatement: pushBlock, + ForOfStatement: pushBlock, + + "IfStatement:exit": popBlock, + "SwitchStatement:exit": popBlock, + "TryStatement:exit": popBlock, + "DoWhileStatement:exit": popBlock, + "WhileStatement:exit": popBlock, + "WithStatement:exit": popBlock, + "ForStatement:exit": popBlock, + "ForInStatement:exit": popBlock, + "ForOfStatement:exit": popBlock, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction, + "Program:exit": endFunction + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/max-len.js b/node_modules/eslint/lib/rules/max-len.js new file mode 100644 index 0000000..53ad531 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-len.js @@ -0,0 +1,437 @@ +/** + * @fileoverview Rule to check for max length on a line. + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const OPTIONS_SCHEMA = { + type: "object", + properties: { + code: { + type: "integer", + minimum: 0 + }, + comments: { + type: "integer", + minimum: 0 + }, + tabWidth: { + type: "integer", + minimum: 0 + }, + ignorePattern: { + type: "string" + }, + ignoreComments: { + type: "boolean" + }, + ignoreStrings: { + type: "boolean" + }, + ignoreUrls: { + type: "boolean" + }, + ignoreTemplateLiterals: { + type: "boolean" + }, + ignoreRegExpLiterals: { + type: "boolean" + }, + ignoreTrailingComments: { + type: "boolean" + } + }, + additionalProperties: false +}; + +const OPTIONS_OR_INTEGER_SCHEMA = { + anyOf: [ + OPTIONS_SCHEMA, + { + type: "integer", + minimum: 0 + } + ] +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce a maximum line length", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-len" + }, + + schema: [ + OPTIONS_OR_INTEGER_SCHEMA, + OPTIONS_OR_INTEGER_SCHEMA, + OPTIONS_SCHEMA + ], + messages: { + max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.", + maxComment: "This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}." + } + }, + + create(context) { + + /* + * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however: + * - They're matching an entire string that we know is a URI + * - We're matching part of a string where we think there *might* be a URL + * - We're only concerned about URLs, as picking out any URI would cause + * too many false positives + * - We don't care about matching the entire URL, any small segment is fine + */ + const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u; + + const sourceCode = context.sourceCode; + + /** + * Computes the length of a line that may contain tabs. The width of each + * tab will be the number of spaces to the next tab stop. + * @param {string} line The line. + * @param {int} tabWidth The width of each tab stop in spaces. + * @returns {int} The computed line length. + * @private + */ + function computeLineLength(line, tabWidth) { + let extraCharacterCount = 0; + + line.replace(/\t/gu, (match, offset) => { + const totalOffset = offset + extraCharacterCount, + previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, + spaceCount = tabWidth - previousTabStopOffset; + + extraCharacterCount += spaceCount - 1; // -1 for the replaced tab + }); + return Array.from(line).length + extraCharacterCount; + } + + // The options object must be the last option specified… + const options = Object.assign({}, context.options[context.options.length - 1]); + + // …but max code length… + if (typeof context.options[0] === "number") { + options.code = context.options[0]; + } + + // …and tabWidth can be optionally specified directly as integers. + if (typeof context.options[1] === "number") { + options.tabWidth = context.options[1]; + } + + const maxLength = typeof options.code === "number" ? options.code : 80, + tabWidth = typeof options.tabWidth === "number" ? options.tabWidth : 4, + ignoreComments = !!options.ignoreComments, + ignoreStrings = !!options.ignoreStrings, + ignoreTemplateLiterals = !!options.ignoreTemplateLiterals, + ignoreRegExpLiterals = !!options.ignoreRegExpLiterals, + ignoreTrailingComments = !!options.ignoreTrailingComments || !!options.ignoreComments, + ignoreUrls = !!options.ignoreUrls, + maxCommentLength = options.comments; + let ignorePattern = options.ignorePattern || null; + + if (ignorePattern) { + ignorePattern = new RegExp(ignorePattern, "u"); + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tells if a given comment is trailing: it starts on the current line and + * extends to or past the end of the current line. + * @param {string} line The source line we want to check for a trailing comment on + * @param {number} lineNumber The one-indexed line number for line + * @param {ASTNode} comment The comment to inspect + * @returns {boolean} If the comment is trailing on the given line + */ + function isTrailingComment(line, lineNumber, comment) { + return comment && + (comment.loc.start.line === lineNumber && lineNumber <= comment.loc.end.line) && + (comment.loc.end.line > lineNumber || comment.loc.end.column === line.length); + } + + /** + * Tells if a comment encompasses the entire line. + * @param {string} line The source line with a trailing comment + * @param {number} lineNumber The one-indexed line number this is on + * @param {ASTNode} comment The comment to remove + * @returns {boolean} If the comment covers the entire line + */ + function isFullLineComment(line, lineNumber, comment) { + const start = comment.loc.start, + end = comment.loc.end, + isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim(); + + return comment && + (start.line < lineNumber || (start.line === lineNumber && isFirstTokenOnLine)) && + (end.line > lineNumber || (end.line === lineNumber && end.column === line.length)); + } + + /** + * Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer. + */ + function isJSXEmptyExpressionInSingleLineContainer(node) { + if (!node || !node.parent || node.type !== "JSXEmptyExpression" || node.parent.type !== "JSXExpressionContainer") { + return false; + } + + const parent = node.parent; + + return parent.loc.start.line === parent.loc.end.line; + } + + /** + * Gets the line after the comment and any remaining trailing whitespace is + * stripped. + * @param {string} line The source line with a trailing comment + * @param {ASTNode} comment The comment to remove + * @returns {string} Line without comment and trailing whitespace + */ + function stripTrailingComment(line, comment) { + + // loc.column is zero-indexed + return line.slice(0, comment.loc.start.column).replace(/\s+$/u, ""); + } + + /** + * Ensure that an array exists at [key] on `object`, and add `value` to it. + * @param {Object} object the object to mutate + * @param {string} key the object's key + * @param {any} value the value to add + * @returns {void} + * @private + */ + function ensureArrayAndPush(object, key, value) { + if (!Array.isArray(object[key])) { + object[key] = []; + } + object[key].push(value); + } + + /** + * Retrieves an array containing all strings (" or ') in the source code. + * @returns {ASTNode[]} An array of string nodes. + */ + function getAllStrings() { + return sourceCode.ast.tokens.filter(token => (token.type === "String" || + (token.type === "JSXText" && sourceCode.getNodeByRangeIndex(token.range[0] - 1).type === "JSXAttribute"))); + } + + /** + * Retrieves an array containing all template literals in the source code. + * @returns {ASTNode[]} An array of template literal nodes. + */ + function getAllTemplateLiterals() { + return sourceCode.ast.tokens.filter(token => token.type === "Template"); + } + + + /** + * Retrieves an array containing all RegExp literals in the source code. + * @returns {ASTNode[]} An array of RegExp literal nodes. + */ + function getAllRegExpLiterals() { + return sourceCode.ast.tokens.filter(token => token.type === "RegularExpression"); + } + + /** + * + * reduce an array of AST nodes by line number, both start and end. + * @param {ASTNode[]} arr array of AST nodes + * @returns {Object} accululated AST nodes + */ + function groupArrayByLineNumber(arr) { + const obj = {}; + + for (let i = 0; i < arr.length; i++) { + const node = arr[i]; + + for (let j = node.loc.start.line; j <= node.loc.end.line; ++j) { + ensureArrayAndPush(obj, j, node); + } + } + return obj; + } + + /** + * Returns an array of all comments in the source code. + * If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer, + * the element is changed with JSXExpressionContainer node. + * @returns {ASTNode[]} An array of comment nodes + */ + function getAllComments() { + const comments = []; + + sourceCode.getAllComments() + .forEach(commentNode => { + const containingNode = sourceCode.getNodeByRangeIndex(commentNode.range[0]); + + if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) { + + // push a unique node only + if (comments[comments.length - 1] !== containingNode.parent) { + comments.push(containingNode.parent); + } + } else { + comments.push(commentNode); + } + }); + + return comments; + } + + /** + * Check the program for max length + * @param {ASTNode} node Node to examine + * @returns {void} + * @private + */ + function checkProgramForMaxLength(node) { + + // split (honors line-ending) + const lines = sourceCode.lines, + + // list of comments to ignore + comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? getAllComments() : []; + + // we iterate over comments in parallel with the lines + let commentsIndex = 0; + + const strings = getAllStrings(); + const stringsByLine = groupArrayByLineNumber(strings); + + const templateLiterals = getAllTemplateLiterals(); + const templateLiteralsByLine = groupArrayByLineNumber(templateLiterals); + + const regExpLiterals = getAllRegExpLiterals(); + const regExpLiteralsByLine = groupArrayByLineNumber(regExpLiterals); + + lines.forEach((line, i) => { + + // i is zero-indexed, line numbers are one-indexed + const lineNumber = i + 1; + + /* + * if we're checking comment length; we need to know whether this + * line is a comment + */ + let lineIsComment = false; + let textToMeasure; + + /* + * We can short-circuit the comment checks if we're already out of + * comments to check. + */ + if (commentsIndex < comments.length) { + let comment = null; + + // iterate over comments until we find one past the current line + do { + comment = comments[++commentsIndex]; + } while (comment && comment.loc.start.line <= lineNumber); + + // and step back by one + comment = comments[--commentsIndex]; + + if (isFullLineComment(line, lineNumber, comment)) { + lineIsComment = true; + textToMeasure = line; + } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) { + textToMeasure = stripTrailingComment(line, comment); + + // ignore multiple trailing comments in the same line + let lastIndex = commentsIndex; + + while (isTrailingComment(textToMeasure, lineNumber, comments[--lastIndex])) { + textToMeasure = stripTrailingComment(textToMeasure, comments[lastIndex]); + } + } else { + textToMeasure = line; + } + } else { + textToMeasure = line; + } + if (ignorePattern && ignorePattern.test(textToMeasure) || + ignoreUrls && URL_REGEXP.test(textToMeasure) || + ignoreStrings && stringsByLine[lineNumber] || + ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || + ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] + ) { + + // ignore this line + return; + } + + const lineLength = computeLineLength(textToMeasure, tabWidth); + const commentLengthApplies = lineIsComment && maxCommentLength; + + if (lineIsComment && ignoreComments) { + return; + } + + const loc = { + start: { + line: lineNumber, + column: 0 + }, + end: { + line: lineNumber, + column: textToMeasure.length + } + }; + + if (commentLengthApplies) { + if (lineLength > maxCommentLength) { + context.report({ + node, + loc, + messageId: "maxComment", + data: { + lineLength, + maxCommentLength + } + }); + } + } else if (lineLength > maxLength) { + context.report({ + node, + loc, + messageId: "max", + data: { + lineLength, + maxLength + } + }); + } + }); + } + + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: checkProgramForMaxLength + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/max-lines-per-function.js b/node_modules/eslint/lib/rules/max-lines-per-function.js new file mode 100644 index 0000000..f981922 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-lines-per-function.js @@ -0,0 +1,213 @@ +/** + * @fileoverview A rule to set the maximum number of line of code in a function. + * @author Pete Ward + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const OPTIONS_SCHEMA = { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0 + }, + skipComments: { + type: "boolean" + }, + skipBlankLines: { + type: "boolean" + }, + IIFEs: { + type: "boolean" + } + }, + additionalProperties: false +}; + +const OPTIONS_OR_INTEGER_SCHEMA = { + oneOf: [ + OPTIONS_SCHEMA, + { + type: "integer", + minimum: 1 + } + ] +}; + +/** + * Given a list of comment nodes, return a map with numeric keys (source code line numbers) and comment token values. + * @param {Array} comments An array of comment nodes. + * @returns {Map} A map with numeric keys (source code line numbers) and comment token values. + */ +function getCommentLineNumbers(comments) { + const map = new Map(); + + comments.forEach(comment => { + for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) { + map.set(i, comment); + } + }); + return map; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of lines of code in a function", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-lines-per-function" + }, + + schema: [ + OPTIONS_OR_INTEGER_SCHEMA + ], + messages: { + exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const lines = sourceCode.lines; + + const option = context.options[0]; + let maxLines = 50; + let skipComments = false; + let skipBlankLines = false; + let IIFEs = false; + + if (typeof option === "object") { + maxLines = typeof option.max === "number" ? option.max : 50; + skipComments = !!option.skipComments; + skipBlankLines = !!option.skipBlankLines; + IIFEs = !!option.IIFEs; + } else if (typeof option === "number") { + maxLines = option; + } + + const commentLineNumbers = getCommentLineNumbers(sourceCode.getAllComments()); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tells if a comment encompasses the entire line. + * @param {string} line The source line with a trailing comment + * @param {number} lineNumber The one-indexed line number this is on + * @param {ASTNode} comment The comment to remove + * @returns {boolean} If the comment covers the entire line + */ + function isFullLineComment(line, lineNumber, comment) { + const start = comment.loc.start, + end = comment.loc.end, + isFirstTokenOnLine = start.line === lineNumber && !line.slice(0, start.column).trim(), + isLastTokenOnLine = end.line === lineNumber && !line.slice(end.column).trim(); + + return comment && + (start.line < lineNumber || isFirstTokenOnLine) && + (end.line > lineNumber || isLastTokenOnLine); + } + + /** + * Identifies is a node is a FunctionExpression which is part of an IIFE + * @param {ASTNode} node Node to test + * @returns {boolean} True if it's an IIFE + */ + function isIIFE(node) { + return (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node; + } + + /** + * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property + * @param {ASTNode} node Node to test + * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property + */ + function isEmbedded(node) { + if (!node.parent) { + return false; + } + if (node !== node.parent.value) { + return false; + } + if (node.parent.type === "MethodDefinition") { + return true; + } + if (node.parent.type === "Property") { + return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set"; + } + return false; + } + + /** + * Count the lines in the function + * @param {ASTNode} funcNode Function AST node + * @returns {void} + * @private + */ + function processFunction(funcNode) { + const node = isEmbedded(funcNode) ? funcNode.parent : funcNode; + + if (!IIFEs && isIIFE(node)) { + return; + } + let lineCount = 0; + + for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) { + const line = lines[i]; + + if (skipComments) { + if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) { + continue; + } + } + + if (skipBlankLines) { + if (line.match(/^\s*$/u)) { + continue; + } + } + + lineCount++; + } + + if (lineCount > maxLines) { + const name = upperCaseFirst(astUtils.getFunctionNameWithKind(funcNode)); + + context.report({ + node, + messageId: "exceed", + data: { name, lineCount, maxLines } + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: processFunction, + FunctionExpression: processFunction, + ArrowFunctionExpression: processFunction + }; + } +}; diff --git a/node_modules/eslint/lib/rules/max-lines.js b/node_modules/eslint/lib/rules/max-lines.js new file mode 100644 index 0000000..e85d442 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-lines.js @@ -0,0 +1,193 @@ +/** + * @fileoverview enforce a maximum file length + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Creates an array of numbers from `start` up to, but not including, `end` + * @param {number} start The start of the range + * @param {number} end The end of the range + * @returns {number[]} The range of numbers + */ +function range(start, end) { + return [...Array(end - start).keys()].map(x => x + start); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of lines per file", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-lines" + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0 + }, + skipComments: { + type: "boolean" + }, + skipBlankLines: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + } + ], + messages: { + exceed: + "File has too many lines ({{actual}}). Maximum allowed is {{max}}." + } + }, + + create(context) { + const option = context.options[0]; + let max = 300; + + if ( + typeof option === "object" && + Object.prototype.hasOwnProperty.call(option, "max") + ) { + max = option.max; + } else if (typeof option === "number") { + max = option; + } + + const skipComments = option && option.skipComments; + const skipBlankLines = option && option.skipBlankLines; + + const sourceCode = context.sourceCode; + + /** + * Returns whether or not a token is a comment node type + * @param {Token} token The token to check + * @returns {boolean} True if the token is a comment node + */ + function isCommentNodeType(token) { + return token && (token.type === "Block" || token.type === "Line"); + } + + /** + * Returns the line numbers of a comment that don't have any code on the same line + * @param {Node} comment The comment node to check + * @returns {number[]} The line numbers + */ + function getLinesWithoutCode(comment) { + let start = comment.loc.start.line; + let end = comment.loc.end.line; + + let token; + + token = comment; + do { + token = sourceCode.getTokenBefore(token, { + includeComments: true + }); + } while (isCommentNodeType(token)); + + if (token && astUtils.isTokenOnSameLine(token, comment)) { + start += 1; + } + + token = comment; + do { + token = sourceCode.getTokenAfter(token, { + includeComments: true + }); + } while (isCommentNodeType(token)); + + if (token && astUtils.isTokenOnSameLine(comment, token)) { + end -= 1; + } + + if (start <= end) { + return range(start, end + 1); + } + return []; + } + + return { + "Program:exit"() { + let lines = sourceCode.lines.map((text, i) => ({ + lineNumber: i + 1, + text + })); + + /* + * If file ends with a linebreak, `sourceCode.lines` will have one extra empty line at the end. + * That isn't a real line, so we shouldn't count it. + */ + if (lines.length > 1 && lines[lines.length - 1].text === "") { + lines.pop(); + } + + if (skipBlankLines) { + lines = lines.filter(l => l.text.trim() !== ""); + } + + if (skipComments) { + const comments = sourceCode.getAllComments(); + + const commentLines = new Set(comments.flatMap(getLinesWithoutCode)); + + lines = lines.filter( + l => !commentLines.has(l.lineNumber) + ); + } + + if (lines.length > max) { + const loc = { + start: { + line: lines[max].lineNumber, + column: 0 + }, + end: { + line: sourceCode.lines.length, + column: sourceCode.lines[sourceCode.lines.length - 1].length + } + }; + + context.report({ + loc, + messageId: "exceed", + data: { + max, + actual: lines.length + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/max-nested-callbacks.js b/node_modules/eslint/lib/rules/max-nested-callbacks.js new file mode 100644 index 0000000..d8f380b --- /dev/null +++ b/node_modules/eslint/lib/rules/max-nested-callbacks.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Rule to enforce a maximum number of nested callbacks. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum depth that callbacks can be nested", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-nested-callbacks" + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0 + }, + max: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + } + ] + } + ], + messages: { + exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Constants + //-------------------------------------------------------------------------- + const option = context.options[0]; + let THRESHOLD = 10; + + if ( + typeof option === "object" && + (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) + ) { + THRESHOLD = option.maximum || option.max; + } else if (typeof option === "number") { + THRESHOLD = option; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const callbackStack = []; + + /** + * Checks a given function node for too many callbacks. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + const parent = node.parent; + + if (parent.type === "CallExpression") { + callbackStack.push(node); + } + + if (callbackStack.length > THRESHOLD) { + const opts = { num: callbackStack.length, max: THRESHOLD }; + + context.report({ node, messageId: "exceed", data: opts }); + } + } + + /** + * Pops the call stack. + * @returns {void} + * @private + */ + function popStack() { + callbackStack.pop(); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + ArrowFunctionExpression: checkFunction, + "ArrowFunctionExpression:exit": popStack, + + FunctionExpression: checkFunction, + "FunctionExpression:exit": popStack + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/max-params.js b/node_modules/eslint/lib/rules/max-params.js new file mode 100644 index 0000000..213477a --- /dev/null +++ b/node_modules/eslint/lib/rules/max-params.js @@ -0,0 +1,102 @@ +/** + * @fileoverview Rule to flag when a function has too many parameters + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of parameters in function definitions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-params" + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0 + }, + max: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + } + ] + } + ], + messages: { + exceed: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0]; + let numParams = 3; + + if ( + typeof option === "object" && + (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) + ) { + numParams = option.maximum || option.max; + } + if (typeof option === "number") { + numParams = option; + } + + /** + * Checks a function to see if it has too many parameters. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + if (node.params.length > numParams) { + context.report({ + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + node, + messageId: "exceed", + data: { + name: upperCaseFirst(astUtils.getFunctionNameWithKind(node)), + count: node.params.length, + max: numParams + } + }); + } + } + + return { + FunctionDeclaration: checkFunction, + ArrowFunctionExpression: checkFunction, + FunctionExpression: checkFunction + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/max-statements-per-line.js b/node_modules/eslint/lib/rules/max-statements-per-line.js new file mode 100644 index 0000000..b966504 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-statements-per-line.js @@ -0,0 +1,196 @@ +/** + * @fileoverview Specify the maximum number of statements allowed per line. + * @author Kenneth Williams + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce a maximum number of statements allowed per line", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-statements-per-line" + }, + + schema: [ + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 1, + default: 1 + } + }, + additionalProperties: false + } + ], + messages: { + exceed: "This line has {{numberOfStatementsOnThisLine}} {{statements}}. Maximum allowed is {{maxStatementsPerLine}}." + } + }, + + create(context) { + + const sourceCode = context.sourceCode, + options = context.options[0] || {}, + maxStatementsPerLine = typeof options.max !== "undefined" ? options.max : 1; + + let lastStatementLine = 0, + numberOfStatementsOnThisLine = 0, + firstExtraStatement; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const SINGLE_CHILD_ALLOWED = /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/u; + + /** + * Reports with the first extra statement, and clears it. + * @returns {void} + */ + function reportFirstExtraStatementAndClear() { + if (firstExtraStatement) { + context.report({ + node: firstExtraStatement, + messageId: "exceed", + data: { + numberOfStatementsOnThisLine, + maxStatementsPerLine, + statements: numberOfStatementsOnThisLine === 1 ? "statement" : "statements" + } + }); + } + firstExtraStatement = null; + } + + /** + * Gets the actual last token of a given node. + * @param {ASTNode} node A node to get. This is a node except EmptyStatement. + * @returns {Token} The actual last token. + */ + function getActualLastToken(node) { + return sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); + } + + /** + * Addresses a given node. + * It updates the state of this rule, then reports the node if the node violated this rule. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function enterStatement(node) { + const line = node.loc.start.line; + + /* + * Skip to allow non-block statements if this is direct child of control statements. + * `if (a) foo();` is counted as 1. + * But `if (a) foo(); else foo();` should be counted as 2. + */ + if (SINGLE_CHILD_ALLOWED.test(node.parent.type) && + node.parent.alternate !== node + ) { + return; + } + + // Update state. + if (line === lastStatementLine) { + numberOfStatementsOnThisLine += 1; + } else { + reportFirstExtraStatementAndClear(); + numberOfStatementsOnThisLine = 1; + lastStatementLine = line; + } + + // Reports if the node violated this rule. + if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) { + firstExtraStatement = firstExtraStatement || node; + } + } + + /** + * Updates the state of this rule with the end line of leaving node to check with the next statement. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function leaveStatement(node) { + const line = getActualLastToken(node).loc.end.line; + + // Update state. + if (line !== lastStatementLine) { + reportFirstExtraStatementAndClear(); + numberOfStatementsOnThisLine = 1; + lastStatementLine = line; + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + BreakStatement: enterStatement, + ClassDeclaration: enterStatement, + ContinueStatement: enterStatement, + DebuggerStatement: enterStatement, + DoWhileStatement: enterStatement, + ExpressionStatement: enterStatement, + ForInStatement: enterStatement, + ForOfStatement: enterStatement, + ForStatement: enterStatement, + FunctionDeclaration: enterStatement, + IfStatement: enterStatement, + ImportDeclaration: enterStatement, + LabeledStatement: enterStatement, + ReturnStatement: enterStatement, + SwitchStatement: enterStatement, + ThrowStatement: enterStatement, + TryStatement: enterStatement, + VariableDeclaration: enterStatement, + WhileStatement: enterStatement, + WithStatement: enterStatement, + ExportNamedDeclaration: enterStatement, + ExportDefaultDeclaration: enterStatement, + ExportAllDeclaration: enterStatement, + + "BreakStatement:exit": leaveStatement, + "ClassDeclaration:exit": leaveStatement, + "ContinueStatement:exit": leaveStatement, + "DebuggerStatement:exit": leaveStatement, + "DoWhileStatement:exit": leaveStatement, + "ExpressionStatement:exit": leaveStatement, + "ForInStatement:exit": leaveStatement, + "ForOfStatement:exit": leaveStatement, + "ForStatement:exit": leaveStatement, + "FunctionDeclaration:exit": leaveStatement, + "IfStatement:exit": leaveStatement, + "ImportDeclaration:exit": leaveStatement, + "LabeledStatement:exit": leaveStatement, + "ReturnStatement:exit": leaveStatement, + "SwitchStatement:exit": leaveStatement, + "ThrowStatement:exit": leaveStatement, + "TryStatement:exit": leaveStatement, + "VariableDeclaration:exit": leaveStatement, + "WhileStatement:exit": leaveStatement, + "WithStatement:exit": leaveStatement, + "ExportNamedDeclaration:exit": leaveStatement, + "ExportDefaultDeclaration:exit": leaveStatement, + "ExportAllDeclaration:exit": leaveStatement, + "Program:exit": reportFirstExtraStatementAndClear + }; + } +}; diff --git a/node_modules/eslint/lib/rules/max-statements.js b/node_modules/eslint/lib/rules/max-statements.js new file mode 100644 index 0000000..7805383 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-statements.js @@ -0,0 +1,184 @@ +/** + * @fileoverview A rule to set the maximum number of statements in a function. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of statements allowed in function blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-statements" + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0 + }, + max: { + type: "integer", + minimum: 0 + } + }, + additionalProperties: false + } + ] + }, + { + type: "object", + properties: { + ignoreTopLevelFunctions: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + messages: { + exceed: "{{name}} has too many statements ({{count}}). Maximum allowed is {{max}}." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = [], + option = context.options[0], + ignoreTopLevelFunctions = context.options[1] && context.options[1].ignoreTopLevelFunctions || false, + topLevelFunctions = []; + let maxStatements = 10; + + if ( + typeof option === "object" && + (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) + ) { + maxStatements = option.maximum || option.max; + } else if (typeof option === "number") { + maxStatements = option; + } + + /** + * Reports a node if it has too many statements + * @param {ASTNode} node node to evaluate + * @param {int} count Number of statements in node + * @param {int} max Maximum number of statements allowed + * @returns {void} + * @private + */ + function reportIfTooManyStatements(node, count, max) { + if (count > max) { + const name = upperCaseFirst(astUtils.getFunctionNameWithKind(node)); + + context.report({ + node, + messageId: "exceed", + data: { name, count, max } + }); + } + } + + /** + * When parsing a new function, store it in our function stack + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push(0); + } + + /** + * Evaluate the node at the end of function + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function endFunction(node) { + const count = functionStack.pop(); + + /* + * This rule does not apply to class static blocks, but we have to track them so + * that statements in them do not count as statements in the enclosing function. + */ + if (node.type === "StaticBlock") { + return; + } + + if (ignoreTopLevelFunctions && functionStack.length === 0) { + topLevelFunctions.push({ node, count }); + } else { + reportIfTooManyStatements(node, count, maxStatements); + } + } + + /** + * Increment the count of the functions + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function countStatements(node) { + functionStack[functionStack.length - 1] += node.body.length; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, + + BlockStatement: countStatements, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction, + + "Program:exit"() { + if (topLevelFunctions.length === 1) { + return; + } + + topLevelFunctions.forEach(element => { + const count = element.count; + const node = element.node; + + reportIfTooManyStatements(node, count, maxStatements); + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/multiline-comment-style.js b/node_modules/eslint/lib/rules/multiline-comment-style.js new file mode 100644 index 0000000..6da9862 --- /dev/null +++ b/node_modules/eslint/lib/rules/multiline-comment-style.js @@ -0,0 +1,474 @@ +/** + * @fileoverview enforce a particular style for multiline comments + * @author Teddy Katz + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a particular style for multiline comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/multiline-comment-style" + }, + + fixable: "whitespace", + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["starred-block", "bare-block"] + } + ], + additionalItems: false + }, + { + type: "array", + items: [ + { + enum: ["separate-lines"] + }, + { + type: "object", + properties: { + checkJSDoc: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + additionalItems: false + } + ] + }, + messages: { + expectedBlock: "Expected a block comment instead of consecutive line comments.", + expectedBareBlock: "Expected a block comment without padding stars.", + startNewline: "Expected a linebreak after '/*'.", + endNewline: "Expected a linebreak before '*/'.", + missingStar: "Expected a '*' at the start of this line.", + alignment: "Expected this line to be aligned with the start of the comment.", + expectedLines: "Expected multiple line comments instead of a block comment." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "starred-block"; + const params = context.options[1] || {}; + const checkJSDoc = !!params.checkJSDoc; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks if a comment line is starred. + * @param {string} line A string representing a comment line. + * @returns {boolean} Whether or not the comment line is starred. + */ + function isStarredCommentLine(line) { + return /^\s*\*/u.test(line); + } + + /** + * Checks if a comment group is in starred-block form. + * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment. + * @returns {boolean} Whether or not the comment group is in starred block form. + */ + function isStarredBlockComment([firstComment]) { + if (firstComment.type !== "Block") { + return false; + } + + const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); + + // The first and last lines can only contain whitespace. + return lines.length > 0 && lines.every((line, i) => (i === 0 || i === lines.length - 1 ? /^\s*$/u : /^\s*\*/u).test(line)); + } + + /** + * Checks if a comment group is in JSDoc form. + * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment. + * @returns {boolean} Whether or not the comment group is in JSDoc form. + */ + function isJSDocComment([firstComment]) { + if (firstComment.type !== "Block") { + return false; + } + + const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); + + return /^\*\s*$/u.test(lines[0]) && + lines.slice(1, -1).every(line => /^\s* /u.test(line)) && + /^\s*$/u.test(lines[lines.length - 1]); + } + + /** + * Processes a comment group that is currently in separate-line form, calculating the offset for each line. + * @param {Token[]} commentGroup A group of comments containing multiple line comments. + * @returns {string[]} An array of the processed lines. + */ + function processSeparateLineComments(commentGroup) { + const allLinesHaveLeadingSpace = commentGroup + .map(({ value }) => value) + .filter(line => line.trim().length) + .every(line => line.startsWith(" ")); + + return commentGroup.map(({ value }) => (allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value)); + } + + /** + * Processes a comment group that is currently in starred-block form, calculating the offset for each line. + * @param {Token} comment A single block comment token in starred-block form. + * @returns {string[]} An array of the processed lines. + */ + function processStarredBlockComment(comment) { + const lines = comment.value.split(astUtils.LINEBREAK_MATCHER) + .filter((line, i, linesArr) => !(i === 0 || i === linesArr.length - 1)) + .map(line => line.replace(/^\s*$/u, "")); + const allLinesHaveLeadingSpace = lines + .map(line => line.replace(/\s*\*/u, "")) + .filter(line => line.trim().length) + .every(line => line.startsWith(" ")); + + return lines.map(line => line.replace(allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, "")); + } + + /** + * Processes a comment group that is currently in bare-block form, calculating the offset for each line. + * @param {Token} comment A single block comment token in bare-block form. + * @returns {string[]} An array of the processed lines. + */ + function processBareBlockComment(comment) { + const lines = comment.value.split(astUtils.LINEBREAK_MATCHER).map(line => line.replace(/^\s*$/u, "")); + const leadingWhitespace = `${sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0])} `; + let offset = ""; + + /* + * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines. + * The first line should not be checked because it is inline with the opening block comment delimiter. + */ + for (const [i, line] of lines.entries()) { + if (!line.trim().length || i === 0) { + continue; + } + + const [, lineOffset] = line.match(/^(\s*\*?\s*)/u); + + if (lineOffset.length < leadingWhitespace.length) { + const newOffset = leadingWhitespace.slice(lineOffset.length - leadingWhitespace.length); + + if (newOffset.length > offset.length) { + offset = newOffset; + } + } + } + + return lines.map(line => { + const match = line.match(/^(\s*\*?\s*)(.*)/u); + const [, lineOffset, lineContents] = match; + + if (lineOffset.length > leadingWhitespace.length) { + return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`; + } + + if (lineOffset.length < leadingWhitespace.length) { + return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`; + } + + return lineContents; + }); + } + + /** + * Gets a list of comment lines in a group, formatting leading whitespace as necessary. + * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment. + * @returns {string[]} A list of comment lines. + */ + function getCommentLines(commentGroup) { + const [firstComment] = commentGroup; + + if (firstComment.type === "Line") { + return processSeparateLineComments(commentGroup); + } + + if (isStarredBlockComment(commentGroup)) { + return processStarredBlockComment(firstComment); + } + + return processBareBlockComment(firstComment); + } + + /** + * Gets the initial offset (whitespace) from the beginning of a line to a given comment token. + * @param {Token} comment The token to check. + * @returns {string} The offset from the beginning of a line to the token. + */ + function getInitialOffset(comment) { + return sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0]); + } + + /** + * Converts a comment into starred-block form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers + */ + function convertToStarredBlock(firstComment, commentLinesList) { + const initialOffset = getInitialOffset(firstComment); + + return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */`; + } + + /** + * Converts a comment into separate-line form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in separate-line form + */ + function convertToSeparateLines(firstComment, commentLinesList) { + return commentLinesList.map(line => `// ${line}`).join(`\n${getInitialOffset(firstComment)}`); + } + + /** + * Converts a comment into bare-block form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in bare-block form + */ + function convertToBlock(firstComment, commentLinesList) { + return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)} `)} */`; + } + + /** + * Each method checks a group of comments to see if it's valid according to the given option. + * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single + * block comment or multiple line comments. + * @returns {void} + */ + const commentGroupCheckers = { + "starred-block"(commentGroup) { + const [firstComment] = commentGroup; + const commentLines = getCommentLines(commentGroup); + + if (commentLines.some(value => value.includes("*/"))) { + return; + } + + if (commentGroup.length > 1) { + context.report({ + loc: { + start: firstComment.loc.start, + end: commentGroup[commentGroup.length - 1].loc.end + }, + messageId: "expectedBlock", + fix(fixer) { + const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]]; + + return commentLines.some(value => value.startsWith("/")) + ? null + : fixer.replaceTextRange(range, convertToStarredBlock(firstComment, commentLines)); + } + }); + } else { + const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); + const expectedLeadingWhitespace = getInitialOffset(firstComment); + const expectedLinePrefix = `${expectedLeadingWhitespace} *`; + + if (!/^\*?\s*$/u.test(lines[0])) { + const start = firstComment.value.startsWith("*") ? firstComment.range[0] + 1 : firstComment.range[0]; + + context.report({ + loc: { + start: firstComment.loc.start, + end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } + }, + messageId: "startNewline", + fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`) + }); + } + + if (!/^\s*$/u.test(lines[lines.length - 1])) { + context.report({ + loc: { + start: { line: firstComment.loc.end.line, column: firstComment.loc.end.column - 2 }, + end: firstComment.loc.end + }, + messageId: "endNewline", + fix: fixer => fixer.replaceTextRange([firstComment.range[1] - 2, firstComment.range[1]], `\n${expectedLinePrefix}/`) + }); + } + + for (let lineNumber = firstComment.loc.start.line + 1; lineNumber <= firstComment.loc.end.line; lineNumber++) { + const lineText = sourceCode.lines[lineNumber - 1]; + const errorType = isStarredCommentLine(lineText) + ? "alignment" + : "missingStar"; + + if (!lineText.startsWith(expectedLinePrefix)) { + context.report({ + loc: { + start: { line: lineNumber, column: 0 }, + end: { line: lineNumber, column: lineText.length } + }, + messageId: errorType, + fix(fixer) { + const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 }); + + if (errorType === "alignment") { + const [, commentTextPrefix = ""] = lineText.match(/^(\s*\*)/u) || []; + const commentTextStartIndex = lineStartIndex + commentTextPrefix.length; + + return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], expectedLinePrefix); + } + + const [, commentTextPrefix = ""] = lineText.match(/^(\s*)/u) || []; + const commentTextStartIndex = lineStartIndex + commentTextPrefix.length; + let offset; + + for (const [idx, line] of lines.entries()) { + if (!/\S+/u.test(line)) { + continue; + } + + const lineTextToAlignWith = sourceCode.lines[firstComment.loc.start.line - 1 + idx]; + const [, prefix = "", initialOffset = ""] = lineTextToAlignWith.match(/^(\s*(?:\/?\*)?(\s*))/u) || []; + + offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}`; + + if (/^\s*\//u.test(lineText) && offset.length === 0) { + offset += " "; + } + break; + } + + return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], `${expectedLinePrefix}${offset}`); + } + }); + } + } + } + }, + "separate-lines"(commentGroup) { + const [firstComment] = commentGroup; + + const isJSDoc = isJSDocComment(commentGroup); + + if (firstComment.type !== "Block" || (!checkJSDoc && isJSDoc)) { + return; + } + + let commentLines = getCommentLines(commentGroup); + + if (isJSDoc) { + commentLines = commentLines.slice(1, commentLines.length - 1); + } + + const tokenAfter = sourceCode.getTokenAfter(firstComment, { includeComments: true }); + + if (tokenAfter && firstComment.loc.end.line === tokenAfter.loc.start.line) { + return; + } + + context.report({ + loc: { + start: firstComment.loc.start, + end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } + }, + messageId: "expectedLines", + fix(fixer) { + return fixer.replaceText(firstComment, convertToSeparateLines(firstComment, commentLines)); + } + }); + }, + "bare-block"(commentGroup) { + if (isJSDocComment(commentGroup)) { + return; + } + + const [firstComment] = commentGroup; + const commentLines = getCommentLines(commentGroup); + + // Disallows consecutive line comments in favor of using a block comment. + if (firstComment.type === "Line" && commentLines.length > 1 && + !commentLines.some(value => value.includes("*/"))) { + context.report({ + loc: { + start: firstComment.loc.start, + end: commentGroup[commentGroup.length - 1].loc.end + }, + messageId: "expectedBlock", + fix(fixer) { + return fixer.replaceTextRange( + [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]], + convertToBlock(firstComment, commentLines) + ); + } + }); + } + + // Prohibits block comments from having a * at the beginning of each line. + if (isStarredBlockComment(commentGroup)) { + context.report({ + loc: { + start: firstComment.loc.start, + end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } + }, + messageId: "expectedBareBlock", + fix(fixer) { + return fixer.replaceText(firstComment, convertToBlock(firstComment, commentLines)); + } + }); + } + } + }; + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + Program() { + return sourceCode.getAllComments() + .filter(comment => comment.type !== "Shebang") + .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value)) + .filter(comment => { + const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); + + return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line; + }) + .reduce((commentGroups, comment, index, commentList) => { + const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); + + if ( + comment.type === "Line" && + index && commentList[index - 1].type === "Line" && + tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 && + tokenBefore === commentList[index - 1] + ) { + commentGroups[commentGroups.length - 1].push(comment); + } else { + commentGroups.push([comment]); + } + + return commentGroups; + }, []) + .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line)) + .forEach(commentGroupCheckers[option]); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/multiline-ternary.js b/node_modules/eslint/lib/rules/multiline-ternary.js new file mode 100644 index 0000000..f156fe3 --- /dev/null +++ b/node_modules/eslint/lib/rules/multiline-ternary.js @@ -0,0 +1,171 @@ +/** + * @fileoverview Enforce newlines between operands of ternary expressions + * @author Kai Cataldo + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce newlines between operands of ternary expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/multiline-ternary" + }, + + schema: [ + { + enum: ["always", "always-multiline", "never"] + } + ], + + messages: { + expectedTestCons: "Expected newline between test and consequent of ternary expression.", + expectedConsAlt: "Expected newline between consequent and alternate of ternary expression.", + unexpectedTestCons: "Unexpected newline between test and consequent of ternary expression.", + unexpectedConsAlt: "Unexpected newline between consequent and alternate of ternary expression." + }, + + fixable: "whitespace" + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0]; + const multiline = option !== "never"; + const allowSingleLine = option === "always-multiline"; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ConditionalExpression(node) { + const questionToken = sourceCode.getTokenAfter(node.test, astUtils.isNotClosingParenToken); + const colonToken = sourceCode.getTokenAfter(node.consequent, astUtils.isNotClosingParenToken); + + const firstTokenOfTest = sourceCode.getFirstToken(node); + const lastTokenOfTest = sourceCode.getTokenBefore(questionToken); + const firstTokenOfConsequent = sourceCode.getTokenAfter(questionToken); + const lastTokenOfConsequent = sourceCode.getTokenBefore(colonToken); + const firstTokenOfAlternate = sourceCode.getTokenAfter(colonToken); + + const areTestAndConsequentOnSameLine = astUtils.isTokenOnSameLine(lastTokenOfTest, firstTokenOfConsequent); + const areConsequentAndAlternateOnSameLine = astUtils.isTokenOnSameLine(lastTokenOfConsequent, firstTokenOfAlternate); + + const hasComments = !!sourceCode.getCommentsInside(node).length; + + if (!multiline) { + if (!areTestAndConsequentOnSameLine) { + context.report({ + node: node.test, + loc: { + start: firstTokenOfTest.loc.start, + end: lastTokenOfTest.loc.end + }, + messageId: "unexpectedTestCons", + fix(fixer) { + if (hasComments) { + return null; + } + const fixers = []; + const areTestAndQuestionOnSameLine = astUtils.isTokenOnSameLine(lastTokenOfTest, questionToken); + const areQuestionAndConsOnSameLine = astUtils.isTokenOnSameLine(questionToken, firstTokenOfConsequent); + + if (!areTestAndQuestionOnSameLine) { + fixers.push(fixer.removeRange([lastTokenOfTest.range[1], questionToken.range[0]])); + } + if (!areQuestionAndConsOnSameLine) { + fixers.push(fixer.removeRange([questionToken.range[1], firstTokenOfConsequent.range[0]])); + } + + return fixers; + } + }); + } + + if (!areConsequentAndAlternateOnSameLine) { + context.report({ + node: node.consequent, + loc: { + start: firstTokenOfConsequent.loc.start, + end: lastTokenOfConsequent.loc.end + }, + messageId: "unexpectedConsAlt", + fix(fixer) { + if (hasComments) { + return null; + } + const fixers = []; + const areConsAndColonOnSameLine = astUtils.isTokenOnSameLine(lastTokenOfConsequent, colonToken); + const areColonAndAltOnSameLine = astUtils.isTokenOnSameLine(colonToken, firstTokenOfAlternate); + + if (!areConsAndColonOnSameLine) { + fixers.push(fixer.removeRange([lastTokenOfConsequent.range[1], colonToken.range[0]])); + } + if (!areColonAndAltOnSameLine) { + fixers.push(fixer.removeRange([colonToken.range[1], firstTokenOfAlternate.range[0]])); + } + + return fixers; + } + }); + } + } else { + if (allowSingleLine && node.loc.start.line === node.loc.end.line) { + return; + } + + if (areTestAndConsequentOnSameLine) { + context.report({ + node: node.test, + loc: { + start: firstTokenOfTest.loc.start, + end: lastTokenOfTest.loc.end + }, + messageId: "expectedTestCons", + fix: fixer => (hasComments ? null : ( + fixer.replaceTextRange( + [ + lastTokenOfTest.range[1], + questionToken.range[0] + ], + "\n" + ) + )) + }); + } + + if (areConsequentAndAlternateOnSameLine) { + context.report({ + node: node.consequent, + loc: { + start: firstTokenOfConsequent.loc.start, + end: lastTokenOfConsequent.loc.end + }, + messageId: "expectedConsAlt", + fix: (fixer => (hasComments ? null : ( + fixer.replaceTextRange( + [ + lastTokenOfConsequent.range[1], + colonToken.range[0] + ], + "\n" + ) + ))) + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/new-cap.js b/node_modules/eslint/lib/rules/new-cap.js new file mode 100644 index 0000000..f81e42f --- /dev/null +++ b/node_modules/eslint/lib/rules/new-cap.js @@ -0,0 +1,276 @@ +/** + * @fileoverview Rule to flag use of constructors without capital letters + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const CAPS_ALLOWED = [ + "Array", + "Boolean", + "Date", + "Error", + "Function", + "Number", + "Object", + "RegExp", + "String", + "Symbol", + "BigInt" +]; + +/** + * Ensure that if the key is provided, it must be an array. + * @param {Object} obj Object to check with `key`. + * @param {string} key Object key to check on `obj`. + * @param {any} fallback If obj[key] is not present, this will be returned. + * @throws {TypeError} If key is not an own array type property of `obj`. + * @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback` + */ +function checkArray(obj, key, fallback) { + + /* c8 ignore start */ + if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) { + throw new TypeError(`${key}, if provided, must be an Array`); + }/* c8 ignore stop */ + return obj[key] || fallback; +} + +/** + * A reducer function to invert an array to an Object mapping the string form of the key, to `true`. + * @param {Object} map Accumulator object for the reduce. + * @param {string} key Object key to set to `true`. + * @returns {Object} Returns the updated Object for further reduction. + */ +function invert(map, key) { + map[key] = true; + return map; +} + +/** + * Creates an object with the cap is new exceptions as its keys and true as their values. + * @param {Object} config Rule configuration + * @returns {Object} Object with cap is new exceptions. + */ +function calculateCapIsNewExceptions(config) { + let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED); + + if (capIsNewExceptions !== CAPS_ALLOWED) { + capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED); + } + + return capIsNewExceptions.reduce(invert, {}); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require constructor names to begin with a capital letter", + recommended: false, + url: "https://eslint.org/docs/latest/rules/new-cap" + }, + + schema: [ + { + type: "object", + properties: { + newIsCap: { + type: "boolean", + default: true + }, + capIsNew: { + type: "boolean", + default: true + }, + newIsCapExceptions: { + type: "array", + items: { + type: "string" + } + }, + newIsCapExceptionPattern: { + type: "string" + }, + capIsNewExceptions: { + type: "array", + items: { + type: "string" + } + }, + capIsNewExceptionPattern: { + type: "string" + }, + properties: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + messages: { + upper: "A function with a name starting with an uppercase letter should only be used as a constructor.", + lower: "A constructor name should not start with a lowercase letter." + } + }, + + create(context) { + + const config = Object.assign({}, context.options[0]); + + config.newIsCap = config.newIsCap !== false; + config.capIsNew = config.capIsNew !== false; + const skipProperties = config.properties === false; + + const newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {}); + const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern, "u") : null; + + const capIsNewExceptions = calculateCapIsNewExceptions(config); + const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern, "u") : null; + + const listeners = {}; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Get exact callee name from expression + * @param {ASTNode} node CallExpression or NewExpression node + * @returns {string} name + */ + function extractNameFromExpression(node) { + return node.callee.type === "Identifier" + ? node.callee.name + : astUtils.getStaticPropertyName(node.callee) || ""; + } + + /** + * Returns the capitalization state of the string - + * Whether the first character is uppercase, lowercase, or non-alphabetic + * @param {string} str String + * @returns {string} capitalization state: "non-alpha", "lower", or "upper" + */ + function getCap(str) { + const firstChar = str.charAt(0); + + const firstCharLower = firstChar.toLowerCase(); + const firstCharUpper = firstChar.toUpperCase(); + + if (firstCharLower === firstCharUpper) { + + // char has no uppercase variant, so it's non-alphabetic + return "non-alpha"; + } + if (firstChar === firstCharLower) { + return "lower"; + } + return "upper"; + + } + + /** + * Check if capitalization is allowed for a CallExpression + * @param {Object} allowedMap Object mapping calleeName to a Boolean + * @param {ASTNode} node CallExpression node + * @param {string} calleeName Capitalized callee name from a CallExpression + * @param {Object} pattern RegExp object from options pattern + * @returns {boolean} Returns true if the callee may be capitalized + */ + function isCapAllowed(allowedMap, node, calleeName, pattern) { + const sourceText = sourceCode.getText(node.callee); + + if (allowedMap[calleeName] || allowedMap[sourceText]) { + return true; + } + + if (pattern && pattern.test(sourceText)) { + return true; + } + + const callee = astUtils.skipChainExpression(node.callee); + + if (calleeName === "UTC" && callee.type === "MemberExpression") { + + // allow if callee is Date.UTC + return callee.object.type === "Identifier" && + callee.object.name === "Date"; + } + + return skipProperties && callee.type === "MemberExpression"; + } + + /** + * Reports the given messageId for the given node. The location will be the start of the property or the callee. + * @param {ASTNode} node CallExpression or NewExpression node. + * @param {string} messageId The messageId to report. + * @returns {void} + */ + function report(node, messageId) { + let callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "MemberExpression") { + callee = callee.property; + } + + context.report({ node, loc: callee.loc, messageId }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + if (config.newIsCap) { + listeners.NewExpression = function(node) { + + const constructorName = extractNameFromExpression(node); + + if (constructorName) { + const capitalization = getCap(constructorName); + const isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName, newIsCapExceptionPattern); + + if (!isAllowed) { + report(node, "lower"); + } + } + }; + } + + if (config.capIsNew) { + listeners.CallExpression = function(node) { + + const calleeName = extractNameFromExpression(node); + + if (calleeName) { + const capitalization = getCap(calleeName); + const isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName, capIsNewExceptionPattern); + + if (!isAllowed) { + report(node, "upper"); + } + } + }; + } + + return listeners; + } +}; diff --git a/node_modules/eslint/lib/rules/new-parens.js b/node_modules/eslint/lib/rules/new-parens.js new file mode 100644 index 0000000..e866731 --- /dev/null +++ b/node_modules/eslint/lib/rules/new-parens.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Rule to flag when using constructor without parentheses + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce or disallow parentheses when invoking a constructor with no arguments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/new-parens" + }, + + fixable: "code", + schema: [ + { + enum: ["always", "never"] + } + ], + messages: { + missing: "Missing '()' invoking a constructor.", + unnecessary: "Unnecessary '()' invoking a constructor with no arguments." + } + }, + + create(context) { + const options = context.options; + const always = options[0] !== "never"; // Default is always + + const sourceCode = context.sourceCode; + + return { + NewExpression(node) { + if (node.arguments.length !== 0) { + return; // if there are arguments, there have to be parens + } + + const lastToken = sourceCode.getLastToken(node); + const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken); + + // `hasParens` is true only if the new expression ends with its own parens, e.g., new new foo() does not end with its own parens + const hasParens = hasLastParen && + astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken)) && + node.callee.range[1] < node.range[1]; + + if (always) { + if (!hasParens) { + context.report({ + node, + messageId: "missing", + fix: fixer => fixer.insertTextAfter(node, "()") + }); + } + } else { + if (hasParens) { + context.report({ + node, + messageId: "unnecessary", + fix: fixer => [ + fixer.remove(sourceCode.getTokenBefore(lastToken)), + fixer.remove(lastToken), + fixer.insertTextBefore(node, "("), + fixer.insertTextAfter(node, ")") + ] + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/newline-after-var.js b/node_modules/eslint/lib/rules/newline-after-var.js new file mode 100644 index 0000000..dc8b24d --- /dev/null +++ b/node_modules/eslint/lib/rules/newline-after-var.js @@ -0,0 +1,253 @@ +/** + * @fileoverview Rule to check empty newline after "var" statement + * @author Gopal Venkatesan + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow an empty line after variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-after-var" + }, + schema: [ + { + enum: ["never", "always"] + } + ], + fixable: "whitespace", + messages: { + expected: "Expected blank line after variable declarations.", + unexpected: "Unexpected blank line after variable declarations." + }, + + deprecated: true, + + replacedBy: ["padding-line-between-statements"] + }, + + create(context) { + const sourceCode = context.sourceCode; + + // Default `mode` to "always". + const mode = context.options[0] === "never" ? "never" : "always"; + + // Cache starting and ending line numbers of comments for faster lookup + const commentEndLine = sourceCode.getAllComments().reduce((result, token) => { + result[token.loc.start.line] = token.loc.end.line; + return result; + }, {}); + + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Gets a token from the given node to compare line to the next statement. + * + * In general, the token is the last token of the node. However, the token is the second last token if the following conditions satisfy. + * + * - The last token is semicolon. + * - The semicolon is on a different line from the previous token of the semicolon. + * + * This behavior would address semicolon-less style code. e.g.: + * + * var foo = 1 + * + * ;(a || b).doSomething() + * @param {ASTNode} node The node to get. + * @returns {Token} The token to compare line to the next statement. + */ + function getLastToken(node) { + const lastToken = sourceCode.getLastToken(node); + + if (lastToken.type === "Punctuator" && lastToken.value === ";") { + const prevToken = sourceCode.getTokenBefore(lastToken); + + if (prevToken.loc.end.line !== lastToken.loc.start.line) { + return prevToken; + } + } + + return lastToken; + } + + /** + * Determine if provided keyword is a variable declaration + * @private + * @param {string} keyword keyword to test + * @returns {boolean} True if `keyword` is a type of var + */ + function isVar(keyword) { + return keyword === "var" || keyword === "let" || keyword === "const"; + } + + /** + * Determine if provided keyword is a variant of for specifiers + * @private + * @param {string} keyword keyword to test + * @returns {boolean} True if `keyword` is a variant of for specifier + */ + function isForTypeSpecifier(keyword) { + return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement"; + } + + /** + * Determine if provided keyword is an export specifiers + * @private + * @param {string} nodeType nodeType to test + * @returns {boolean} True if `nodeType` is an export specifier + */ + function isExportSpecifier(nodeType) { + return nodeType === "ExportNamedDeclaration" || nodeType === "ExportSpecifier" || + nodeType === "ExportDefaultDeclaration" || nodeType === "ExportAllDeclaration"; + } + + /** + * Determine if provided node is the last of their parent block. + * @private + * @param {ASTNode} node node to test + * @returns {boolean} True if `node` is last of their parent block. + */ + function isLastNode(node) { + const token = sourceCode.getTokenAfter(node); + + return !token || (token.type === "Punctuator" && token.value === "}"); + } + + /** + * Gets the last line of a group of consecutive comments + * @param {number} commentStartLine The starting line of the group + * @returns {number} The number of the last comment line of the group + */ + function getLastCommentLineOfBlock(commentStartLine) { + const currentCommentEnd = commentEndLine[commentStartLine]; + + return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd; + } + + /** + * Determine if a token starts more than one line after a comment ends + * @param {token} token The token being checked + * @param {integer} commentStartLine The line number on which the comment starts + * @returns {boolean} True if `token` does not start immediately after a comment + */ + function hasBlankLineAfterComment(token, commentStartLine) { + return token.loc.start.line > getLastCommentLineOfBlock(commentStartLine) + 1; + } + + /** + * Checks that a blank line exists after a variable declaration when mode is + * set to "always", or checks that there is no blank line when mode is set + * to "never" + * @private + * @param {ASTNode} node `VariableDeclaration` node to test + * @returns {void} + */ + function checkForBlankLine(node) { + + /* + * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will + * sometimes be second-last if there is a semicolon on a different line. + */ + const lastToken = getLastToken(node), + + /* + * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken + * is the last token of the node. + */ + nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node), + nextLineNum = lastToken.loc.end.line + 1; + + // Ignore if there is no following statement + if (!nextToken) { + return; + } + + // Ignore if parent of node is a for variant + if (isForTypeSpecifier(node.parent.type)) { + return; + } + + // Ignore if parent of node is an export specifier + if (isExportSpecifier(node.parent.type)) { + return; + } + + /* + * Some coding styles use multiple `var` statements, so do nothing if + * the next token is a `var` statement. + */ + if (nextToken.type === "Keyword" && isVar(nextToken.value)) { + return; + } + + // Ignore if it is last statement in a block + if (isLastNode(node)) { + return; + } + + // Next statement is not a `var`... + const noNextLineToken = nextToken.loc.start.line > nextLineNum; + const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined"); + + if (mode === "never" && noNextLineToken && !hasNextLineComment) { + context.report({ + node, + messageId: "unexpected", + fix(fixer) { + const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER); + + return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`); + } + }); + } + + // Token on the next line, or comment without blank line + if ( + mode === "always" && ( + !noNextLineToken || + hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum) + ) + ) { + context.report({ + node, + messageId: "expected", + fix(fixer) { + if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) { + return fixer.insertTextBefore(nextToken, "\n\n"); + } + + return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n"); + } + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForBlankLine + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/newline-before-return.js b/node_modules/eslint/lib/rules/newline-before-return.js new file mode 100644 index 0000000..73d8ef9 --- /dev/null +++ b/node_modules/eslint/lib/rules/newline-before-return.js @@ -0,0 +1,217 @@ +/** + * @fileoverview Rule to require newlines before `return` statement + * @author Kai Cataldo + * @deprecated in ESLint v4.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require an empty line before `return` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-before-return" + }, + + fixable: "whitespace", + schema: [], + messages: { + expected: "Expected newline before return statement." + }, + + deprecated: true, + replacedBy: ["padding-line-between-statements"] + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tests whether node is preceded by supplied tokens + * @param {ASTNode} node node to check + * @param {Array} testTokens array of tokens to test against + * @returns {boolean} Whether or not the node is preceded by one of the supplied tokens + * @private + */ + function isPrecededByTokens(node, testTokens) { + const tokenBefore = sourceCode.getTokenBefore(node); + + return testTokens.includes(tokenBefore.value); + } + + /** + * Checks whether node is the first node after statement or in block + * @param {ASTNode} node node to check + * @returns {boolean} Whether or not the node is the first node after statement or in block + * @private + */ + function isFirstNode(node) { + const parentType = node.parent.type; + + if (node.parent.body) { + return Array.isArray(node.parent.body) + ? node.parent.body[0] === node + : node.parent.body === node; + } + + if (parentType === "IfStatement") { + return isPrecededByTokens(node, ["else", ")"]); + } + if (parentType === "DoWhileStatement") { + return isPrecededByTokens(node, ["do"]); + } + if (parentType === "SwitchCase") { + return isPrecededByTokens(node, [":"]); + } + return isPrecededByTokens(node, [")"]); + + } + + /** + * Returns the number of lines of comments that precede the node + * @param {ASTNode} node node to check for overlapping comments + * @param {number} lineNumTokenBefore line number of previous token, to check for overlapping comments + * @returns {number} Number of lines of comments that precede the node + * @private + */ + function calcCommentLines(node, lineNumTokenBefore) { + const comments = sourceCode.getCommentsBefore(node); + let numLinesComments = 0; + + if (!comments.length) { + return numLinesComments; + } + + comments.forEach(comment => { + numLinesComments++; + + if (comment.type === "Block") { + numLinesComments += comment.loc.end.line - comment.loc.start.line; + } + + // avoid counting lines with inline comments twice + if (comment.loc.start.line === lineNumTokenBefore) { + numLinesComments--; + } + + if (comment.loc.end.line === node.loc.start.line) { + numLinesComments--; + } + }); + + return numLinesComments; + } + + /** + * Returns the line number of the token before the node that is passed in as an argument + * @param {ASTNode} node The node to use as the start of the calculation + * @returns {number} Line number of the token before `node` + * @private + */ + function getLineNumberOfTokenBefore(node) { + const tokenBefore = sourceCode.getTokenBefore(node); + let lineNumTokenBefore; + + /** + * Global return (at the beginning of a script) is a special case. + * If there is no token before `return`, then we expect no line + * break before the return. Comments are allowed to occupy lines + * before the global return, just no blank lines. + * Setting lineNumTokenBefore to zero in that case results in the + * desired behavior. + */ + if (tokenBefore) { + lineNumTokenBefore = tokenBefore.loc.end.line; + } else { + lineNumTokenBefore = 0; // global return at beginning of script + } + + return lineNumTokenBefore; + } + + /** + * Checks whether node is preceded by a newline + * @param {ASTNode} node node to check + * @returns {boolean} Whether or not the node is preceded by a newline + * @private + */ + function hasNewlineBefore(node) { + const lineNumNode = node.loc.start.line; + const lineNumTokenBefore = getLineNumberOfTokenBefore(node); + const commentLines = calcCommentLines(node, lineNumTokenBefore); + + return (lineNumNode - lineNumTokenBefore - commentLines) > 1; + } + + /** + * Checks whether it is safe to apply a fix to a given return statement. + * + * The fix is not considered safe if the given return statement has leading comments, + * as we cannot safely determine if the newline should be added before or after the comments. + * For more information, see: https://github.com/eslint/eslint/issues/5958#issuecomment-222767211 + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if it can fix the node. + * @private + */ + function canFix(node) { + const leadingComments = sourceCode.getCommentsBefore(node); + const lastLeadingComment = leadingComments[leadingComments.length - 1]; + const tokenBefore = sourceCode.getTokenBefore(node); + + if (leadingComments.length === 0) { + return true; + } + + /* + * if the last leading comment ends in the same line as the previous token and + * does not share a line with the `return` node, we can consider it safe to fix. + * Example: + * function a() { + * var b; //comment + * return; + * } + */ + if (lastLeadingComment.loc.end.line === tokenBefore.loc.end.line && + lastLeadingComment.loc.end.line !== node.loc.start.line) { + return true; + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ReturnStatement(node) { + if (!isFirstNode(node) && !hasNewlineBefore(node)) { + context.report({ + node, + messageId: "expected", + fix(fixer) { + if (canFix(node)) { + const tokenBefore = sourceCode.getTokenBefore(node); + const newlines = node.loc.start.line === tokenBefore.loc.end.line ? "\n\n" : "\n"; + + return fixer.insertTextBefore(node, newlines); + } + return null; + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/newline-per-chained-call.js b/node_modules/eslint/lib/rules/newline-per-chained-call.js new file mode 100644 index 0000000..b2e6cd9 --- /dev/null +++ b/node_modules/eslint/lib/rules/newline-per-chained-call.js @@ -0,0 +1,123 @@ +/** + * @fileoverview Rule to ensure newline per method call when chaining calls + * @author Rajendra Patil + * @author Burak Yigit Kaya + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require a newline after each call in a method chain", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-per-chained-call" + }, + + fixable: "whitespace", + + schema: [{ + type: "object", + properties: { + ignoreChainWithDepth: { + type: "integer", + minimum: 1, + maximum: 10, + default: 2 + } + }, + additionalProperties: false + }], + messages: { + expected: "Expected line break before `{{callee}}`." + } + }, + + create(context) { + + const options = context.options[0] || {}, + ignoreChainWithDepth = options.ignoreChainWithDepth || 2; + + const sourceCode = context.sourceCode; + + /** + * Get the prefix of a given MemberExpression node. + * If the MemberExpression node is a computed value it returns a + * left bracket. If not it returns a period. + * @param {ASTNode} node A MemberExpression node to get + * @returns {string} The prefix of the node. + */ + function getPrefix(node) { + if (node.computed) { + if (node.optional) { + return "?.["; + } + return "["; + } + if (node.optional) { + return "?."; + } + return "."; + } + + /** + * Gets the property text of a given MemberExpression node. + * If the text is multiline, this returns only the first line. + * @param {ASTNode} node A MemberExpression node to get. + * @returns {string} The property text of the node. + */ + function getPropertyText(node) { + const prefix = getPrefix(node); + const lines = sourceCode.getText(node.property).split(astUtils.LINEBREAK_MATCHER); + const suffix = node.computed && lines.length === 1 ? "]" : ""; + + return prefix + lines[0] + suffix; + } + + return { + "CallExpression:exit"(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type !== "MemberExpression") { + return; + } + + let parent = astUtils.skipChainExpression(callee.object); + let depth = 1; + + while (parent && parent.callee) { + depth += 1; + parent = astUtils.skipChainExpression(astUtils.skipChainExpression(parent.callee).object); + } + + if (depth > ignoreChainWithDepth && astUtils.isTokenOnSameLine(callee.object, callee.property)) { + const firstTokenAfterObject = sourceCode.getTokenAfter(callee.object, astUtils.isNotClosingParenToken); + + context.report({ + node: callee.property, + loc: { + start: firstTokenAfterObject.loc.start, + end: callee.loc.end + }, + messageId: "expected", + data: { + callee: getPropertyText(callee) + }, + fix(fixer) { + return fixer.insertTextBefore(firstTokenAfterObject, "\n"); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-alert.js b/node_modules/eslint/lib/rules/no-alert.js new file mode 100644 index 0000000..cc87285 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-alert.js @@ -0,0 +1,138 @@ +/** + * @fileoverview Rule to flag use of alert, confirm, prompt + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + getStaticPropertyName: getPropertyName, + getVariableByName, + skipChainExpression +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given name is a prohibited identifier. + * @param {string} name The name to check + * @returns {boolean} Whether or not the name is prohibited. + */ +function isProhibitedIdentifier(name) { + return /^(alert|confirm|prompt)$/u.test(name); +} + +/** + * Finds the eslint-scope reference in the given scope. + * @param {Object} scope The scope to search. + * @param {ASTNode} node The identifier node. + * @returns {Reference|null} Returns the found reference or null if none were found. + */ +function findReference(scope, node) { + const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1]); + + if (references.length === 1) { + return references[0]; + } + return null; +} + +/** + * Checks if the given identifier node is shadowed in the given scope. + * @param {Object} scope The current scope. + * @param {string} node The identifier node to check + * @returns {boolean} Whether or not the name is shadowed. + */ +function isShadowed(scope, node) { + const reference = findReference(scope, node); + + return reference && reference.resolved && reference.resolved.defs.length > 0; +} + +/** + * Checks if the given identifier node is a ThisExpression in the global scope or the global window property. + * @param {Object} scope The current scope. + * @param {string} node The identifier node to check + * @returns {boolean} Whether or not the node is a reference to the global object. + */ +function isGlobalThisReferenceOrGlobalWindow(scope, node) { + if (scope.type === "global" && node.type === "ThisExpression") { + return true; + } + if ( + node.type === "Identifier" && + ( + node.name === "window" || + (node.name === "globalThis" && getVariableByName(scope, "globalThis")) + ) + ) { + return !isShadowed(scope, node); + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `alert`, `confirm`, and `prompt`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-alert" + }, + + schema: [], + + messages: { + unexpected: "Unexpected {{name}}." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + const callee = skipChainExpression(node.callee), + currentScope = sourceCode.getScope(node); + + // without window. + if (callee.type === "Identifier") { + const name = callee.name; + + if (!isShadowed(currentScope, callee) && isProhibitedIdentifier(callee.name)) { + context.report({ + node, + messageId: "unexpected", + data: { name } + }); + } + + } else if (callee.type === "MemberExpression" && isGlobalThisReferenceOrGlobalWindow(currentScope, callee.object)) { + const name = getPropertyName(callee); + + if (isProhibitedIdentifier(name)) { + context.report({ + node, + messageId: "unexpected", + data: { name } + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-array-constructor.js b/node_modules/eslint/lib/rules/no-array-constructor.js new file mode 100644 index 0000000..b539926 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-array-constructor.js @@ -0,0 +1,54 @@ +/** + * @fileoverview Disallow construction of dense arrays using the Array constructor + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `Array` constructors", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-array-constructor" + }, + + schema: [], + + messages: { + preferLiteral: "The array literal notation [] is preferable." + } + }, + + create(context) { + + /** + * Disallow construction of dense arrays using the Array constructor + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function check(node) { + if ( + node.arguments.length !== 1 && + node.callee.type === "Identifier" && + node.callee.name === "Array" + ) { + context.report({ node, messageId: "preferLiteral" }); + } + } + + return { + CallExpression: check, + NewExpression: check + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-async-promise-executor.js b/node_modules/eslint/lib/rules/no-async-promise-executor.js new file mode 100644 index 0000000..ea6c851 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-async-promise-executor.js @@ -0,0 +1,39 @@ +/** + * @fileoverview disallow using an async function as a Promise executor + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow using an async function as a Promise executor", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-async-promise-executor" + }, + + fixable: null, + schema: [], + messages: { + async: "Promise executor functions should not be async." + } + }, + + create(context) { + return { + "NewExpression[callee.name='Promise'][arguments.0.async=true]"(node) { + context.report({ + node: context.sourceCode.getFirstToken(node.arguments[0], token => token.value === "async"), + messageId: "async" + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-await-in-loop.js b/node_modules/eslint/lib/rules/no-await-in-loop.js new file mode 100644 index 0000000..20230de --- /dev/null +++ b/node_modules/eslint/lib/rules/no-await-in-loop.js @@ -0,0 +1,106 @@ +/** + * @fileoverview Rule to disallow uses of await inside of loops. + * @author Nat Mote (nmote) + */ +"use strict"; + +/** + * Check whether it should stop traversing ancestors at the given node. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if it should stop traversing. + */ +function isBoundary(node) { + const t = node.type; + + return ( + t === "FunctionDeclaration" || + t === "FunctionExpression" || + t === "ArrowFunctionExpression" || + + /* + * Don't report the await expressions on for-await-of loop since it's + * asynchronous iteration intentionally. + */ + (t === "ForOfStatement" && node.await === true) + ); +} + +/** + * Check whether the given node is in loop. + * @param {ASTNode} node A node to check. + * @param {ASTNode} parent A parent node to check. + * @returns {boolean} `true` if the node is in loop. + */ +function isLooped(node, parent) { + switch (parent.type) { + case "ForStatement": + return ( + node === parent.test || + node === parent.update || + node === parent.body + ); + + case "ForOfStatement": + case "ForInStatement": + return node === parent.body; + + case "WhileStatement": + case "DoWhileStatement": + return node === parent.test || node === parent.body; + + default: + return false; + } +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow `await` inside of loops", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-await-in-loop" + }, + + schema: [], + + messages: { + unexpectedAwait: "Unexpected `await` inside a loop." + } + }, + create(context) { + + /** + * Validate an await expression. + * @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. + * @returns {void} + */ + function validate(awaitNode) { + if (awaitNode.type === "ForOfStatement" && !awaitNode.await) { + return; + } + + let node = awaitNode; + let parent = node.parent; + + while (parent && !isBoundary(parent)) { + if (isLooped(node, parent)) { + context.report({ + node: awaitNode, + messageId: "unexpectedAwait" + }); + return; + } + node = parent; + parent = parent.parent; + } + } + + return { + AwaitExpression: validate, + ForOfStatement: validate + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-bitwise.js b/node_modules/eslint/lib/rules/no-bitwise.js new file mode 100644 index 0000000..d90992b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-bitwise.js @@ -0,0 +1,119 @@ +/** + * @fileoverview Rule to flag bitwise identifiers + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * + * Set of bitwise operators. + * + */ +const BITWISE_OPERATORS = [ + "^", "|", "&", "<<", ">>", ">>>", + "^=", "|=", "&=", "<<=", ">>=", ">>>=", + "~" +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow bitwise operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-bitwise" + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + enum: BITWISE_OPERATORS + }, + uniqueItems: true + }, + int32Hint: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + unexpected: "Unexpected use of '{{operator}}'." + } + }, + + create(context) { + const options = context.options[0] || {}; + const allowed = options.allow || []; + const int32Hint = options.int32Hint === true; + + /** + * Reports an unexpected use of a bitwise operator. + * @param {ASTNode} node Node which contains the bitwise operator. + * @returns {void} + */ + function report(node) { + context.report({ node, messageId: "unexpected", data: { operator: node.operator } }); + } + + /** + * Checks if the given node has a bitwise operator. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node has a bitwise operator. + */ + function hasBitwiseOperator(node) { + return BITWISE_OPERATORS.includes(node.operator); + } + + /** + * Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node has a bitwise operator. + */ + function allowedOperator(node) { + return allowed.includes(node.operator); + } + + /** + * Checks if the given bitwise operator is used for integer typecasting, i.e. "|0" + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is used in integer typecasting. + */ + function isInt32Hint(node) { + return int32Hint && node.operator === "|" && node.right && + node.right.type === "Literal" && node.right.value === 0; + } + + /** + * Report if the given node contains a bitwise operator. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNodeForBitwiseOperator(node) { + if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) { + report(node); + } + } + + return { + AssignmentExpression: checkNodeForBitwiseOperator, + BinaryExpression: checkNodeForBitwiseOperator, + UnaryExpression: checkNodeForBitwiseOperator + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-buffer-constructor.js b/node_modules/eslint/lib/rules/no-buffer-constructor.js new file mode 100644 index 0000000..0b73c76 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-buffer-constructor.js @@ -0,0 +1,50 @@ +/** + * @fileoverview disallow use of the Buffer() constructor + * @author Teddy Katz + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "problem", + + docs: { + description: "Disallow use of the `Buffer()` constructor", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-buffer-constructor" + }, + + schema: [], + + messages: { + deprecated: "{{expr}} is deprecated. Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe() instead." + } + }, + + create(context) { + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + "CallExpression[callee.name='Buffer'], NewExpression[callee.name='Buffer']"(node) { + context.report({ + node, + messageId: "deprecated", + data: { expr: node.type === "CallExpression" ? "Buffer()" : "new Buffer()" } + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-caller.js b/node_modules/eslint/lib/rules/no-caller.js new file mode 100644 index 0000000..3e61a8e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-caller.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Rule to flag use of arguments.callee and arguments.caller. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `arguments.caller` or `arguments.callee`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-caller" + }, + + schema: [], + + messages: { + unexpected: "Avoid arguments.{{prop}}." + } + }, + + create(context) { + + return { + + MemberExpression(node) { + const objectName = node.object.name, + propertyName = node.property.name; + + if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/u)) { + context.report({ node, messageId: "unexpected", data: { prop: propertyName } }); + } + + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-case-declarations.js b/node_modules/eslint/lib/rules/no-case-declarations.js new file mode 100644 index 0000000..8dc5b02 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-case-declarations.js @@ -0,0 +1,64 @@ +/** + * @fileoverview Rule to flag use of an lexical declarations inside a case clause + * @author Erik Arvidsson + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow lexical declarations in case clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-case-declarations" + }, + + schema: [], + + messages: { + unexpected: "Unexpected lexical declaration in case block." + } + }, + + create(context) { + + /** + * Checks whether or not a node is a lexical declaration. + * @param {ASTNode} node A direct child statement of a switch case. + * @returns {boolean} Whether or not the node is a lexical declaration. + */ + function isLexicalDeclaration(node) { + switch (node.type) { + case "FunctionDeclaration": + case "ClassDeclaration": + return true; + case "VariableDeclaration": + return node.kind !== "var"; + default: + return false; + } + } + + return { + SwitchCase(node) { + for (let i = 0; i < node.consequent.length; i++) { + const statement = node.consequent[i]; + + if (isLexicalDeclaration(statement)) { + context.report({ + node: statement, + messageId: "unexpected" + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-catch-shadow.js b/node_modules/eslint/lib/rules/no-catch-shadow.js new file mode 100644 index 0000000..f9d8552 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-catch-shadow.js @@ -0,0 +1,82 @@ +/** + * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier + * @author Ian Christian Myers + * @deprecated in ESLint v5.1.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `catch` clause parameters from shadowing variables in the outer scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-catch-shadow" + }, + + replacedBy: ["no-shadow"], + + deprecated: true, + schema: [], + + messages: { + mutable: "Value of '{{name}}' may be overwritten in IE 8 and earlier." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the parameters are been shadowed + * @param {Object} scope current scope + * @param {string} name parameter name + * @returns {boolean} True is its been shadowed + */ + function paramIsShadowing(scope, name) { + return astUtils.getVariableByName(scope, name) !== null; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "CatchClause[param!=null]"(node) { + let scope = sourceCode.getScope(node); + + /* + * When ecmaVersion >= 6, CatchClause creates its own scope + * so start from one upper scope to exclude the current node + */ + if (scope.block === node) { + scope = scope.upper; + } + + if (paramIsShadowing(scope, node.param.name)) { + context.report({ node, messageId: "mutable", data: { name: node.param.name } }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-class-assign.js b/node_modules/eslint/lib/rules/no-class-assign.js new file mode 100644 index 0000000..49f3b84 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-class-assign.js @@ -0,0 +1,63 @@ +/** + * @fileoverview A rule to disallow modifying variables of class declarations + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning class members", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-class-assign" + }, + + schema: [], + + messages: { + class: "'{{name}}' is a class." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, messageId: "class", data: { name: reference.identifier.name } }); + + }); + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {ASTNode} node A ClassDeclaration/ClassExpression node to check. + * @returns {void} + */ + function checkForClass(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + ClassDeclaration: checkForClass, + ClassExpression: checkForClass + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-compare-neg-zero.js b/node_modules/eslint/lib/rules/no-compare-neg-zero.js new file mode 100644 index 0000000..112f6c1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-compare-neg-zero.js @@ -0,0 +1,60 @@ +/** + * @fileoverview The rule should warn against code that tries to compare against -0. + * @author Aladdin-ADD + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow comparing against -0", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-compare-neg-zero" + }, + + fixable: null, + schema: [], + + messages: { + unexpected: "Do not use the '{{operator}}' operator to compare against -0." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks a given node is -0 + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is -0. + */ + function isNegZero(node) { + return node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal" && node.argument.value === 0; + } + const OPERATORS_TO_CHECK = new Set([">", ">=", "<", "<=", "==", "===", "!=", "!=="]); + + return { + BinaryExpression(node) { + if (OPERATORS_TO_CHECK.has(node.operator)) { + if (isNegZero(node.left) || isNegZero(node.right)) { + context.report({ + node, + messageId: "unexpected", + data: { operator: node.operator } + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-cond-assign.js b/node_modules/eslint/lib/rules/no-cond-assign.js new file mode 100644 index 0000000..9529202 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-cond-assign.js @@ -0,0 +1,159 @@ +/** + * @fileoverview Rule to flag assignment in a conditional statement's test expression + * @author Stephen Murray + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TEST_CONDITION_PARENT_TYPES = new Set(["IfStatement", "WhileStatement", "DoWhileStatement", "ForStatement", "ConditionalExpression"]); + +const NODE_DESCRIPTIONS = { + DoWhileStatement: "a 'do...while' statement", + ForStatement: "a 'for' statement", + IfStatement: "an 'if' statement", + WhileStatement: "a 'while' statement" +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow assignment operators in conditional expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-cond-assign" + }, + + schema: [ + { + enum: ["except-parens", "always"] + } + ], + + messages: { + unexpected: "Unexpected assignment within {{type}}.", + + // must match JSHint's error message + missing: "Expected a conditional expression and instead saw an assignment." + } + }, + + create(context) { + + const prohibitAssign = (context.options[0] || "except-parens"); + + const sourceCode = context.sourceCode; + + /** + * Check whether an AST node is the test expression for a conditional statement. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the node is the text expression for a conditional statement; otherwise, `false`. + */ + function isConditionalTestExpression(node) { + return node.parent && + TEST_CONDITION_PARENT_TYPES.has(node.parent.type) && + node === node.parent.test; + } + + /** + * Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement. + * @param {!Object} node The node to use at the start of the search. + * @returns {?Object} The closest ancestor node that represents a conditional statement. + */ + function findConditionalAncestor(node) { + let currentAncestor = node; + + do { + if (isConditionalTestExpression(currentAncestor)) { + return currentAncestor.parent; + } + } while ((currentAncestor = currentAncestor.parent) && !astUtils.isFunction(currentAncestor)); + + return null; + } + + /** + * Check whether the code represented by an AST node is enclosed in two sets of parentheses. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the code is enclosed in two sets of parentheses; otherwise, `false`. + */ + function isParenthesisedTwice(node) { + const previousToken = sourceCode.getTokenBefore(node, 1), + nextToken = sourceCode.getTokenAfter(node, 1); + + return astUtils.isParenthesised(sourceCode, node) && + previousToken && astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && + astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1]; + } + + /** + * Check a conditional statement's test expression for top-level assignments that are not enclosed in parentheses. + * @param {!Object} node The node for the conditional statement. + * @returns {void} + */ + function testForAssign(node) { + if (node.test && + (node.test.type === "AssignmentExpression") && + (node.type === "ForStatement" + ? !astUtils.isParenthesised(sourceCode, node.test) + : !isParenthesisedTwice(node.test) + ) + ) { + + context.report({ + node: node.test, + messageId: "missing" + }); + } + } + + /** + * Check whether an assignment expression is descended from a conditional statement's test expression. + * @param {!Object} node The node for the assignment expression. + * @returns {void} + */ + function testForConditionalAncestor(node) { + const ancestor = findConditionalAncestor(node); + + if (ancestor) { + context.report({ + node, + messageId: "unexpected", + data: { + type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type + } + }); + } + } + + if (prohibitAssign === "always") { + return { + AssignmentExpression: testForConditionalAncestor + }; + } + + return { + DoWhileStatement: testForAssign, + ForStatement: testForAssign, + IfStatement: testForAssign, + WhileStatement: testForAssign, + ConditionalExpression: testForAssign + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-confusing-arrow.js b/node_modules/eslint/lib/rules/no-confusing-arrow.js new file mode 100644 index 0000000..de6e2f3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-confusing-arrow.js @@ -0,0 +1,89 @@ +/** + * @fileoverview A rule to warn against using arrow functions when they could be + * confused with comparisons + * @author Jxck + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is a conditional expression. + * @param {ASTNode} node node to test + * @returns {boolean} `true` if the node is a conditional expression. + */ +function isConditional(node) { + return node && node.type === "ConditionalExpression"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow arrow functions where they could be confused with comparisons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-confusing-arrow" + }, + + fixable: "code", + + schema: [{ + type: "object", + properties: { + allowParens: { type: "boolean", default: true }, + onlyOneSimpleParam: { type: "boolean", default: false } + }, + additionalProperties: false + }], + + messages: { + confusing: "Arrow function used ambiguously with a conditional expression." + } + }, + + create(context) { + const config = context.options[0] || {}; + const allowParens = config.allowParens || (config.allowParens === void 0); + const onlyOneSimpleParam = config.onlyOneSimpleParam; + const sourceCode = context.sourceCode; + + + /** + * Reports if an arrow function contains an ambiguous conditional. + * @param {ASTNode} node A node to check and report. + * @returns {void} + */ + function checkArrowFunc(node) { + const body = node.body; + + if (isConditional(body) && + !(allowParens && astUtils.isParenthesised(sourceCode, body)) && + !(onlyOneSimpleParam && !(node.params.length === 1 && node.params[0].type === "Identifier"))) { + context.report({ + node, + messageId: "confusing", + fix(fixer) { + + // if `allowParens` is not set to true don't bother wrapping in parens + return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`); + } + }); + } + } + + return { + ArrowFunctionExpression: checkArrowFunc + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-console.js b/node_modules/eslint/lib/rules/no-console.js new file mode 100644 index 0000000..f257098 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-console.js @@ -0,0 +1,135 @@ +/** + * @fileoverview Rule to flag use of console object + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `console`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-console" + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + type: "string" + }, + minItems: 1, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpected: "Unexpected console statement." + } + }, + + create(context) { + const options = context.options[0] || {}; + const allowed = options.allow || []; + const sourceCode = context.sourceCode; + + /** + * Checks whether the given reference is 'console' or not. + * @param {eslint-scope.Reference} reference The reference to check. + * @returns {boolean} `true` if the reference is 'console'. + */ + function isConsole(reference) { + const id = reference.identifier; + + return id && id.name === "console"; + } + + /** + * Checks whether the property name of the given MemberExpression node + * is allowed by options or not. + * @param {ASTNode} node The MemberExpression node to check. + * @returns {boolean} `true` if the property name of the node is allowed. + */ + function isAllowed(node) { + const propertyName = astUtils.getStaticPropertyName(node); + + return propertyName && allowed.includes(propertyName); + } + + /** + * Checks whether the given reference is a member access which is not + * allowed by options or not. + * @param {eslint-scope.Reference} reference The reference to check. + * @returns {boolean} `true` if the reference is a member access which + * is not allowed by options. + */ + function isMemberAccessExceptAllowed(reference) { + const node = reference.identifier; + const parent = node.parent; + + return ( + parent.type === "MemberExpression" && + parent.object === node && + !isAllowed(parent) + ); + } + + /** + * Reports the given reference as a violation. + * @param {eslint-scope.Reference} reference The reference to report. + * @returns {void} + */ + function report(reference) { + const node = reference.identifier.parent; + + context.report({ + node, + loc: node.loc, + messageId: "unexpected" + }); + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + const consoleVar = astUtils.getVariableByName(scope, "console"); + const shadowed = consoleVar && consoleVar.defs.length > 0; + + /* + * 'scope.through' includes all references to undefined + * variables. If the variable 'console' is not defined, it uses + * 'scope.through'. + */ + const references = consoleVar + ? consoleVar.references + : scope.through.filter(isConsole); + + if (!shadowed) { + references + .filter(isMemberAccessExceptAllowed) + .forEach(report); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-const-assign.js b/node_modules/eslint/lib/rules/no-const-assign.js new file mode 100644 index 0000000..0ceaf7e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-const-assign.js @@ -0,0 +1,56 @@ +/** + * @fileoverview A rule to disallow modifying variables that are declared using `const` + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning `const` variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-const-assign" + }, + + schema: [], + + messages: { + const: "'{{name}}' is constant." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, messageId: "const", data: { name: reference.identifier.name } }); + }); + } + + return { + VariableDeclaration(node) { + if (node.kind === "const") { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-constant-binary-expression.js b/node_modules/eslint/lib/rules/no-constant-binary-expression.js new file mode 100644 index 0000000..845255a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constant-binary-expression.js @@ -0,0 +1,509 @@ +/** + * @fileoverview Rule to flag constant comparisons and logical expressions that always/never short circuit + * @author Jordan Eldredge + */ + +"use strict"; + +const globals = require("globals"); +const { isNullLiteral, isConstant, isReferenceToGlobalVariable, isLogicalAssignmentOperator } = require("./utils/ast-utils"); + +const NUMERIC_OR_STRING_BINARY_OPERATORS = new Set(["+", "-", "*", "/", "%", "|", "^", "&", "**", "<<", ">>", ">>>"]); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is `null` or `undefined`. Similar to the one + * found in ast-utils.js, but this one correctly handles the edge case that + * `undefined` has been redefined. + * @param {Scope} scope Scope in which the expression was found. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `null` or `undefined`. + * @public + */ +function isNullOrUndefined(scope, node) { + return ( + isNullLiteral(node) || + (node.type === "Identifier" && node.name === "undefined" && isReferenceToGlobalVariable(scope, node)) || + (node.type === "UnaryExpression" && node.operator === "void") + ); +} + +/** + * Test if an AST node has a statically knowable constant nullishness. Meaning, + * it will always resolve to a constant value of either: `null`, `undefined` + * or not `null` _or_ `undefined`. An expression that can vary between those + * three states at runtime would return `false`. + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The AST node being tested. + * @param {boolean} nonNullish if `true` then nullish values are not considered constant. + * @returns {boolean} Does `node` have constant nullishness? + */ +function hasConstantNullishness(scope, node, nonNullish) { + if (nonNullish && isNullOrUndefined(scope, node)) { + return false; + } + + switch (node.type) { + case "ObjectExpression": // Objects are never nullish + case "ArrayExpression": // Arrays are never nullish + case "ArrowFunctionExpression": // Functions never nullish + case "FunctionExpression": // Functions are never nullish + case "ClassExpression": // Classes are never nullish + case "NewExpression": // Objects are never nullish + case "Literal": // Nullish, or non-nullish, literals never change + case "TemplateLiteral": // A string is never nullish + case "UpdateExpression": // Numbers are never nullish + case "BinaryExpression": // Numbers, strings, or booleans are never nullish + return true; + case "CallExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + const functionName = node.callee.name; + + return (functionName === "Boolean" || functionName === "String" || functionName === "Number") && + isReferenceToGlobalVariable(scope, node.callee); + } + case "LogicalExpression": { + return node.operator === "??" && hasConstantNullishness(scope, node.right, true); + } + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantNullishness(scope, node.right, nonNullish); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) / + */ + if (isLogicalAssignmentOperator(node.operator)) { + return false; + } + + /* + * The remaining assignment expressions all result in a numeric or + * string (non-nullish) value: + * "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=" + */ + + return true; + case "UnaryExpression": + + /* + * "void" Always returns `undefined` + * "typeof" All types are strings, and thus non-nullish + * "!" Boolean is never nullish + * "delete" Returns a boolean, which is never nullish + * Math operators always return numbers or strings, neither of which + * are non-nullish "+", "-", "~" + */ + + return true; + case "SequenceExpression": { + const last = node.expressions[node.expressions.length - 1]; + + return hasConstantNullishness(scope, last, nonNullish); + } + case "Identifier": + return node.name === "undefined" && isReferenceToGlobalVariable(scope, node); + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Test if an AST node is a boolean value that never changes. Specifically we + * test for: + * 1. Literal booleans (`true` or `false`) + * 2. Unary `!` expressions with a constant value + * 3. Constant booleans created via the `Boolean` global function + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Is `node` guaranteed to be a boolean? + */ +function isStaticBoolean(scope, node) { + switch (node.type) { + case "Literal": + return typeof node.value === "boolean"; + case "CallExpression": + return node.callee.type === "Identifier" && node.callee.name === "Boolean" && + isReferenceToGlobalVariable(scope, node.callee) && + (node.arguments.length === 0 || isConstant(scope, node.arguments[0], true)); + case "UnaryExpression": + return node.operator === "!" && isConstant(scope, node.argument, true); + default: + return false; + } +} + + +/** + * Test if an AST node will always give the same result when compared to a + * boolean value. Note that comparison to boolean values is different than + * truthiness. + * https://262.ecma-international.org/5.1/#sec-11.9.3 + * + * Javascript `==` operator works by converting the boolean to `1` (true) or + * `+0` (false) and then checks the values `==` equality to that number. + * @param {Scope} scope The scope in which node was found. + * @param {ASTNode} node The node to test. + * @returns {boolean} Will `node` always coerce to the same boolean value? + */ +function hasConstantLooseBooleanComparison(scope, node) { + switch (node.type) { + case "ObjectExpression": + case "ClassExpression": + + /** + * In theory objects like: + * + * `{toString: () => a}` + * `{valueOf: () => a}` + * + * Or a classes like: + * + * `class { static toString() { return a } }` + * `class { static valueOf() { return a } }` + * + * Are not constant verifiably when `inBooleanPosition` is + * false, but it's an edge case we've opted not to handle. + */ + return true; + case "ArrayExpression": { + const nonSpreadElements = node.elements.filter(e => + + // Elements can be `null` in sparse arrays: `[,,]`; + e !== null && e.type !== "SpreadElement"); + + + /* + * Possible future direction if needed: We could check if the + * single value would result in variable boolean comparison. + * For now we will err on the side of caution since `[x]` could + * evaluate to `[0]` or `[1]`. + */ + return node.elements.length === 0 || nonSpreadElements.length > 1; + } + case "ArrowFunctionExpression": + case "FunctionExpression": + return true; + case "UnaryExpression": + if (node.operator === "void" || // Always returns `undefined` + node.operator === "typeof" // All `typeof` strings, when coerced to number, are not 0 or 1. + ) { + return true; + } + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + /* + * We won't try to reason about +, -, ~, or delete + * In theory, for the mathematical operators, we could look at the + * argument and try to determine if it coerces to a constant numeric + * value. + */ + return false; + case "NewExpression": // Objects might have custom `.valueOf` or `.toString`. + return false; + case "CallExpression": { + if (node.callee.type === "Identifier" && + node.callee.name === "Boolean" && + isReferenceToGlobalVariable(scope, node.callee) + ) { + return node.arguments.length === 0 || isConstant(scope, node.arguments[0], true); + } + return false; + } + case "Literal": // True or false, literals never change + return true; + case "Identifier": + return node.name === "undefined" && isReferenceToGlobalVariable(scope, node); + case "TemplateLiteral": + + /* + * In theory we could try to check if the quasi are sufficient to + * prove that the expression will always be true, but it would be + * tricky to get right. For example: `000.${foo}000` + */ + return node.expressions.length === 0; + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantLooseBooleanComparison(scope, node.right); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) + * + * The remaining assignment expressions all result in a numeric or + * string (non-nullish) values which could be truthy or falsy: + * "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=" + */ + return false; + case "SequenceExpression": { + const last = node.expressions[node.expressions.length - 1]; + + return hasConstantLooseBooleanComparison(scope, last); + } + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + + +/** + * Test if an AST node will always give the same result when _strictly_ compared + * to a boolean value. This can happen if the expression can never be boolean, or + * if it is always the same boolean value. + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Will `node` always give the same result when compared to a + * static boolean value? + */ +function hasConstantStrictBooleanComparison(scope, node) { + switch (node.type) { + case "ObjectExpression": // Objects are not booleans + case "ArrayExpression": // Arrays are not booleans + case "ArrowFunctionExpression": // Functions are not booleans + case "FunctionExpression": + case "ClassExpression": // Classes are not booleans + case "NewExpression": // Objects are not booleans + case "TemplateLiteral": // Strings are not booleans + case "Literal": // True, false, or not boolean, literals never change. + case "UpdateExpression": // Numbers are not booleans + return true; + case "BinaryExpression": + return NUMERIC_OR_STRING_BINARY_OPERATORS.has(node.operator); + case "UnaryExpression": { + if (node.operator === "delete") { + return false; + } + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + /* + * The remaining operators return either strings or numbers, neither + * of which are boolean. + */ + return true; + } + case "SequenceExpression": { + const last = node.expressions[node.expressions.length - 1]; + + return hasConstantStrictBooleanComparison(scope, last); + } + case "Identifier": + return node.name === "undefined" && isReferenceToGlobalVariable(scope, node); + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantStrictBooleanComparison(scope, node.right); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) + */ + if (isLogicalAssignmentOperator(node.operator)) { + return false; + } + + /* + * The remaining assignment expressions all result in either a number + * or a string, neither of which can ever be boolean. + */ + return true; + case "CallExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + const functionName = node.callee.name; + + if ( + (functionName === "String" || functionName === "Number") && + isReferenceToGlobalVariable(scope, node.callee) + ) { + return true; + } + if (functionName === "Boolean" && isReferenceToGlobalVariable(scope, node.callee)) { + return ( + node.arguments.length === 0 || isConstant(scope, node.arguments[0], true)); + } + return false; + } + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Test if an AST node will always result in a newly constructed object + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Will `node` always be new? + */ +function isAlwaysNew(scope, node) { + switch (node.type) { + case "ObjectExpression": + case "ArrayExpression": + case "ArrowFunctionExpression": + case "FunctionExpression": + case "ClassExpression": + return true; + case "NewExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + + /* + * All the built-in constructors are always new, but + * user-defined constructors could return a sentinel + * object. + * + * Catching these is especially useful for primitive constructors + * which return boxed values, a surprising gotcha' in JavaScript. + */ + return Object.hasOwnProperty.call(globals.builtin, node.callee.name) && + isReferenceToGlobalVariable(scope, node.callee); + } + case "Literal": + + // Regular expressions are objects, and thus always new + return typeof node.regex === "object"; + case "SequenceExpression": { + const last = node.expressions[node.expressions.length - 1]; + + return isAlwaysNew(scope, last); + } + case "AssignmentExpression": + if (node.operator === "=") { + return isAlwaysNew(scope, node.right); + } + return false; + case "ConditionalExpression": + return isAlwaysNew(scope, node.consequent) && isAlwaysNew(scope, node.alternate); + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Checks if one operand will cause the result to be constant. + * @param {Scope} scope Scope in which the expression was found. + * @param {ASTNode} a One side of the expression + * @param {ASTNode} b The other side of the expression + * @param {string} operator The binary expression operator + * @returns {ASTNode | null} The node which will cause the expression to have a constant result. + */ +function findBinaryExpressionConstantOperand(scope, a, b, operator) { + if (operator === "==" || operator === "!=") { + if ( + (isNullOrUndefined(scope, a) && hasConstantNullishness(scope, b, false)) || + (isStaticBoolean(scope, a) && hasConstantLooseBooleanComparison(scope, b)) + ) { + return b; + } + } else if (operator === "===" || operator === "!==") { + if ( + (isNullOrUndefined(scope, a) && hasConstantNullishness(scope, b, false)) || + (isStaticBoolean(scope, a) && hasConstantStrictBooleanComparison(scope, b)) + ) { + return b; + } + } + return null; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + docs: { + description: "Disallow expressions where the operation doesn't affect the value", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-constant-binary-expression" + }, + schema: [], + messages: { + constantBinaryOperand: "Unexpected constant binary expression. Compares constantly with the {{otherSide}}-hand side of the `{{operator}}`.", + constantShortCircuit: "Unexpected constant {{property}} on the left-hand side of a `{{operator}}` expression.", + alwaysNew: "Unexpected comparison to newly constructed object. These two values can never be equal.", + bothAlwaysNew: "Unexpected comparison of two newly constructed objects. These two values can never be equal." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + LogicalExpression(node) { + const { operator, left } = node; + const scope = sourceCode.getScope(node); + + if ((operator === "&&" || operator === "||") && isConstant(scope, left, true)) { + context.report({ node: left, messageId: "constantShortCircuit", data: { property: "truthiness", operator } }); + } else if (operator === "??" && hasConstantNullishness(scope, left, false)) { + context.report({ node: left, messageId: "constantShortCircuit", data: { property: "nullishness", operator } }); + } + }, + BinaryExpression(node) { + const scope = sourceCode.getScope(node); + const { right, left, operator } = node; + const rightConstantOperand = findBinaryExpressionConstantOperand(scope, left, right, operator); + const leftConstantOperand = findBinaryExpressionConstantOperand(scope, right, left, operator); + + if (rightConstantOperand) { + context.report({ node: rightConstantOperand, messageId: "constantBinaryOperand", data: { operator, otherSide: "left" } }); + } else if (leftConstantOperand) { + context.report({ node: leftConstantOperand, messageId: "constantBinaryOperand", data: { operator, otherSide: "right" } }); + } else if (operator === "===" || operator === "!==") { + if (isAlwaysNew(scope, left)) { + context.report({ node: left, messageId: "alwaysNew" }); + } else if (isAlwaysNew(scope, right)) { + context.report({ node: right, messageId: "alwaysNew" }); + } + } else if (operator === "==" || operator === "!=") { + + /* + * If both sides are "new", then both sides are objects and + * therefore they will be compared by reference even with `==` + * equality. + */ + if (isAlwaysNew(scope, left) && isAlwaysNew(scope, right)) { + context.report({ node: left, messageId: "bothAlwaysNew" }); + } + } + + } + + /* + * In theory we could handle short-circuiting assignment operators, + * for some constant values, but that would require walking the + * scope to find the value of the variable being assigned. This is + * dependant on https://github.com/eslint/eslint/issues/13776 + * + * AssignmentExpression() {}, + */ + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-constant-condition.js b/node_modules/eslint/lib/rules/no-constant-condition.js new file mode 100644 index 0000000..24abe36 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constant-condition.js @@ -0,0 +1,150 @@ +/** + * @fileoverview Rule to flag use constant conditions + * @author Christian Schulz + */ + +"use strict"; + +const { isConstant } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow constant expressions in conditions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-constant-condition" + }, + + schema: [ + { + type: "object", + properties: { + checkLoops: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpected: "Unexpected constant condition." + } + }, + + create(context) { + const options = context.options[0] || {}, + checkLoops = options.checkLoops !== false, + loopSetStack = []; + const sourceCode = context.sourceCode; + + let loopsInCurrentScope = new Set(); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tracks when the given node contains a constant condition. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function trackConstantConditionLoop(node) { + if (node.test && isConstant(sourceCode.getScope(node), node.test, true)) { + loopsInCurrentScope.add(node); + } + } + + /** + * Reports when the set contains the given constant condition node + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkConstantConditionLoopInSet(node) { + if (loopsInCurrentScope.has(node)) { + loopsInCurrentScope.delete(node); + context.report({ node: node.test, messageId: "unexpected" }); + } + } + + /** + * Reports when the given node contains a constant condition. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function reportIfConstant(node) { + if (node.test && isConstant(sourceCode.getScope(node), node.test, true)) { + context.report({ node: node.test, messageId: "unexpected" }); + } + } + + /** + * Stores current set of constant loops in loopSetStack temporarily + * and uses a new set to track constant loops + * @returns {void} + * @private + */ + function enterFunction() { + loopSetStack.push(loopsInCurrentScope); + loopsInCurrentScope = new Set(); + } + + /** + * Reports when the set still contains stored constant conditions + * @returns {void} + * @private + */ + function exitFunction() { + loopsInCurrentScope = loopSetStack.pop(); + } + + /** + * Checks node when checkLoops option is enabled + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkLoop(node) { + if (checkLoops) { + trackConstantConditionLoop(node); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ConditionalExpression: reportIfConstant, + IfStatement: reportIfConstant, + WhileStatement: checkLoop, + "WhileStatement:exit": checkConstantConditionLoopInSet, + DoWhileStatement: checkLoop, + "DoWhileStatement:exit": checkConstantConditionLoopInSet, + ForStatement: checkLoop, + "ForStatement > .test": node => checkLoop(node.parent), + "ForStatement:exit": checkConstantConditionLoopInSet, + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + YieldExpression: () => loopsInCurrentScope.clear() + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-constructor-return.js b/node_modules/eslint/lib/rules/no-constructor-return.js new file mode 100644 index 0000000..d7d9893 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constructor-return.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Rule to disallow returning value from constructor. + * @author Pig Fang + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow returning value from constructor", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-constructor-return" + }, + + schema: {}, + + fixable: null, + + messages: { + unexpected: "Unexpected return statement in constructor." + } + }, + + create(context) { + const stack = []; + + return { + onCodePathStart(_, node) { + stack.push(node); + }, + onCodePathEnd() { + stack.pop(); + }, + ReturnStatement(node) { + const last = stack[stack.length - 1]; + + if (!last.parent) { + return; + } + + if ( + last.parent.type === "MethodDefinition" && + last.parent.kind === "constructor" && + (node.parent.parent === last || node.argument) + ) { + context.report({ + node, + messageId: "unexpected" + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-continue.js b/node_modules/eslint/lib/rules/no-continue.js new file mode 100644 index 0000000..f6e484b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-continue.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Rule to flag use of continue statement + * @author Borislav Zhivkov + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `continue` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-continue" + }, + + schema: [], + + messages: { + unexpected: "Unexpected use of continue statement." + } + }, + + create(context) { + + return { + ContinueStatement(node) { + context.report({ node, messageId: "unexpected" }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-control-regex.js b/node_modules/eslint/lib/rules/no-control-regex.js new file mode 100644 index 0000000..dc412fc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-control-regex.js @@ -0,0 +1,138 @@ +/** + * @fileoverview Rule to forbid control characters from regular expressions. + * @author Nicholas C. Zakas + */ + +"use strict"; + +const RegExpValidator = require("@eslint-community/regexpp").RegExpValidator; +const collector = new (class { + constructor() { + this._source = ""; + this._controlChars = []; + this._validator = new RegExpValidator(this); + } + + onPatternEnter() { + + /* + * `RegExpValidator` may parse the pattern twice in one `validatePattern`. + * So `this._controlChars` should be cleared here as well. + * + * For example, the `/(?\x1f)/` regex will parse the pattern twice. + * This is based on the content described in Annex B. + * If the regex contains a `GroupName` and the `u` flag is not used, `ParseText` will be called twice. + * See https://tc39.es/ecma262/2023/multipage/additional-ecmascript-features-for-web-browsers.html#sec-parsepattern-annexb + */ + this._controlChars = []; + } + + onCharacter(start, end, cp) { + if (cp >= 0x00 && + cp <= 0x1F && + ( + this._source.codePointAt(start) === cp || + this._source.slice(start, end).startsWith("\\x") || + this._source.slice(start, end).startsWith("\\u") + ) + ) { + this._controlChars.push(`\\x${`0${cp.toString(16)}`.slice(-2)}`); + } + } + + collectControlChars(regexpStr, flags) { + const uFlag = typeof flags === "string" && flags.includes("u"); + const vFlag = typeof flags === "string" && flags.includes("v"); + + this._controlChars = []; + this._source = regexpStr; + + try { + this._validator.validatePattern(regexpStr, void 0, void 0, { unicode: uFlag, unicodeSets: vFlag }); // Call onCharacter hook + } catch { + + // Ignore syntax errors in RegExp. + } + return this._controlChars; + } +})(); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow control characters in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-control-regex" + }, + + schema: [], + + messages: { + unexpected: "Unexpected control character(s) in regular expression: {{controlChars}}." + } + }, + + create(context) { + + /** + * Get the regex expression + * @param {ASTNode} node `Literal` node to evaluate + * @returns {{ pattern: string, flags: string | null } | null} Regex if found (the given node is either a regex literal + * or a string literal that is the pattern argument of a RegExp constructor call). Otherwise `null`. If flags cannot be determined, + * the `flags` property will be `null`. + * @private + */ + function getRegExp(node) { + if (node.regex) { + return node.regex; + } + if (typeof node.value === "string" && + (node.parent.type === "NewExpression" || node.parent.type === "CallExpression") && + node.parent.callee.type === "Identifier" && + node.parent.callee.name === "RegExp" && + node.parent.arguments[0] === node + ) { + const pattern = node.value; + const flags = + node.parent.arguments.length > 1 && + node.parent.arguments[1].type === "Literal" && + typeof node.parent.arguments[1].value === "string" + ? node.parent.arguments[1].value + : null; + + return { pattern, flags }; + } + + return null; + } + + return { + Literal(node) { + const regExp = getRegExp(node); + + if (regExp) { + const { pattern, flags } = regExp; + const controlCharacters = collector.collectControlChars(pattern, flags); + + if (controlCharacters.length > 0) { + context.report({ + node, + messageId: "unexpected", + data: { + controlChars: controlCharacters.join(", ") + } + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-debugger.js b/node_modules/eslint/lib/rules/no-debugger.js new file mode 100644 index 0000000..f698435 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-debugger.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to flag use of a debugger statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow the use of `debugger`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-debugger" + }, + + fixable: null, + schema: [], + + messages: { + unexpected: "Unexpected 'debugger' statement." + } + }, + + create(context) { + + return { + DebuggerStatement(node) { + context.report({ + node, + messageId: "unexpected" + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-delete-var.js b/node_modules/eslint/lib/rules/no-delete-var.js new file mode 100644 index 0000000..126603c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-delete-var.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Rule to flag when deleting variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow deleting variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-delete-var" + }, + + schema: [], + + messages: { + unexpected: "Variables should not be deleted." + } + }, + + create(context) { + + return { + + UnaryExpression(node) { + if (node.operator === "delete" && node.argument.type === "Identifier") { + context.report({ node, messageId: "unexpected" }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-div-regex.js b/node_modules/eslint/lib/rules/no-div-regex.js new file mode 100644 index 0000000..208f840 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-div-regex.js @@ -0,0 +1,53 @@ +/** + * @fileoverview Rule to check for ambiguous div operator in regexes + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow equal signs explicitly at the beginning of regular expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-div-regex" + }, + + fixable: "code", + + schema: [], + + messages: { + unexpected: "A regular expression literal can be confused with '/='." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + + Literal(node) { + const token = sourceCode.getFirstToken(node); + + if (token.type === "RegularExpression" && token.value[1] === "=") { + context.report({ + node, + messageId: "unexpected", + fix(fixer) { + return fixer.replaceTextRange([token.range[0] + 1, token.range[0] + 2], "[=]"); + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-args.js b/node_modules/eslint/lib/rules/no-dupe-args.js new file mode 100644 index 0000000..c04ede5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-args.js @@ -0,0 +1,82 @@ +/** + * @fileoverview Rule to flag duplicate arguments + * @author Jamund Ferguson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate arguments in `function` definitions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-args" + }, + + schema: [], + + messages: { + unexpected: "Duplicate param '{{name}}'." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whether or not a given definition is a parameter's. + * @param {eslint-scope.DefEntry} def A definition to check. + * @returns {boolean} `true` if the definition is a parameter's. + */ + function isParameter(def) { + return def.type === "Parameter"; + } + + /** + * Determines if a given node has duplicate parameters. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkParams(node) { + const variables = sourceCode.getDeclaredVariables(node); + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + // Checks and reports duplications. + const defs = variable.defs.filter(isParameter); + + if (defs.length >= 2) { + context.report({ + node, + messageId: "unexpected", + data: { name: variable.name } + }); + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: checkParams, + FunctionExpression: checkParams + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-class-members.js b/node_modules/eslint/lib/rules/no-dupe-class-members.js new file mode 100644 index 0000000..2a7a9e8 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-class-members.js @@ -0,0 +1,104 @@ +/** + * @fileoverview A rule to disallow duplicate name in class members. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate class members", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-class-members" + }, + + schema: [], + + messages: { + unexpected: "Duplicate name '{{name}}'." + } + }, + + create(context) { + let stack = []; + + /** + * Gets state of a given member name. + * @param {string} name A name of a member. + * @param {boolean} isStatic A flag which specifies that is a static member. + * @returns {Object} A state of a given member name. + * - retv.init {boolean} A flag which shows the name is declared as normal member. + * - retv.get {boolean} A flag which shows the name is declared as getter. + * - retv.set {boolean} A flag which shows the name is declared as setter. + */ + function getState(name, isStatic) { + const stateMap = stack[stack.length - 1]; + const key = `$${name}`; // to avoid "__proto__". + + if (!stateMap[key]) { + stateMap[key] = { + nonStatic: { init: false, get: false, set: false }, + static: { init: false, get: false, set: false } + }; + } + + return stateMap[key][isStatic ? "static" : "nonStatic"]; + } + + return { + + // Initializes the stack of state of member declarations. + Program() { + stack = []; + }, + + // Initializes state of member declarations for the class. + ClassBody() { + stack.push(Object.create(null)); + }, + + // Disposes the state for the class. + "ClassBody:exit"() { + stack.pop(); + }, + + // Reports the node if its name has been declared already. + "MethodDefinition, PropertyDefinition"(node) { + const name = astUtils.getStaticPropertyName(node); + const kind = node.type === "MethodDefinition" ? node.kind : "field"; + + if (name === null || kind === "constructor") { + return; + } + + const state = getState(name, node.static); + let isDuplicate = false; + + if (kind === "get") { + isDuplicate = (state.init || state.get); + state.get = true; + } else if (kind === "set") { + isDuplicate = (state.init || state.set); + state.set = true; + } else { + isDuplicate = (state.init || state.get || state.set); + state.init = true; + } + + if (isDuplicate) { + context.report({ node, messageId: "unexpected", data: { name } }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-else-if.js b/node_modules/eslint/lib/rules/no-dupe-else-if.js new file mode 100644 index 0000000..60f436d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-else-if.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Rule to disallow duplicate conditions in if-else-if chains + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the first given array is a subset of the second given array. + * @param {Function} comparator A function to compare two elements, should return `true` if they are equal. + * @param {Array} arrA The array to compare from. + * @param {Array} arrB The array to compare against. + * @returns {boolean} `true` if the array `arrA` is a subset of the array `arrB`. + */ +function isSubsetByComparator(comparator, arrA, arrB) { + return arrA.every(a => arrB.some(b => comparator(a, b))); +} + +/** + * Splits the given node by the given logical operator. + * @param {string} operator Logical operator `||` or `&&`. + * @param {ASTNode} node The node to split. + * @returns {ASTNode[]} Array of conditions that makes the node when joined by the operator. + */ +function splitByLogicalOperator(operator, node) { + if (node.type === "LogicalExpression" && node.operator === operator) { + return [...splitByLogicalOperator(operator, node.left), ...splitByLogicalOperator(operator, node.right)]; + } + return [node]; +} + +const splitByOr = splitByLogicalOperator.bind(null, "||"); +const splitByAnd = splitByLogicalOperator.bind(null, "&&"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate conditions in if-else-if chains", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-else-if" + }, + + schema: [], + + messages: { + unexpected: "This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether the two given nodes are considered to be equal. In particular, given that the nodes + * represent expressions in a boolean context, `||` and `&&` can be considered as commutative operators. + * @param {ASTNode} a First node. + * @param {ASTNode} b Second node. + * @returns {boolean} `true` if the nodes are considered to be equal. + */ + function equal(a, b) { + if (a.type !== b.type) { + return false; + } + + if ( + a.type === "LogicalExpression" && + (a.operator === "||" || a.operator === "&&") && + a.operator === b.operator + ) { + return equal(a.left, b.left) && equal(a.right, b.right) || + equal(a.left, b.right) && equal(a.right, b.left); + } + + return astUtils.equalTokens(a, b, sourceCode); + } + + const isSubset = isSubsetByComparator.bind(null, equal); + + return { + IfStatement(node) { + const test = node.test, + conditionsToCheck = test.type === "LogicalExpression" && test.operator === "&&" + ? [test, ...splitByAnd(test)] + : [test]; + let current = node, + listToCheck = conditionsToCheck.map(c => splitByOr(c).map(splitByAnd)); + + while (current.parent && current.parent.type === "IfStatement" && current.parent.alternate === current) { + current = current.parent; + + const currentOrOperands = splitByOr(current.test).map(splitByAnd); + + listToCheck = listToCheck.map(orOperands => orOperands.filter( + orOperand => !currentOrOperands.some(currentOrOperand => isSubset(currentOrOperand, orOperand)) + )); + + if (listToCheck.some(orOperands => orOperands.length === 0)) { + context.report({ node: test, messageId: "unexpected" }); + break; + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-keys.js b/node_modules/eslint/lib/rules/no-dupe-keys.js new file mode 100644 index 0000000..980b004 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-keys.js @@ -0,0 +1,142 @@ +/** + * @fileoverview Rule to flag use of duplicate keys in an object. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const GET_KIND = /^(?:init|get)$/u; +const SET_KIND = /^(?:init|set)$/u; + +/** + * The class which stores properties' information of an object. + */ +class ObjectInfo { + + /** + * @param {ObjectInfo|null} upper The information of the outer object. + * @param {ASTNode} node The ObjectExpression node of this information. + */ + constructor(upper, node) { + this.upper = upper; + this.node = node; + this.properties = new Map(); + } + + /** + * Gets the information of the given Property node. + * @param {ASTNode} node The Property node to get. + * @returns {{get: boolean, set: boolean}} The information of the property. + */ + getPropertyInfo(node) { + const name = astUtils.getStaticPropertyName(node); + + if (!this.properties.has(name)) { + this.properties.set(name, { get: false, set: false }); + } + return this.properties.get(name); + } + + /** + * Checks whether the given property has been defined already or not. + * @param {ASTNode} node The Property node to check. + * @returns {boolean} `true` if the property has been defined. + */ + isPropertyDefined(node) { + const entry = this.getPropertyInfo(node); + + return ( + (GET_KIND.test(node.kind) && entry.get) || + (SET_KIND.test(node.kind) && entry.set) + ); + } + + /** + * Defines the given property. + * @param {ASTNode} node The Property node to define. + * @returns {void} + */ + defineProperty(node) { + const entry = this.getPropertyInfo(node); + + if (GET_KIND.test(node.kind)) { + entry.get = true; + } + if (SET_KIND.test(node.kind)) { + entry.set = true; + } + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate keys in object literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-keys" + }, + + schema: [], + + messages: { + unexpected: "Duplicate key '{{name}}'." + } + }, + + create(context) { + let info = null; + + return { + ObjectExpression(node) { + info = new ObjectInfo(info, node); + }, + "ObjectExpression:exit"() { + info = info.upper; + }, + + Property(node) { + const name = astUtils.getStaticPropertyName(node); + + // Skip destructuring. + if (node.parent.type !== "ObjectExpression") { + return; + } + + // Skip if the name is not static. + if (name === null) { + return; + } + + // Reports if the name is defined already. + if (info.isPropertyDefined(node)) { + context.report({ + node: info.node, + loc: node.key.loc, + messageId: "unexpected", + data: { name } + }); + } + + // Update info. + info.defineProperty(node); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-duplicate-case.js b/node_modules/eslint/lib/rules/no-duplicate-case.js new file mode 100644 index 0000000..839f357 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-duplicate-case.js @@ -0,0 +1,71 @@ +/** + * @fileoverview Rule to disallow a duplicate case label. + * @author Dieter Oberkofler + * @author Burak Yigit Kaya + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate case labels", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-duplicate-case" + }, + + schema: [], + + messages: { + unexpected: "Duplicate case label." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether the two given nodes are considered to be equal. + * @param {ASTNode} a First node. + * @param {ASTNode} b Second node. + * @returns {boolean} `true` if the nodes are considered to be equal. + */ + function equal(a, b) { + if (a.type !== b.type) { + return false; + } + + return astUtils.equalTokens(a, b, sourceCode); + } + return { + SwitchStatement(node) { + const previousTests = []; + + for (const switchCase of node.cases) { + if (switchCase.test) { + const test = switchCase.test; + + if (previousTests.some(previousTest => equal(previousTest, test))) { + context.report({ node: switchCase, messageId: "unexpected" }); + } else { + previousTests.push(test); + } + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-duplicate-imports.js b/node_modules/eslint/lib/rules/no-duplicate-imports.js new file mode 100644 index 0000000..25c07b7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-duplicate-imports.js @@ -0,0 +1,290 @@ +/** + * @fileoverview Restrict usage of duplicate imports. + * @author Simen Bekkhus + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const NAMED_TYPES = ["ImportSpecifier", "ExportSpecifier"]; +const NAMESPACE_TYPES = [ + "ImportNamespaceSpecifier", + "ExportNamespaceSpecifier" +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Check if an import/export type belongs to (ImportSpecifier|ExportSpecifier) or (ImportNamespaceSpecifier|ExportNamespaceSpecifier). + * @param {string} importExportType An import/export type to check. + * @param {string} type Can be "named" or "namespace" + * @returns {boolean} True if import/export type belongs to (ImportSpecifier|ExportSpecifier) or (ImportNamespaceSpecifier|ExportNamespaceSpecifier) and false if it doesn't. + */ +function isImportExportSpecifier(importExportType, type) { + const arrayToCheck = type === "named" ? NAMED_TYPES : NAMESPACE_TYPES; + + return arrayToCheck.includes(importExportType); +} + +/** + * Return the type of (import|export). + * @param {ASTNode} node A node to get. + * @returns {string} The type of the (import|export). + */ +function getImportExportType(node) { + if (node.specifiers && node.specifiers.length > 0) { + const nodeSpecifiers = node.specifiers; + const index = nodeSpecifiers.findIndex( + ({ type }) => + isImportExportSpecifier(type, "named") || + isImportExportSpecifier(type, "namespace") + ); + const i = index > -1 ? index : 0; + + return nodeSpecifiers[i].type; + } + if (node.type === "ExportAllDeclaration") { + if (node.exported) { + return "ExportNamespaceSpecifier"; + } + return "ExportAll"; + } + return "SideEffectImport"; +} + +/** + * Returns a boolean indicates if two (import|export) can be merged + * @param {ASTNode} node1 A node to check. + * @param {ASTNode} node2 A node to check. + * @returns {boolean} True if two (import|export) can be merged, false if they can't. + */ +function isImportExportCanBeMerged(node1, node2) { + const importExportType1 = getImportExportType(node1); + const importExportType2 = getImportExportType(node2); + + if ( + (importExportType1 === "ExportAll" && + importExportType2 !== "ExportAll" && + importExportType2 !== "SideEffectImport") || + (importExportType1 !== "ExportAll" && + importExportType1 !== "SideEffectImport" && + importExportType2 === "ExportAll") + ) { + return false; + } + if ( + (isImportExportSpecifier(importExportType1, "namespace") && + isImportExportSpecifier(importExportType2, "named")) || + (isImportExportSpecifier(importExportType2, "namespace") && + isImportExportSpecifier(importExportType1, "named")) + ) { + return false; + } + return true; +} + +/** + * Returns a boolean if we should report (import|export). + * @param {ASTNode} node A node to be reported or not. + * @param {[ASTNode]} previousNodes An array contains previous nodes of the module imported or exported. + * @returns {boolean} True if the (import|export) should be reported. + */ +function shouldReportImportExport(node, previousNodes) { + let i = 0; + + while (i < previousNodes.length) { + if (isImportExportCanBeMerged(node, previousNodes[i])) { + return true; + } + i++; + } + return false; +} + +/** + * Returns array contains only nodes with declarations types equal to type. + * @param {[{node: ASTNode, declarationType: string}]} nodes An array contains objects, each object contains a node and a declaration type. + * @param {string} type Declaration type. + * @returns {[ASTNode]} An array contains only nodes with declarations types equal to type. + */ +function getNodesByDeclarationType(nodes, type) { + return nodes + .filter(({ declarationType }) => declarationType === type) + .map(({ node }) => node); +} + +/** + * Returns the name of the module imported or re-exported. + * @param {ASTNode} node A node to get. + * @returns {string} The name of the module, or empty string if no name. + */ +function getModule(node) { + if (node && node.source && node.source.value) { + return node.source.value.trim(); + } + return ""; +} + +/** + * Checks if the (import|export) can be merged with at least one import or one export, and reports if so. + * @param {RuleContext} context The ESLint rule context object. + * @param {ASTNode} node A node to get. + * @param {Map} modules A Map object contains as a key a module name and as value an array contains objects, each object contains a node and a declaration type. + * @param {string} declarationType A declaration type can be an import or export. + * @param {boolean} includeExports Whether or not to check for exports in addition to imports. + * @returns {void} No return value. + */ +function checkAndReport( + context, + node, + modules, + declarationType, + includeExports +) { + const module = getModule(node); + + if (modules.has(module)) { + const previousNodes = modules.get(module); + const messagesIds = []; + const importNodes = getNodesByDeclarationType(previousNodes, "import"); + let exportNodes; + + if (includeExports) { + exportNodes = getNodesByDeclarationType(previousNodes, "export"); + } + if (declarationType === "import") { + if (shouldReportImportExport(node, importNodes)) { + messagesIds.push("import"); + } + if (includeExports) { + if (shouldReportImportExport(node, exportNodes)) { + messagesIds.push("importAs"); + } + } + } else if (declarationType === "export") { + if (shouldReportImportExport(node, exportNodes)) { + messagesIds.push("export"); + } + if (shouldReportImportExport(node, importNodes)) { + messagesIds.push("exportAs"); + } + } + messagesIds.forEach(messageId => + context.report({ + node, + messageId, + data: { + module + } + })); + } +} + +/** + * @callback nodeCallback + * @param {ASTNode} node A node to handle. + */ + +/** + * Returns a function handling the (imports|exports) of a given file + * @param {RuleContext} context The ESLint rule context object. + * @param {Map} modules A Map object contains as a key a module name and as value an array contains objects, each object contains a node and a declaration type. + * @param {string} declarationType A declaration type can be an import or export. + * @param {boolean} includeExports Whether or not to check for exports in addition to imports. + * @returns {nodeCallback} A function passed to ESLint to handle the statement. + */ +function handleImportsExports( + context, + modules, + declarationType, + includeExports +) { + return function(node) { + const module = getModule(node); + + if (module) { + checkAndReport( + context, + node, + modules, + declarationType, + includeExports + ); + const currentNode = { node, declarationType }; + let nodes = [currentNode]; + + if (modules.has(module)) { + const previousNodes = modules.get(module); + + nodes = [...previousNodes, currentNode]; + } + modules.set(module, nodes); + } + }; +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate module imports", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-duplicate-imports" + }, + + schema: [ + { + type: "object", + properties: { + includeExports: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + import: "'{{module}}' import is duplicated.", + importAs: "'{{module}}' import is duplicated as export.", + export: "'{{module}}' export is duplicated.", + exportAs: "'{{module}}' export is duplicated as import." + } + }, + + create(context) { + const includeExports = (context.options[0] || {}).includeExports, + modules = new Map(); + const handlers = { + ImportDeclaration: handleImportsExports( + context, + modules, + "import", + includeExports + ) + }; + + if (includeExports) { + handlers.ExportNamedDeclaration = handleImportsExports( + context, + modules, + "export", + includeExports + ); + handlers.ExportAllDeclaration = handleImportsExports( + context, + modules, + "export", + includeExports + ); + } + return handlers; + } +}; diff --git a/node_modules/eslint/lib/rules/no-else-return.js b/node_modules/eslint/lib/rules/no-else-return.js new file mode 100644 index 0000000..9dbf569 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-else-return.js @@ -0,0 +1,405 @@ +/** + * @fileoverview Rule to flag `else` after a `return` in `if` + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const FixTracker = require("./utils/fix-tracker"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `else` blocks after `return` statements in `if` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-else-return" + }, + + schema: [{ + type: "object", + properties: { + allowElseIf: { + type: "boolean", + default: true + } + }, + additionalProperties: false + }], + + fixable: "code", + + messages: { + unexpected: "Unnecessary 'else' after 'return'." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whether the given names can be safely used to declare block-scoped variables + * in the given scope. Name collisions can produce redeclaration syntax errors, + * or silently change references and modify behavior of the original code. + * + * This is not a generic function. In particular, it is assumed that the scope is a function scope or + * a function's inner scope, and that the names can be valid identifiers in the given scope. + * @param {string[]} names Array of variable names. + * @param {eslint-scope.Scope} scope Function scope or a function's inner scope. + * @returns {boolean} True if all names can be safely declared, false otherwise. + */ + function isSafeToDeclare(names, scope) { + + if (names.length === 0) { + return true; + } + + const functionScope = scope.variableScope; + + /* + * If this is a function scope, scope.variables will contain parameters, implicit variables such as "arguments", + * all function-scoped variables ('var'), and block-scoped variables defined in the scope. + * If this is an inner scope, scope.variables will contain block-scoped variables defined in the scope. + * + * Redeclaring any of these would cause a syntax error, except for the implicit variables. + */ + const declaredVariables = scope.variables.filter(({ defs }) => defs.length > 0); + + if (declaredVariables.some(({ name }) => names.includes(name))) { + return false; + } + + // Redeclaring a catch variable would also cause a syntax error. + if (scope !== functionScope && scope.upper.type === "catch") { + if (scope.upper.variables.some(({ name }) => names.includes(name))) { + return false; + } + } + + /* + * Redeclaring an implicit variable, such as "arguments", would not cause a syntax error. + * However, if the variable was used, declaring a new one with the same name would change references + * and modify behavior. + */ + const usedImplicitVariables = scope.variables.filter(({ defs, references }) => + defs.length === 0 && references.length > 0); + + if (usedImplicitVariables.some(({ name }) => names.includes(name))) { + return false; + } + + /* + * Declaring a variable with a name that was already used to reference a variable from an upper scope + * would change references and modify behavior. + */ + if (scope.through.some(t => names.includes(t.identifier.name))) { + return false; + } + + /* + * If the scope is an inner scope (not the function scope), an uninitialized `var` variable declared inside + * the scope node (directly or in one of its descendants) is neither declared nor 'through' in the scope. + * + * For example, this would be a syntax error "Identifier 'a' has already been declared": + * function foo() { if (bar) { let a; if (baz) { var a; } } } + */ + if (scope !== functionScope) { + const scopeNodeRange = scope.block.range; + const variablesToCheck = functionScope.variables.filter(({ name }) => names.includes(name)); + + if (variablesToCheck.some(v => v.defs.some(({ node: { range } }) => + scopeNodeRange[0] <= range[0] && range[1] <= scopeNodeRange[1]))) { + return false; + } + } + + return true; + } + + + /** + * Checks whether the removal of `else` and its braces is safe from variable name collisions. + * @param {Node} node The 'else' node. + * @param {eslint-scope.Scope} scope The scope in which the node and the whole 'if' statement is. + * @returns {boolean} True if it is safe, false otherwise. + */ + function isSafeFromNameCollisions(node, scope) { + + if (node.type === "FunctionDeclaration") { + + // Conditional function declaration. Scope and hoisting are unpredictable, different engines work differently. + return false; + } + + if (node.type !== "BlockStatement") { + return true; + } + + const elseBlockScope = scope.childScopes.find(({ block }) => block === node); + + if (!elseBlockScope) { + + // ecmaVersion < 6, `else` block statement cannot have its own scope, no possible collisions. + return true; + } + + /* + * elseBlockScope is supposed to merge into its upper scope. elseBlockScope.variables array contains + * only block-scoped variables (such as let and const variables or class and function declarations) + * defined directly in the elseBlockScope. These are exactly the only names that could cause collisions. + */ + const namesToCheck = elseBlockScope.variables.map(({ name }) => name); + + return isSafeToDeclare(namesToCheck, scope); + } + + /** + * Display the context report if rule is violated + * @param {Node} elseNode The 'else' node + * @returns {void} + */ + function displayReport(elseNode) { + const currentScope = sourceCode.getScope(elseNode.parent); + + context.report({ + node: elseNode, + messageId: "unexpected", + fix(fixer) { + + if (!isSafeFromNameCollisions(elseNode, currentScope)) { + return null; + } + + const startToken = sourceCode.getFirstToken(elseNode); + const elseToken = sourceCode.getTokenBefore(startToken); + const source = sourceCode.getText(elseNode); + const lastIfToken = sourceCode.getTokenBefore(elseToken); + let fixedSource, firstTokenOfElseBlock; + + if (startToken.type === "Punctuator" && startToken.value === "{") { + firstTokenOfElseBlock = sourceCode.getTokenAfter(startToken); + } else { + firstTokenOfElseBlock = startToken; + } + + /* + * If the if block does not have curly braces and does not end in a semicolon + * and the else block starts with (, [, /, +, ` or -, then it is not + * safe to remove the else keyword, because ASI will not add a semicolon + * after the if block + */ + const ifBlockMaybeUnsafe = elseNode.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";"; + const elseBlockUnsafe = /^[([/+`-]/u.test(firstTokenOfElseBlock.value); + + if (ifBlockMaybeUnsafe && elseBlockUnsafe) { + return null; + } + + const endToken = sourceCode.getLastToken(elseNode); + const lastTokenOfElseBlock = sourceCode.getTokenBefore(endToken); + + if (lastTokenOfElseBlock.value !== ";") { + const nextToken = sourceCode.getTokenAfter(endToken); + + const nextTokenUnsafe = nextToken && /^[([/+`-]/u.test(nextToken.value); + const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line; + + /* + * If the else block contents does not end in a semicolon, + * and the else block starts with (, [, /, +, ` or -, then it is not + * safe to remove the else block, because ASI will not add a semicolon + * after the remaining else block contents + */ + if (nextTokenUnsafe || (nextTokenOnSameLine && nextToken.value !== "}")) { + return null; + } + } + + if (startToken.type === "Punctuator" && startToken.value === "{") { + fixedSource = source.slice(1, -1); + } else { + fixedSource = source; + } + + /* + * Extend the replacement range to include the entire + * function to avoid conflicting with no-useless-return. + * https://github.com/eslint/eslint/issues/8026 + * + * Also, to avoid name collisions between two else blocks. + */ + return new FixTracker(fixer, sourceCode) + .retainEnclosingFunction(elseNode) + .replaceTextRange([elseToken.range[0], elseNode.range[1]], fixedSource); + } + }); + } + + /** + * Check to see if the node is a ReturnStatement + * @param {Node} node The node being evaluated + * @returns {boolean} True if node is a return + */ + function checkForReturn(node) { + return node.type === "ReturnStatement"; + } + + /** + * Naive return checking, does not iterate through the whole + * BlockStatement because we make the assumption that the ReturnStatement + * will be the last node in the body of the BlockStatement. + * @param {Node} node The consequent/alternate node + * @returns {boolean} True if it has a return + */ + function naiveHasReturn(node) { + if (node.type === "BlockStatement") { + const body = node.body, + lastChildNode = body[body.length - 1]; + + return lastChildNode && checkForReturn(lastChildNode); + } + return checkForReturn(node); + } + + /** + * Check to see if the node is valid for evaluation, + * meaning it has an else. + * @param {Node} node The node being evaluated + * @returns {boolean} True if the node is valid + */ + function hasElse(node) { + return node.alternate && node.consequent; + } + + /** + * If the consequent is an IfStatement, check to see if it has an else + * and both its consequent and alternate path return, meaning this is + * a nested case of rule violation. If-Else not considered currently. + * @param {Node} node The consequent node + * @returns {boolean} True if this is a nested rule violation + */ + function checkForIf(node) { + return node.type === "IfStatement" && hasElse(node) && + naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent); + } + + /** + * Check the consequent/body node to make sure it is not + * a ReturnStatement or an IfStatement that returns on both + * code paths. + * @param {Node} node The consequent or body node + * @returns {boolean} `true` if it is a Return/If node that always returns. + */ + function checkForReturnOrIf(node) { + return checkForReturn(node) || checkForIf(node); + } + + + /** + * Check whether a node returns in every codepath. + * @param {Node} node The node to be checked + * @returns {boolean} `true` if it returns on every codepath. + */ + function alwaysReturns(node) { + if (node.type === "BlockStatement") { + + // If we have a BlockStatement, check each consequent body node. + return node.body.some(checkForReturnOrIf); + } + + /* + * If not a block statement, make sure the consequent isn't a + * ReturnStatement or an IfStatement with returns on both paths. + */ + return checkForReturnOrIf(node); + } + + + /** + * Check the if statement, but don't catch else-if blocks. + * @returns {void} + * @param {Node} node The node for the if statement to check + * @private + */ + function checkIfWithoutElse(node) { + const parent = node.parent; + + /* + * Fixing this would require splitting one statement into two, so no error should + * be reported if this node is in a position where only one statement is allowed. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { + return; + } + + const consequents = []; + let alternate; + + for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) { + if (!currentNode.alternate) { + return; + } + consequents.push(currentNode.consequent); + alternate = currentNode.alternate; + } + + if (consequents.every(alwaysReturns)) { + displayReport(alternate); + } + } + + /** + * Check the if statement + * @returns {void} + * @param {Node} node The node for the if statement to check + * @private + */ + function checkIfWithElse(node) { + const parent = node.parent; + + + /* + * Fixing this would require splitting one statement into two, so no error should + * be reported if this node is in a position where only one statement is allowed. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { + return; + } + + const alternate = node.alternate; + + if (alternate && alwaysReturns(node.consequent)) { + displayReport(alternate); + } + } + + const allowElseIf = !(context.options[0] && context.options[0].allowElseIf === false); + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "IfStatement:exit": allowElseIf ? checkIfWithoutElse : checkIfWithElse + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-empty-character-class.js b/node_modules/eslint/lib/rules/no-empty-character-class.js new file mode 100644 index 0000000..5c84102 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-character-class.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Rule to flag the use of empty character classes in regular expressions + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new RegExpParser(); +const QUICK_TEST_REGEX = /\[\]/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow empty character classes in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty-character-class" + }, + + schema: [], + + messages: { + unexpected: "Empty class." + } + }, + + create(context) { + return { + "Literal[regex]"(node) { + const { pattern, flags } = node.regex; + + if (!QUICK_TEST_REGEX.test(pattern)) { + return; + } + + let regExpAST; + + try { + regExpAST = parser.parsePattern(pattern, 0, pattern.length, { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v") + }); + } catch { + + // Ignore regular expressions that regexpp cannot parse + return; + } + + visitRegExpAST(regExpAST, { + onCharacterClassEnter(characterClass) { + if (!characterClass.negate && characterClass.elements.length === 0) { + context.report({ node, messageId: "unexpected" }); + } + } + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-empty-function.js b/node_modules/eslint/lib/rules/no-empty-function.js new file mode 100644 index 0000000..2fcb755 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-function.js @@ -0,0 +1,167 @@ +/** + * @fileoverview Rule to disallow empty functions. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const ALLOW_OPTIONS = Object.freeze([ + "functions", + "arrowFunctions", + "generatorFunctions", + "methods", + "generatorMethods", + "getters", + "setters", + "constructors", + "asyncFunctions", + "asyncMethods" +]); + +/** + * Gets the kind of a given function node. + * @param {ASTNode} node A function node to get. This is one of + * an ArrowFunctionExpression, a FunctionDeclaration, or a + * FunctionExpression. + * @returns {string} The kind of the function. This is one of "functions", + * "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods", + * "generatorMethods", "asyncMethods", "getters", "setters", and + * "constructors". + */ +function getKind(node) { + const parent = node.parent; + let kind = ""; + + if (node.type === "ArrowFunctionExpression") { + return "arrowFunctions"; + } + + // Detects main kind. + if (parent.type === "Property") { + if (parent.kind === "get") { + return "getters"; + } + if (parent.kind === "set") { + return "setters"; + } + kind = parent.method ? "methods" : "functions"; + + } else if (parent.type === "MethodDefinition") { + if (parent.kind === "get") { + return "getters"; + } + if (parent.kind === "set") { + return "setters"; + } + if (parent.kind === "constructor") { + return "constructors"; + } + kind = "methods"; + + } else { + kind = "functions"; + } + + // Detects prefix. + let prefix = ""; + + if (node.generator) { + prefix = "generator"; + } else if (node.async) { + prefix = "async"; + } else { + return kind; + } + return prefix + kind[0].toUpperCase() + kind.slice(1); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow empty functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-empty-function" + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { enum: ALLOW_OPTIONS }, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpected: "Unexpected empty {{name}}." + } + }, + + create(context) { + const options = context.options[0] || {}; + const allowed = options.allow || []; + + const sourceCode = context.sourceCode; + + /** + * Reports a given function node if the node matches the following patterns. + * + * - Not allowed by options. + * - The body is empty. + * - The body doesn't have any comments. + * @param {ASTNode} node A function node to report. This is one of + * an ArrowFunctionExpression, a FunctionDeclaration, or a + * FunctionExpression. + * @returns {void} + */ + function reportIfEmpty(node) { + const kind = getKind(node); + const name = astUtils.getFunctionNameWithKind(node); + const innerComments = sourceCode.getTokens(node.body, { + includeComments: true, + filter: astUtils.isCommentToken + }); + + if (!allowed.includes(kind) && + node.body.type === "BlockStatement" && + node.body.body.length === 0 && + innerComments.length === 0 + ) { + context.report({ + node, + loc: node.body.loc, + messageId: "unexpected", + data: { name } + }); + } + } + + return { + ArrowFunctionExpression: reportIfEmpty, + FunctionDeclaration: reportIfEmpty, + FunctionExpression: reportIfEmpty + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-empty-pattern.js b/node_modules/eslint/lib/rules/no-empty-pattern.js new file mode 100644 index 0000000..fb75f6d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-pattern.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Rule to disallow an empty pattern + * @author Alberto Rodríguez + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow empty destructuring patterns", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty-pattern" + }, + + schema: [ + { + type: "object", + properties: { + allowObjectPatternsAsParameters: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + unexpected: "Unexpected empty {{type}} pattern." + } + }, + + create(context) { + const options = context.options[0] || {}, + allowObjectPatternsAsParameters = options.allowObjectPatternsAsParameters || false; + + return { + ObjectPattern(node) { + + if (node.properties.length > 0) { + return; + } + + // Allow {} and {} = {} empty object patterns as parameters when allowObjectPatternsAsParameters is true + if ( + allowObjectPatternsAsParameters && + ( + astUtils.isFunction(node.parent) || + ( + node.parent.type === "AssignmentPattern" && + astUtils.isFunction(node.parent.parent) && + node.parent.right.type === "ObjectExpression" && + node.parent.right.properties.length === 0 + ) + ) + ) { + return; + } + + context.report({ node, messageId: "unexpected", data: { type: "object" } }); + }, + ArrayPattern(node) { + if (node.elements.length === 0) { + context.report({ node, messageId: "unexpected", data: { type: "array" } }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-empty-static-block.js b/node_modules/eslint/lib/rules/no-empty-static-block.js new file mode 100644 index 0000000..81fc449 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-static-block.js @@ -0,0 +1,47 @@ +/** + * @fileoverview Rule to disallow empty static blocks. + * @author Sosuke Suzuki + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow empty static blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-empty-static-block" + }, + + schema: [], + + messages: { + unexpected: "Unexpected empty static block." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + StaticBlock(node) { + if (node.body.length === 0) { + const closingBrace = sourceCode.getLastToken(node); + + if (sourceCode.getCommentsBefore(closingBrace).length === 0) { + context.report({ + node, + messageId: "unexpected" + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-empty.js b/node_modules/eslint/lib/rules/no-empty.js new file mode 100644 index 0000000..1c15796 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty.js @@ -0,0 +1,103 @@ +/** + * @fileoverview Rule to flag use of an empty block statement + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + docs: { + description: "Disallow empty block statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty" + }, + + schema: [ + { + type: "object", + properties: { + allowEmptyCatch: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + unexpected: "Empty {{type}} statement.", + suggestComment: "Add comment inside empty {{type}} statement." + } + }, + + create(context) { + const options = context.options[0] || {}, + allowEmptyCatch = options.allowEmptyCatch || false; + + const sourceCode = context.sourceCode; + + return { + BlockStatement(node) { + + // if the body is not empty, we can just return immediately + if (node.body.length !== 0) { + return; + } + + // a function is generally allowed to be empty + if (astUtils.isFunction(node.parent)) { + return; + } + + if (allowEmptyCatch && node.parent.type === "CatchClause") { + return; + } + + // any other block is only allowed to be empty, if it contains a comment + if (sourceCode.getCommentsInside(node).length > 0) { + return; + } + + context.report({ + node, + messageId: "unexpected", + data: { type: "block" }, + suggest: [ + { + messageId: "suggestComment", + data: { type: "block" }, + fix(fixer) { + const range = [node.range[0] + 1, node.range[1] - 1]; + + return fixer.replaceTextRange(range, " /* empty */ "); + } + } + ] + }); + }, + + SwitchStatement(node) { + + if (typeof node.cases === "undefined" || node.cases.length === 0) { + context.report({ node, messageId: "unexpected", data: { type: "switch" } }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-eq-null.js b/node_modules/eslint/lib/rules/no-eq-null.js new file mode 100644 index 0000000..9252907 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-eq-null.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Rule to flag comparisons to null without a type-checking + * operator. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `null` comparisons without type-checking operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-eq-null" + }, + + schema: [], + + messages: { + unexpected: "Use '===' to compare with null." + } + }, + + create(context) { + + return { + + BinaryExpression(node) { + const badOperator = node.operator === "==" || node.operator === "!="; + + if (node.right.type === "Literal" && node.right.raw === "null" && badOperator || + node.left.type === "Literal" && node.left.raw === "null" && badOperator) { + context.report({ node, messageId: "unexpected" }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-eval.js b/node_modules/eslint/lib/rules/no-eval.js new file mode 100644 index 0000000..a059526 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-eval.js @@ -0,0 +1,286 @@ +/** + * @fileoverview Rule to flag use of eval() statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const candidatesOfGlobalObject = Object.freeze([ + "global", + "window", + "globalThis" +]); + +/** + * Checks a given node is a MemberExpression node which has the specified name's + * property. + * @param {ASTNode} node A node to check. + * @param {string} name A name to check. + * @returns {boolean} `true` if the node is a MemberExpression node which has + * the specified name's property + */ +function isMember(node, name) { + return astUtils.isSpecificMemberAccess(node, null, name); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `eval()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-eval" + }, + + schema: [ + { + type: "object", + properties: { + allowIndirect: { type: "boolean", default: false } + }, + additionalProperties: false + } + ], + + messages: { + unexpected: "eval can be harmful." + } + }, + + create(context) { + const allowIndirect = Boolean( + context.options[0] && + context.options[0].allowIndirect + ); + const sourceCode = context.sourceCode; + let funcInfo = null; + + /** + * Pushes a `this` scope (non-arrow function, class static block, or class field initializer) information to the stack. + * Top-level scopes are handled separately. + * + * This is used in order to check whether or not `this` binding is a + * reference to the global object. + * @param {ASTNode} node A node of the scope. + * For functions, this is one of FunctionDeclaration, FunctionExpression. + * For class static blocks, this is StaticBlock. + * For class field initializers, this can be any node that is PropertyDefinition#value. + * @returns {void} + */ + function enterThisScope(node) { + const strict = sourceCode.getScope(node).isStrict; + + funcInfo = { + upper: funcInfo, + node, + strict, + isTopLevelOfScript: false, + defaultThis: false, + initialized: strict + }; + } + + /** + * Pops a variable scope from the stack. + * @returns {void} + */ + function exitThisScope() { + funcInfo = funcInfo.upper; + } + + /** + * Reports a given node. + * + * `node` is `Identifier` or `MemberExpression`. + * The parent of `node` might be `CallExpression`. + * + * The location of the report is always `eval` `Identifier` (or possibly + * `Literal`). The type of the report is `CallExpression` if the parent is + * `CallExpression`. Otherwise, it's the given node type. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function report(node) { + const parent = node.parent; + const locationNode = node.type === "MemberExpression" + ? node.property + : node; + + const reportNode = parent.type === "CallExpression" && parent.callee === node + ? parent + : node; + + context.report({ + node: reportNode, + loc: locationNode.loc, + messageId: "unexpected" + }); + } + + /** + * Reports accesses of `eval` via the global object. + * @param {eslint-scope.Scope} globalScope The global scope. + * @returns {void} + */ + function reportAccessingEvalViaGlobalObject(globalScope) { + for (let i = 0; i < candidatesOfGlobalObject.length; ++i) { + const name = candidatesOfGlobalObject[i]; + const variable = astUtils.getVariableByName(globalScope, name); + + if (!variable) { + continue; + } + + const references = variable.references; + + for (let j = 0; j < references.length; ++j) { + const identifier = references[j].identifier; + let node = identifier.parent; + + // To detect code like `window.window.eval`. + while (isMember(node, name)) { + node = node.parent; + } + + // Reports. + if (isMember(node, "eval")) { + report(node); + } + } + } + } + + /** + * Reports all accesses of `eval` (excludes direct calls to eval). + * @param {eslint-scope.Scope} globalScope The global scope. + * @returns {void} + */ + function reportAccessingEval(globalScope) { + const variable = astUtils.getVariableByName(globalScope, "eval"); + + if (!variable) { + return; + } + + const references = variable.references; + + for (let i = 0; i < references.length; ++i) { + const reference = references[i]; + const id = reference.identifier; + + if (id.name === "eval" && !astUtils.isCallee(id)) { + + // Is accessing to eval (excludes direct calls to eval) + report(id); + } + } + } + + if (allowIndirect) { + + // Checks only direct calls to eval. It's simple! + return { + "CallExpression:exit"(node) { + const callee = node.callee; + + /* + * Optional call (`eval?.("code")`) is not direct eval. + * The direct eval is only step 6.a.vi of https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation + * But the optional call is https://tc39.es/ecma262/#sec-optional-chaining-chain-evaluation + */ + if (!node.optional && astUtils.isSpecificId(callee, "eval")) { + report(callee); + } + } + }; + } + + return { + "CallExpression:exit"(node) { + const callee = node.callee; + + if (astUtils.isSpecificId(callee, "eval")) { + report(callee); + } + }, + + Program(node) { + const scope = sourceCode.getScope(node), + features = context.parserOptions.ecmaFeatures || {}, + strict = + scope.isStrict || + node.sourceType === "module" || + (features.globalReturn && scope.childScopes[0].isStrict), + isTopLevelOfScript = node.sourceType !== "module" && !features.globalReturn; + + funcInfo = { + upper: null, + node, + strict, + isTopLevelOfScript, + defaultThis: true, + initialized: true + }; + }, + + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + exitThisScope(); + reportAccessingEval(globalScope); + reportAccessingEvalViaGlobalObject(globalScope); + }, + + FunctionDeclaration: enterThisScope, + "FunctionDeclaration:exit": exitThisScope, + FunctionExpression: enterThisScope, + "FunctionExpression:exit": exitThisScope, + "PropertyDefinition > *.value": enterThisScope, + "PropertyDefinition > *.value:exit": exitThisScope, + StaticBlock: enterThisScope, + "StaticBlock:exit": exitThisScope, + + ThisExpression(node) { + if (!isMember(node.parent, "eval")) { + return; + } + + /* + * `this.eval` is found. + * Checks whether or not the value of `this` is the global object. + */ + if (!funcInfo.initialized) { + funcInfo.initialized = true; + funcInfo.defaultThis = astUtils.isDefaultThisBinding( + funcInfo.node, + sourceCode + ); + } + + // `this` at the top level of scripts always refers to the global object + if (funcInfo.isTopLevelOfScript || (!funcInfo.strict && funcInfo.defaultThis)) { + + // `this.eval` is possible built-in `eval`. + report(node.parent); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-ex-assign.js b/node_modules/eslint/lib/rules/no-ex-assign.js new file mode 100644 index 0000000..d0e9feb --- /dev/null +++ b/node_modules/eslint/lib/rules/no-ex-assign.js @@ -0,0 +1,54 @@ +/** + * @fileoverview Rule to flag assignment of the exception parameter + * @author Stephen Murray + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning exceptions in `catch` clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-ex-assign" + }, + + schema: [], + + messages: { + unexpected: "Do not assign to the exception parameter." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, messageId: "unexpected" }); + }); + } + + return { + CatchClause(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-extend-native.js b/node_modules/eslint/lib/rules/no-extend-native.js new file mode 100644 index 0000000..fcbb385 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extend-native.js @@ -0,0 +1,179 @@ +/** + * @fileoverview Rule to flag adding properties to native object's prototypes. + * @author David Nelson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const globals = require("globals"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow extending native types", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extend-native" + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpected: "{{builtin}} prototype is read only, properties should not be added." + } + }, + + create(context) { + + const config = context.options[0] || {}; + const sourceCode = context.sourceCode; + const exceptions = new Set(config.exceptions || []); + const modifiedBuiltins = new Set( + Object.keys(globals.builtin) + .filter(builtin => builtin[0].toUpperCase() === builtin[0]) + .filter(builtin => !exceptions.has(builtin)) + ); + + /** + * Reports a lint error for the given node. + * @param {ASTNode} node The node to report. + * @param {string} builtin The name of the native builtin being extended. + * @returns {void} + */ + function reportNode(node, builtin) { + context.report({ + node, + messageId: "unexpected", + data: { + builtin + } + }); + } + + /** + * Check to see if the `prototype` property of the given object + * identifier node is being accessed. + * @param {ASTNode} identifierNode The Identifier representing the object + * to check. + * @returns {boolean} True if the identifier is the object of a + * MemberExpression and its `prototype` property is being accessed, + * false otherwise. + */ + function isPrototypePropertyAccessed(identifierNode) { + return Boolean( + identifierNode && + identifierNode.parent && + identifierNode.parent.type === "MemberExpression" && + identifierNode.parent.object === identifierNode && + astUtils.getStaticPropertyName(identifierNode.parent) === "prototype" + ); + } + + /** + * Check if it's an assignment to the property of the given node. + * Example: `*.prop = 0` // the `*` is the given node. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if an assignment to the property of the node. + */ + function isAssigningToPropertyOf(node) { + return ( + node.parent.type === "MemberExpression" && + node.parent.object === node && + node.parent.parent.type === "AssignmentExpression" && + node.parent.parent.left === node.parent + ); + } + + /** + * Checks if the given node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`. + */ + function isInDefinePropertyCall(node) { + return ( + node.parent.type === "CallExpression" && + node.parent.arguments[0] === node && + astUtils.isSpecificMemberAccess(node.parent.callee, "Object", /^definePropert(?:y|ies)$/u) + ); + } + + /** + * Check to see if object prototype access is part of a prototype + * extension. There are three ways a prototype can be extended: + * 1. Assignment to prototype property (Object.prototype.foo = 1) + * 2. Object.defineProperty()/Object.defineProperties() on a prototype + * If prototype extension is detected, report the AssignmentExpression + * or CallExpression node. + * @param {ASTNode} identifierNode The Identifier representing the object + * which prototype is being accessed and possibly extended. + * @returns {void} + */ + function checkAndReportPrototypeExtension(identifierNode) { + if (!isPrototypePropertyAccessed(identifierNode)) { + return; // This is not `*.prototype` access. + } + + /* + * `identifierNode.parent` is a MemberExpression `*.prototype`. + * If it's an optional member access, it may be wrapped by a `ChainExpression` node. + */ + const prototypeNode = + identifierNode.parent.parent.type === "ChainExpression" + ? identifierNode.parent.parent + : identifierNode.parent; + + if (isAssigningToPropertyOf(prototypeNode)) { + + // `*.prototype` -> MemberExpression -> AssignmentExpression + reportNode(prototypeNode.parent.parent, identifierNode.name); + } else if (isInDefinePropertyCall(prototypeNode)) { + + // `*.prototype` -> CallExpression + reportNode(prototypeNode.parent, identifierNode.name); + } + } + + return { + + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + modifiedBuiltins.forEach(builtin => { + const builtinVar = globalScope.set.get(builtin); + + if (builtinVar && builtinVar.references) { + builtinVar.references + .map(ref => ref.identifier) + .forEach(checkAndReportPrototypeExtension); + } + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-extra-bind.js b/node_modules/eslint/lib/rules/no-extra-bind.js new file mode 100644 index 0000000..e1e72b0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-bind.js @@ -0,0 +1,213 @@ +/** + * @fileoverview Rule to flag unnecessary bind calls + * @author Bence Dányi + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SIDE_EFFECT_FREE_NODE_TYPES = new Set(["Literal", "Identifier", "ThisExpression", "FunctionExpression"]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary calls to `.bind()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-bind" + }, + + schema: [], + fixable: "code", + + messages: { + unexpected: "The function binding is unnecessary." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Checks if a node is free of side effects. + * + * This check is stricter than it needs to be, in order to keep the implementation simple. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is known to be side-effect free, false otherwise. + */ + function isSideEffectFree(node) { + return SIDE_EFFECT_FREE_NODE_TYPES.has(node.type); + } + + /** + * Reports a given function node. + * @param {ASTNode} node A node to report. This is a FunctionExpression or + * an ArrowFunctionExpression. + * @returns {void} + */ + function report(node) { + const memberNode = node.parent; + const callNode = memberNode.parent.type === "ChainExpression" + ? memberNode.parent.parent + : memberNode.parent; + + context.report({ + node: callNode, + messageId: "unexpected", + loc: memberNode.property.loc, + + fix(fixer) { + if (!isSideEffectFree(callNode.arguments[0])) { + return null; + } + + /* + * The list of the first/last token pair of a removal range. + * This is two parts because closing parentheses may exist between the method name and arguments. + * E.g. `(function(){}.bind ) (obj)` + * ^^^^^ ^^^^^ < removal ranges + * E.g. `(function(){}?.['bind'] ) ?.(obj)` + * ^^^^^^^^^^ ^^^^^^^ < removal ranges + */ + const tokenPairs = [ + [ + + // `.`, `?.`, or `[` token. + sourceCode.getTokenAfter( + memberNode.object, + astUtils.isNotClosingParenToken + ), + + // property name or `]` token. + sourceCode.getLastToken(memberNode) + ], + [ + + // `?.` or `(` token of arguments. + sourceCode.getTokenAfter( + memberNode, + astUtils.isNotClosingParenToken + ), + + // `)` token of arguments. + sourceCode.getLastToken(callNode) + ] + ]; + const firstTokenToRemove = tokenPairs[0][0]; + const lastTokenToRemove = tokenPairs[1][1]; + + if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) { + return null; + } + + return tokenPairs.map(([start, end]) => + fixer.removeRange([start.range[0], end.range[1]])); + } + }); + } + + /** + * Checks whether or not a given function node is the callee of `.bind()` + * method. + * + * e.g. `(function() {}.bind(foo))` + * @param {ASTNode} node A node to report. This is a FunctionExpression or + * an ArrowFunctionExpression. + * @returns {boolean} `true` if the node is the callee of `.bind()` method. + */ + function isCalleeOfBindMethod(node) { + if (!astUtils.isSpecificMemberAccess(node.parent, null, "bind")) { + return false; + } + + // The node of `*.bind` member access. + const bindNode = node.parent.parent.type === "ChainExpression" + ? node.parent.parent + : node.parent; + + return ( + bindNode.parent.type === "CallExpression" && + bindNode.parent.callee === bindNode && + bindNode.parent.arguments.length === 1 && + bindNode.parent.arguments[0].type !== "SpreadElement" + ); + } + + /** + * Adds a scope information object to the stack. + * @param {ASTNode} node A node to add. This node is a FunctionExpression + * or a FunctionDeclaration node. + * @returns {void} + */ + function enterFunction(node) { + scopeInfo = { + isBound: isCalleeOfBindMethod(node), + thisFound: false, + upper: scopeInfo + }; + } + + /** + * Removes the scope information object from the top of the stack. + * At the same time, this reports the function node if the function has + * `.bind()` and the `this` keywords found. + * @param {ASTNode} node A node to remove. This node is a + * FunctionExpression or a FunctionDeclaration node. + * @returns {void} + */ + function exitFunction(node) { + if (scopeInfo.isBound && !scopeInfo.thisFound) { + report(node); + } + + scopeInfo = scopeInfo.upper; + } + + /** + * Reports a given arrow function if the function is callee of `.bind()` + * method. + * @param {ASTNode} node A node to report. This node is an + * ArrowFunctionExpression. + * @returns {void} + */ + function exitArrowFunction(node) { + if (isCalleeOfBindMethod(node)) { + report(node); + } + } + + /** + * Set the mark as the `this` keyword was found in this scope. + * @returns {void} + */ + function markAsThisFound() { + if (scopeInfo) { + scopeInfo.thisFound = true; + } + } + + return { + "ArrowFunctionExpression:exit": exitArrowFunction, + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + ThisExpression: markAsThisFound + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-extra-boolean-cast.js b/node_modules/eslint/lib/rules/no-extra-boolean-cast.js new file mode 100644 index 0000000..f342533 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-boolean-cast.js @@ -0,0 +1,317 @@ +/** + * @fileoverview Rule to flag unnecessary double negation in Boolean contexts + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const eslintUtils = require("@eslint-community/eslint-utils"); + +const precedence = astUtils.getPrecedence; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary boolean casts", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-extra-boolean-cast" + }, + + schema: [{ + type: "object", + properties: { + enforceForLogicalOperands: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + fixable: "code", + + messages: { + unexpectedCall: "Redundant Boolean call.", + unexpectedNegation: "Redundant double negation." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + // Node types which have a test which will coerce values to booleans. + const BOOLEAN_NODE_TYPES = new Set([ + "IfStatement", + "DoWhileStatement", + "WhileStatement", + "ConditionalExpression", + "ForStatement" + ]); + + /** + * Check if a node is a Boolean function or constructor. + * @param {ASTNode} node the node + * @returns {boolean} If the node is Boolean function or constructor + */ + function isBooleanFunctionOrConstructorCall(node) { + + // Boolean() and new Boolean() + return (node.type === "CallExpression" || node.type === "NewExpression") && + node.callee.type === "Identifier" && + node.callee.name === "Boolean"; + } + + /** + * Checks whether the node is a logical expression and that the option is enabled + * @param {ASTNode} node the node + * @returns {boolean} if the node is a logical expression and option is enabled + */ + function isLogicalContext(node) { + return node.type === "LogicalExpression" && + (node.operator === "||" || node.operator === "&&") && + (context.options.length && context.options[0].enforceForLogicalOperands === true); + + } + + + /** + * Check if a node is in a context where its value would be coerced to a boolean at runtime. + * @param {ASTNode} node The node + * @returns {boolean} If it is in a boolean context + */ + function isInBooleanContext(node) { + return ( + (isBooleanFunctionOrConstructorCall(node.parent) && + node === node.parent.arguments[0]) || + + (BOOLEAN_NODE_TYPES.has(node.parent.type) && + node === node.parent.test) || + + // ! + (node.parent.type === "UnaryExpression" && + node.parent.operator === "!") + ); + } + + /** + * Checks whether the node is a context that should report an error + * Acts recursively if it is in a logical context + * @param {ASTNode} node the node + * @returns {boolean} If the node is in one of the flagged contexts + */ + function isInFlaggedContext(node) { + if (node.parent.type === "ChainExpression") { + return isInFlaggedContext(node.parent); + } + + return isInBooleanContext(node) || + (isLogicalContext(node.parent) && + + // For nested logical statements + isInFlaggedContext(node.parent) + ); + } + + + /** + * Check if a node has comments inside. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if it has comments inside. + */ + function hasCommentsInside(node) { + return Boolean(sourceCode.getCommentsInside(node).length); + } + + /** + * Checks if the given node is wrapped in grouping parentheses. Parentheses for constructs such as if() don't count. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is parenthesized. + * @private + */ + function isParenthesized(node) { + return eslintUtils.isParenthesized(1, node, sourceCode); + } + + /** + * Determines whether the given node needs to be parenthesized when replacing the previous node. + * It assumes that `previousNode` is the node to be reported by this rule, so it has a limited list + * of possible parent node types. By the same assumption, the node's role in a particular parent is already known. + * For example, if the parent is `ConditionalExpression`, `previousNode` must be its `test` child. + * @param {ASTNode} previousNode Previous node. + * @param {ASTNode} node The node to check. + * @throws {Error} (Unreachable.) + * @returns {boolean} `true` if the node needs to be parenthesized. + */ + function needsParens(previousNode, node) { + if (previousNode.parent.type === "ChainExpression") { + return needsParens(previousNode.parent, node); + } + if (isParenthesized(previousNode)) { + + // parentheses around the previous node will stay, so there is no need for an additional pair + return false; + } + + // parent of the previous node will become parent of the replacement node + const parent = previousNode.parent; + + switch (parent.type) { + case "CallExpression": + case "NewExpression": + return node.type === "SequenceExpression"; + case "IfStatement": + case "DoWhileStatement": + case "WhileStatement": + case "ForStatement": + return false; + case "ConditionalExpression": + return precedence(node) <= precedence(parent); + case "UnaryExpression": + return precedence(node) < precedence(parent); + case "LogicalExpression": + if (astUtils.isMixedLogicalAndCoalesceExpressions(node, parent)) { + return true; + } + if (previousNode === parent.left) { + return precedence(node) < precedence(parent); + } + return precedence(node) <= precedence(parent); + + /* c8 ignore next */ + default: + throw new Error(`Unexpected parent type: ${parent.type}`); + } + } + + return { + UnaryExpression(node) { + const parent = node.parent; + + + // Exit early if it's guaranteed not to match + if (node.operator !== "!" || + parent.type !== "UnaryExpression" || + parent.operator !== "!") { + return; + } + + + if (isInFlaggedContext(parent)) { + context.report({ + node: parent, + messageId: "unexpectedNegation", + fix(fixer) { + if (hasCommentsInside(parent)) { + return null; + } + + if (needsParens(parent, node.argument)) { + return fixer.replaceText(parent, `(${sourceCode.getText(node.argument)})`); + } + + let prefix = ""; + const tokenBefore = sourceCode.getTokenBefore(parent); + const firstReplacementToken = sourceCode.getFirstToken(node.argument); + + if ( + tokenBefore && + tokenBefore.range[1] === parent.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken) + ) { + prefix = " "; + } + + return fixer.replaceText(parent, prefix + sourceCode.getText(node.argument)); + } + }); + } + }, + + CallExpression(node) { + if (node.callee.type !== "Identifier" || node.callee.name !== "Boolean") { + return; + } + + if (isInFlaggedContext(node)) { + context.report({ + node, + messageId: "unexpectedCall", + fix(fixer) { + const parent = node.parent; + + if (node.arguments.length === 0) { + if (parent.type === "UnaryExpression" && parent.operator === "!") { + + /* + * !Boolean() -> true + */ + + if (hasCommentsInside(parent)) { + return null; + } + + const replacement = "true"; + let prefix = ""; + const tokenBefore = sourceCode.getTokenBefore(parent); + + if ( + tokenBefore && + tokenBefore.range[1] === parent.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, replacement) + ) { + prefix = " "; + } + + return fixer.replaceText(parent, prefix + replacement); + } + + /* + * Boolean() -> false + */ + + if (hasCommentsInside(node)) { + return null; + } + + return fixer.replaceText(node, "false"); + } + + if (node.arguments.length === 1) { + const argument = node.arguments[0]; + + if (argument.type === "SpreadElement" || hasCommentsInside(node)) { + return null; + } + + /* + * Boolean(expression) -> expression + */ + + if (needsParens(node, argument)) { + return fixer.replaceText(node, `(${sourceCode.getText(argument)})`); + } + + return fixer.replaceText(node, sourceCode.getText(argument)); + } + + // two or more arguments + return null; + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-extra-label.js b/node_modules/eslint/lib/rules/no-extra-label.js new file mode 100644 index 0000000..45ff441 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-label.js @@ -0,0 +1,149 @@ +/** + * @fileoverview Rule to disallow unnecessary labels + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary labels", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-label" + }, + + schema: [], + fixable: "code", + + messages: { + unexpected: "This label '{{name}}' is unnecessary." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Creates a new scope with a breakable statement. + * @param {ASTNode} node A node to create. This is a BreakableStatement. + * @returns {void} + */ + function enterBreakableStatement(node) { + scopeInfo = { + label: node.parent.type === "LabeledStatement" ? node.parent.label : null, + breakable: true, + upper: scopeInfo + }; + } + + /** + * Removes the top scope of the stack. + * @returns {void} + */ + function exitBreakableStatement() { + scopeInfo = scopeInfo.upper; + } + + /** + * Creates a new scope with a labeled statement. + * + * This ignores it if the body is a breakable statement. + * In this case it's handled in the `enterBreakableStatement` function. + * @param {ASTNode} node A node to create. This is a LabeledStatement. + * @returns {void} + */ + function enterLabeledStatement(node) { + if (!astUtils.isBreakableStatement(node.body)) { + scopeInfo = { + label: node.label, + breakable: false, + upper: scopeInfo + }; + } + } + + /** + * Removes the top scope of the stack. + * + * This ignores it if the body is a breakable statement. + * In this case it's handled in the `exitBreakableStatement` function. + * @param {ASTNode} node A node. This is a LabeledStatement. + * @returns {void} + */ + function exitLabeledStatement(node) { + if (!astUtils.isBreakableStatement(node.body)) { + scopeInfo = scopeInfo.upper; + } + } + + /** + * Reports a given control node if it's unnecessary. + * @param {ASTNode} node A node. This is a BreakStatement or a + * ContinueStatement. + * @returns {void} + */ + function reportIfUnnecessary(node) { + if (!node.label) { + return; + } + + const labelNode = node.label; + + for (let info = scopeInfo; info !== null; info = info.upper) { + if (info.breakable || info.label && info.label.name === labelNode.name) { + if (info.breakable && info.label && info.label.name === labelNode.name) { + context.report({ + node: labelNode, + messageId: "unexpected", + data: labelNode, + fix(fixer) { + const breakOrContinueToken = sourceCode.getFirstToken(node); + + if (sourceCode.commentsExistBetween(breakOrContinueToken, labelNode)) { + return null; + } + + return fixer.removeRange([breakOrContinueToken.range[1], labelNode.range[1]]); + } + }); + } + return; + } + } + } + + return { + WhileStatement: enterBreakableStatement, + "WhileStatement:exit": exitBreakableStatement, + DoWhileStatement: enterBreakableStatement, + "DoWhileStatement:exit": exitBreakableStatement, + ForStatement: enterBreakableStatement, + "ForStatement:exit": exitBreakableStatement, + ForInStatement: enterBreakableStatement, + "ForInStatement:exit": exitBreakableStatement, + ForOfStatement: enterBreakableStatement, + "ForOfStatement:exit": exitBreakableStatement, + SwitchStatement: enterBreakableStatement, + "SwitchStatement:exit": exitBreakableStatement, + LabeledStatement: enterLabeledStatement, + "LabeledStatement:exit": exitLabeledStatement, + BreakStatement: reportIfUnnecessary, + ContinueStatement: reportIfUnnecessary + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-extra-parens.js b/node_modules/eslint/lib/rules/no-extra-parens.js new file mode 100644 index 0000000..bb80987 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-parens.js @@ -0,0 +1,1319 @@ +/** + * @fileoverview Disallow parenthesising higher precedence subexpressions. + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const { isParenthesized: isParenthesizedRaw } = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils.js"); + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow unnecessary parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-parens" + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["functions"] + } + ], + minItems: 0, + maxItems: 1 + }, + { + type: "array", + items: [ + { + enum: ["all"] + }, + { + type: "object", + properties: { + conditionalAssign: { type: "boolean" }, + ternaryOperandBinaryExpressions: { type: "boolean" }, + nestedBinaryExpressions: { type: "boolean" }, + returnAssign: { type: "boolean" }, + ignoreJSX: { enum: ["none", "all", "single-line", "multi-line"] }, + enforceForArrowConditionals: { type: "boolean" }, + enforceForSequenceExpressions: { type: "boolean" }, + enforceForNewInMemberExpressions: { type: "boolean" }, + enforceForFunctionPrototypeMethods: { type: "boolean" }, + allowParensAfterCommentPattern: { type: "string" } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + } + ] + }, + + messages: { + unexpected: "Unnecessary parentheses around expression." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + const tokensToIgnore = new WeakSet(); + const precedence = astUtils.getPrecedence; + const ALL_NODES = context.options[0] !== "functions"; + const EXCEPT_COND_ASSIGN = ALL_NODES && context.options[1] && context.options[1].conditionalAssign === false; + const EXCEPT_COND_TERNARY = ALL_NODES && context.options[1] && context.options[1].ternaryOperandBinaryExpressions === false; + const NESTED_BINARY = ALL_NODES && context.options[1] && context.options[1].nestedBinaryExpressions === false; + const EXCEPT_RETURN_ASSIGN = ALL_NODES && context.options[1] && context.options[1].returnAssign === false; + const IGNORE_JSX = ALL_NODES && context.options[1] && context.options[1].ignoreJSX; + const IGNORE_ARROW_CONDITIONALS = ALL_NODES && context.options[1] && + context.options[1].enforceForArrowConditionals === false; + const IGNORE_SEQUENCE_EXPRESSIONS = ALL_NODES && context.options[1] && + context.options[1].enforceForSequenceExpressions === false; + const IGNORE_NEW_IN_MEMBER_EXPR = ALL_NODES && context.options[1] && + context.options[1].enforceForNewInMemberExpressions === false; + const IGNORE_FUNCTION_PROTOTYPE_METHODS = ALL_NODES && context.options[1] && + context.options[1].enforceForFunctionPrototypeMethods === false; + const ALLOW_PARENS_AFTER_COMMENT_PATTERN = ALL_NODES && context.options[1] && context.options[1].allowParensAfterCommentPattern; + + const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ type: "AssignmentExpression" }); + const PRECEDENCE_OF_UPDATE_EXPR = precedence({ type: "UpdateExpression" }); + + let reportsBuffer; + + /** + * Determines whether the given node is a `call` or `apply` method call, invoked directly on a `FunctionExpression` node. + * Example: function(){}.call() + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is an immediate `call` or `apply` method call. + * @private + */ + function isImmediateFunctionPrototypeMethodCall(node) { + const callNode = astUtils.skipChainExpression(node); + + if (callNode.type !== "CallExpression") { + return false; + } + const callee = astUtils.skipChainExpression(callNode.callee); + + return ( + callee.type === "MemberExpression" && + callee.object.type === "FunctionExpression" && + ["call", "apply"].includes(astUtils.getStaticPropertyName(callee)) + ); + } + + /** + * Determines if this rule should be enforced for a node given the current configuration. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the rule should be enforced for this node. + * @private + */ + function ruleApplies(node) { + if (node.type === "JSXElement" || node.type === "JSXFragment") { + const isSingleLine = node.loc.start.line === node.loc.end.line; + + switch (IGNORE_JSX) { + + // Exclude this JSX element from linting + case "all": + return false; + + // Exclude this JSX element if it is multi-line element + case "multi-line": + return isSingleLine; + + // Exclude this JSX element if it is single-line element + case "single-line": + return !isSingleLine; + + // Nothing special to be done for JSX elements + case "none": + break; + + // no default + } + } + + if (node.type === "SequenceExpression" && IGNORE_SEQUENCE_EXPRESSIONS) { + return false; + } + + if (isImmediateFunctionPrototypeMethodCall(node) && IGNORE_FUNCTION_PROTOTYPE_METHODS) { + return false; + } + + return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression"; + } + + /** + * Determines if a node is surrounded by parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is parenthesised. + * @private + */ + function isParenthesised(node) { + return isParenthesizedRaw(1, node, sourceCode); + } + + /** + * Determines if a node is surrounded by parentheses twice. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is doubly parenthesised. + * @private + */ + function isParenthesisedTwice(node) { + return isParenthesizedRaw(2, node, sourceCode); + } + + /** + * Determines if a node is surrounded by (potentially) invalid parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is incorrectly parenthesised. + * @private + */ + function hasExcessParens(node) { + return ruleApplies(node) && isParenthesised(node); + } + + /** + * Determines if a node that is expected to be parenthesised is surrounded by + * (potentially) invalid extra parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. + * @private + */ + function hasDoubleExcessParens(node) { + return ruleApplies(node) && isParenthesisedTwice(node); + } + + /** + * Determines if a node that is expected to be parenthesised is surrounded by + * (potentially) invalid extra parentheses with considering precedence level of the node. + * If the preference level of the node is not higher or equal to precedence lower limit, it also checks + * whether the node is surrounded by parentheses twice or not. + * @param {ASTNode} node The node to be checked. + * @param {number} precedenceLowerLimit The lower limit of precedence. + * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. + * @private + */ + function hasExcessParensWithPrecedence(node, precedenceLowerLimit) { + if (ruleApplies(node) && isParenthesised(node)) { + if ( + precedence(node) >= precedenceLowerLimit || + isParenthesisedTwice(node) + ) { + return true; + } + } + return false; + } + + /** + * Determines if a node test expression is allowed to have a parenthesised assignment + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the assignment can be parenthesised. + * @private + */ + function isCondAssignException(node) { + return EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression"; + } + + /** + * Determines if a node is in a return statement + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is in a return statement. + * @private + */ + function isInReturnStatement(node) { + for (let currentNode = node; currentNode; currentNode = currentNode.parent) { + if ( + currentNode.type === "ReturnStatement" || + (currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement") + ) { + return true; + } + } + + return false; + } + + /** + * Determines if a constructor function is newed-up with parens + * @param {ASTNode} newExpression The NewExpression node to be checked. + * @returns {boolean} True if the constructor is called with parens. + * @private + */ + function isNewExpressionWithParens(newExpression) { + const lastToken = sourceCode.getLastToken(newExpression); + const penultimateToken = sourceCode.getTokenBefore(lastToken); + + return newExpression.arguments.length > 0 || + ( + + // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens + astUtils.isOpeningParenToken(penultimateToken) && + astUtils.isClosingParenToken(lastToken) && + newExpression.callee.range[1] < newExpression.range[1] + ); + } + + /** + * Determines if a node is or contains an assignment expression + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is or contains an assignment expression. + * @private + */ + function containsAssignment(node) { + if (node.type === "AssignmentExpression") { + return true; + } + if (node.type === "ConditionalExpression" && + (node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) { + return true; + } + if ((node.left && node.left.type === "AssignmentExpression") || + (node.right && node.right.type === "AssignmentExpression")) { + return true; + } + + return false; + } + + /** + * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the assignment can be parenthesised. + * @private + */ + function isReturnAssignException(node) { + if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) { + return false; + } + + if (node.type === "ReturnStatement") { + return node.argument && containsAssignment(node.argument); + } + if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") { + return containsAssignment(node.body); + } + return containsAssignment(node); + + } + + /** + * Determines if a node following a [no LineTerminator here] restriction is + * surrounded by (potentially) invalid extra parentheses. + * @param {Token} token The token preceding the [no LineTerminator here] restriction. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is incorrectly parenthesised. + * @private + */ + function hasExcessParensNoLineTerminator(token, node) { + if (token.loc.end.line === node.loc.start.line) { + return hasExcessParens(node); + } + + return hasDoubleExcessParens(node); + } + + /** + * Determines whether a node should be preceded by an additional space when removing parens + * @param {ASTNode} node node to evaluate; must be surrounded by parentheses + * @returns {boolean} `true` if a space should be inserted before the node + * @private + */ + function requiresLeadingSpace(node) { + const leftParenToken = sourceCode.getTokenBefore(node); + const tokenBeforeLeftParen = sourceCode.getTokenBefore(leftParenToken, { includeComments: true }); + const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParenToken, { includeComments: true }); + + return tokenBeforeLeftParen && + tokenBeforeLeftParen.range[1] === leftParenToken.range[0] && + leftParenToken.range[1] === tokenAfterLeftParen.range[0] && + !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, tokenAfterLeftParen); + } + + /** + * Determines whether a node should be followed by an additional space when removing parens + * @param {ASTNode} node node to evaluate; must be surrounded by parentheses + * @returns {boolean} `true` if a space should be inserted after the node + * @private + */ + function requiresTrailingSpace(node) { + const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 }); + const rightParenToken = nextTwoTokens[0]; + const tokenAfterRightParen = nextTwoTokens[1]; + const tokenBeforeRightParen = sourceCode.getLastToken(node); + + return rightParenToken && tokenAfterRightParen && + !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) && + !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen); + } + + /** + * Determines if a given expression node is an IIFE + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the given node is an IIFE + */ + function isIIFE(node) { + const maybeCallNode = astUtils.skipChainExpression(node); + + return maybeCallNode.type === "CallExpression" && maybeCallNode.callee.type === "FunctionExpression"; + } + + /** + * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment. + * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax, + * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary. + * @param {ASTNode} [node] The node to check + * @returns {boolean} `true` if the given node can be a valid assignment target + */ + function canBeAssignmentTarget(node) { + return node && (node.type === "Identifier" || node.type === "MemberExpression"); + } + + /** + * Checks if a node is fixable. + * A node is fixable if removing a single pair of surrounding parentheses does not turn it + * into a directive after fixing other nodes. + * Almost all nodes are fixable, except if all of the following conditions are met: + * The node is a string Literal + * It has a single pair of parentheses + * It is the only child of an ExpressionStatement + * @param {ASTNode} node The node to evaluate. + * @returns {boolean} Whether or not the node is fixable. + * @private + */ + function isFixable(node) { + + // if it's not a string literal it can be autofixed + if (node.type !== "Literal" || typeof node.value !== "string") { + return true; + } + if (isParenthesisedTwice(node)) { + return true; + } + return !astUtils.isTopLevelExpressionStatement(node.parent); + } + + /** + * Report the node + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function report(node) { + const leftParenToken = sourceCode.getTokenBefore(node); + const rightParenToken = sourceCode.getTokenAfter(node); + + if (!isParenthesisedTwice(node)) { + if (tokensToIgnore.has(sourceCode.getFirstToken(node))) { + return; + } + + if (isIIFE(node) && !isParenthesised(node.callee)) { + return; + } + + if (ALLOW_PARENS_AFTER_COMMENT_PATTERN) { + const commentsBeforeLeftParenToken = sourceCode.getCommentsBefore(leftParenToken); + const totalCommentsBeforeLeftParenTokenCount = commentsBeforeLeftParenToken.length; + const ignorePattern = new RegExp(ALLOW_PARENS_AFTER_COMMENT_PATTERN, "u"); + + if ( + totalCommentsBeforeLeftParenTokenCount > 0 && + ignorePattern.test(commentsBeforeLeftParenToken[totalCommentsBeforeLeftParenTokenCount - 1].value) + ) { + return; + } + } + } + + /** + * Finishes reporting + * @returns {void} + * @private + */ + function finishReport() { + context.report({ + node, + loc: leftParenToken.loc, + messageId: "unexpected", + fix: isFixable(node) + ? fixer => { + const parenthesizedSource = sourceCode.text.slice(leftParenToken.range[1], rightParenToken.range[0]); + + return fixer.replaceTextRange([ + leftParenToken.range[0], + rightParenToken.range[1] + ], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : "")); + } + : null + }); + } + + if (reportsBuffer) { + reportsBuffer.reports.push({ node, finishReport }); + return; + } + + finishReport(); + } + + /** + * Evaluate a argument of the node. + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkArgumentWithPrecedence(node) { + if (hasExcessParensWithPrecedence(node.argument, precedence(node))) { + report(node.argument); + } + } + + /** + * Check if a member expression contains a call expression + * @param {ASTNode} node MemberExpression node to evaluate + * @returns {boolean} true if found, false if not + */ + function doesMemberExpressionContainCallExpression(node) { + let currentNode = node.object; + let currentNodeType = node.object.type; + + while (currentNodeType === "MemberExpression") { + currentNode = currentNode.object; + currentNodeType = currentNode.type; + } + + return currentNodeType === "CallExpression"; + } + + /** + * Evaluate a new call + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkCallNew(node) { + const callee = node.callee; + + if (hasExcessParensWithPrecedence(callee, precedence(node))) { + if ( + hasDoubleExcessParens(callee) || + !( + isIIFE(node) || + + // (new A)(); new (new A)(); + ( + callee.type === "NewExpression" && + !isNewExpressionWithParens(callee) && + !( + node.type === "NewExpression" && + !isNewExpressionWithParens(node) + ) + ) || + + // new (a().b)(); new (a.b().c); + ( + node.type === "NewExpression" && + callee.type === "MemberExpression" && + doesMemberExpressionContainCallExpression(callee) + ) || + + // (a?.b)(); (a?.())(); + ( + !node.optional && + callee.type === "ChainExpression" + ) + ) + ) { + report(node.callee); + } + } + node.arguments + .filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR)) + .forEach(report); + } + + /** + * Evaluate binary logicals + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkBinaryLogical(node) { + const prec = precedence(node); + const leftPrecedence = precedence(node.left); + const rightPrecedence = precedence(node.right); + const isExponentiation = node.operator === "**"; + const shouldSkipLeft = NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression"); + const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression"); + + if (!shouldSkipLeft && hasExcessParens(node.left)) { + if ( + !(["AwaitExpression", "UnaryExpression"].includes(node.left.type) && isExponentiation) && + !astUtils.isMixedLogicalAndCoalesceExpressions(node.left, node) && + (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation)) || + isParenthesisedTwice(node.left) + ) { + report(node.left); + } + } + + if (!shouldSkipRight && hasExcessParens(node.right)) { + if ( + !astUtils.isMixedLogicalAndCoalesceExpressions(node.right, node) && + (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation)) || + isParenthesisedTwice(node.right) + ) { + report(node.right); + } + } + } + + /** + * Check the parentheses around the super class of the given class definition. + * @param {ASTNode} node The node of class declarations to check. + * @returns {void} + */ + function checkClass(node) { + if (!node.superClass) { + return; + } + + /* + * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. + * Otherwise, parentheses are needed. + */ + const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR + ? hasExcessParens(node.superClass) + : hasDoubleExcessParens(node.superClass); + + if (hasExtraParens) { + report(node.superClass); + } + } + + /** + * Check the parentheses around the argument of the given spread operator. + * @param {ASTNode} node The node of spread elements/properties to check. + * @returns {void} + */ + function checkSpreadOperator(node) { + if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(node.argument); + } + } + + /** + * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration + * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node + * @returns {void} + */ + function checkExpressionOrExportStatement(node) { + const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node); + const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken); + const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null; + const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null; + + if ( + astUtils.isOpeningParenToken(firstToken) && + ( + astUtils.isOpeningBraceToken(secondToken) || + secondToken.type === "Keyword" && ( + secondToken.value === "function" || + secondToken.value === "class" || + secondToken.value === "let" && + tokenAfterClosingParens && + ( + astUtils.isOpeningBracketToken(tokenAfterClosingParens) || + tokenAfterClosingParens.type === "Identifier" + ) + ) || + secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function" + ) + ) { + tokensToIgnore.add(secondToken); + } + + const hasExtraParens = node.parent.type === "ExportDefaultDeclaration" + ? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR) + : hasExcessParens(node); + + if (hasExtraParens) { + report(node); + } + } + + /** + * Finds the path from the given node to the specified ancestor. + * @param {ASTNode} node First node in the path. + * @param {ASTNode} ancestor Last node in the path. + * @returns {ASTNode[]} Path, including both nodes. + * @throws {Error} If the given node does not have the specified ancestor. + */ + function pathToAncestor(node, ancestor) { + const path = [node]; + let currentNode = node; + + while (currentNode !== ancestor) { + + currentNode = currentNode.parent; + + /* c8 ignore start */ + if (currentNode === null) { + throw new Error("Nodes are not in the ancestor-descendant relationship."); + }/* c8 ignore stop */ + + path.push(currentNode); + } + + return path; + } + + /** + * Finds the path from the given node to the specified descendant. + * @param {ASTNode} node First node in the path. + * @param {ASTNode} descendant Last node in the path. + * @returns {ASTNode[]} Path, including both nodes. + * @throws {Error} If the given node does not have the specified descendant. + */ + function pathToDescendant(node, descendant) { + return pathToAncestor(descendant, node).reverse(); + } + + /** + * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer + * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop. + * @param {ASTNode} node Ancestor of an 'in' expression. + * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself. + * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis. + */ + function isSafelyEnclosingInExpression(node, child) { + switch (node.type) { + case "ArrayExpression": + case "ArrayPattern": + case "BlockStatement": + case "ObjectExpression": + case "ObjectPattern": + case "TemplateLiteral": + return true; + case "ArrowFunctionExpression": + case "FunctionExpression": + return node.params.includes(child); + case "CallExpression": + case "NewExpression": + return node.arguments.includes(child); + case "MemberExpression": + return node.computed && node.property === child; + case "ConditionalExpression": + return node.consequent === child; + default: + return false; + } + } + + /** + * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately. + * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings. + * @returns {void} + */ + function startNewReportsBuffering() { + reportsBuffer = { + upper: reportsBuffer, + inExpressionNodes: [], + reports: [] + }; + } + + /** + * Ends the current reports buffering. + * @returns {void} + */ + function endCurrentReportsBuffering() { + const { upper, inExpressionNodes, reports } = reportsBuffer; + + if (upper) { + upper.inExpressionNodes.push(...inExpressionNodes); + upper.reports.push(...reports); + } else { + + // flush remaining reports + reports.forEach(({ finishReport }) => finishReport()); + } + + reportsBuffer = upper; + } + + /** + * Checks whether the given node is in the current reports buffer. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is in the current buffer, false otherwise. + */ + function isInCurrentReportsBuffer(node) { + return reportsBuffer.reports.some(r => r.node === node); + } + + /** + * Removes the given node from the current reports buffer. + * @param {ASTNode} node Node to remove. + * @returns {void} + */ + function removeFromCurrentReportsBuffer(node) { + reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node); + } + + /** + * Checks whether a node is a MemberExpression at NewExpression's callee. + * @param {ASTNode} node node to check. + * @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise. + */ + function isMemberExpInNewCallee(node) { + if (node.type === "MemberExpression") { + return node.parent.type === "NewExpression" && node.parent.callee === node + ? true + : node.parent.object === node && isMemberExpInNewCallee(node.parent); + } + return false; + } + + /** + * Checks if the left-hand side of an assignment is an identifier, the operator is one of + * `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous class or function. + * + * As per https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation, an + * assignment involving one of the operators `=`, `&&=`, `||=` or `??=` where the right-hand + * side is an anonymous class or function and the left-hand side is an *unparenthesized* + * identifier has different semantics than other assignments. + * Specifically, when an expression like `foo = function () {}` is evaluated, `foo.name` + * will be set to the string "foo", i.e. the identifier name. The same thing does not happen + * when evaluating `(foo) = function () {}`. + * Since the parenthesizing of the identifier in the left-hand side is significant in this + * special case, the parentheses, if present, should not be flagged as unnecessary. + * @param {ASTNode} node an AssignmentExpression node. + * @returns {boolean} `true` if the left-hand side of the assignment is an identifier, the + * operator is one of `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous + * class or function; otherwise, `false`. + */ + function isAnonymousFunctionAssignmentException({ left, operator, right }) { + if (left.type === "Identifier" && ["=", "&&=", "||=", "??="].includes(operator)) { + const rhsType = right.type; + + if (rhsType === "ArrowFunctionExpression") { + return true; + } + if ((rhsType === "FunctionExpression" || rhsType === "ClassExpression") && !right.id) { + return true; + } + } + return false; + } + + return { + ArrayExpression(node) { + node.elements + .filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR)) + .forEach(report); + }, + + ArrayPattern(node) { + node.elements + .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e)) + .forEach(report); + }, + + ArrowFunctionExpression(node) { + if (isReturnAssignException(node)) { + return; + } + + if (node.body.type === "ConditionalExpression" && + IGNORE_ARROW_CONDITIONALS + ) { + return; + } + + if (node.body.type !== "BlockStatement") { + const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken); + const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken); + + if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) { + tokensToIgnore.add(firstBodyToken); + } + if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(node.body); + } + } + }, + + AssignmentExpression(node) { + if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left) && + (!isAnonymousFunctionAssignmentException(node) || isParenthesisedTwice(node.left))) { + report(node.left); + } + + if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) { + report(node.right); + } + }, + + BinaryExpression(node) { + if (reportsBuffer && node.operator === "in") { + reportsBuffer.inExpressionNodes.push(node); + } + + checkBinaryLogical(node); + }, + + CallExpression: checkCallNew, + + ConditionalExpression(node) { + if (isReturnAssignException(node)) { + return; + } + + const availableTypes = new Set(["BinaryExpression", "LogicalExpression"]); + + if ( + !(EXCEPT_COND_TERNARY && availableTypes.has(node.test.type)) && + !isCondAssignException(node) && + hasExcessParensWithPrecedence(node.test, precedence({ type: "LogicalExpression", operator: "||" })) + ) { + report(node.test); + } + + if ( + !(EXCEPT_COND_TERNARY && availableTypes.has(node.consequent.type)) && + hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(node.consequent); + } + + if ( + !(EXCEPT_COND_TERNARY && availableTypes.has(node.alternate.type)) && + hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(node.alternate); + } + }, + + DoWhileStatement(node) { + if (hasExcessParens(node.test) && !isCondAssignException(node)) { + report(node.test); + } + }, + + ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration), + ExpressionStatement: node => checkExpressionOrExportStatement(node.expression), + + ForInStatement(node) { + if (node.left.type !== "VariableDeclaration") { + const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken); + + if ( + firstLeftToken.value === "let" && + astUtils.isOpeningBracketToken( + sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken) + ) + ) { + + // ForInStatement#left expression cannot start with `let[`. + tokensToIgnore.add(firstLeftToken); + } + } + + if (hasExcessParens(node.left)) { + report(node.left); + } + + if (hasExcessParens(node.right)) { + report(node.right); + } + }, + + ForOfStatement(node) { + if (node.left.type !== "VariableDeclaration") { + const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken); + + if (firstLeftToken.value === "let") { + + // ForOfStatement#left expression cannot start with `let`. + tokensToIgnore.add(firstLeftToken); + } + } + + if (hasExcessParens(node.left)) { + report(node.left); + } + + if (hasExcessParensWithPrecedence(node.right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(node.right); + } + }, + + ForStatement(node) { + if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) { + report(node.test); + } + + if (node.update && hasExcessParens(node.update)) { + report(node.update); + } + + if (node.init) { + + if (node.init.type !== "VariableDeclaration") { + const firstToken = sourceCode.getFirstToken(node.init, astUtils.isNotOpeningParenToken); + + if ( + firstToken.value === "let" && + astUtils.isOpeningBracketToken( + sourceCode.getTokenAfter(firstToken, astUtils.isNotClosingParenToken) + ) + ) { + + // ForStatement#init expression cannot start with `let[`. + tokensToIgnore.add(firstToken); + } + } + + startNewReportsBuffering(); + + if (hasExcessParens(node.init)) { + report(node.init); + } + } + }, + + "ForStatement > *.init:exit"(node) { + + /* + * Removing parentheses around `in` expressions might change semantics and cause errors. + * + * For example, this valid for loop: + * for (let a = (b in c); ;); + * after removing parentheses would be treated as an invalid for-in loop: + * for (let a = b in c; ;); + */ + + if (reportsBuffer.reports.length) { + reportsBuffer.inExpressionNodes.forEach(inExpressionNode => { + const path = pathToDescendant(node, inExpressionNode); + let nodeToExclude; + + for (let i = 0; i < path.length; i++) { + const pathNode = path[i]; + + if (i < path.length - 1) { + const nextPathNode = path[i + 1]; + + if (isSafelyEnclosingInExpression(pathNode, nextPathNode)) { + + // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]'). + return; + } + } + + if (isParenthesised(pathNode)) { + if (isInCurrentReportsBuffer(pathNode)) { + + // This node was supposed to be reported, but parentheses might be necessary. + + if (isParenthesisedTwice(pathNode)) { + + /* + * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses. + * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses. + * The remaining pair is safely enclosing the 'in' expression. + */ + return; + } + + // Exclude the outermost node only. + if (!nodeToExclude) { + nodeToExclude = pathNode; + } + + // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside. + + } else { + + // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'. + return; + } + } + } + + // Exclude the node from the list (i.e. treat parentheses as necessary) + removeFromCurrentReportsBuffer(nodeToExclude); + }); + } + + endCurrentReportsBuffering(); + }, + + IfStatement(node) { + if (hasExcessParens(node.test) && !isCondAssignException(node)) { + report(node.test); + } + }, + + ImportExpression(node) { + const { source } = node; + + if (source.type === "SequenceExpression") { + if (hasDoubleExcessParens(source)) { + report(source); + } + } else if (hasExcessParens(source)) { + report(source); + } + }, + + LogicalExpression: checkBinaryLogical, + + MemberExpression(node) { + const shouldAllowWrapOnce = isMemberExpInNewCallee(node) && + doesMemberExpressionContainCallExpression(node); + const nodeObjHasExcessParens = shouldAllowWrapOnce + ? hasDoubleExcessParens(node.object) + : hasExcessParens(node.object) && + !( + isImmediateFunctionPrototypeMethodCall(node.parent) && + node.parent.callee === node && + IGNORE_FUNCTION_PROTOTYPE_METHODS + ); + + if ( + nodeObjHasExcessParens && + precedence(node.object) >= precedence(node) && + ( + node.computed || + !( + astUtils.isDecimalInteger(node.object) || + + // RegExp literal is allowed to have parens (#1589) + (node.object.type === "Literal" && node.object.regex) + ) + ) + ) { + report(node.object); + } + + if (nodeObjHasExcessParens && + node.object.type === "CallExpression" + ) { + report(node.object); + } + + if (nodeObjHasExcessParens && + !IGNORE_NEW_IN_MEMBER_EXPR && + node.object.type === "NewExpression" && + isNewExpressionWithParens(node.object)) { + report(node.object); + } + + if (nodeObjHasExcessParens && + node.optional && + node.object.type === "ChainExpression" + ) { + report(node.object); + } + + if (node.computed && hasExcessParens(node.property)) { + report(node.property); + } + }, + + "MethodDefinition[computed=true]"(node) { + if (hasExcessParensWithPrecedence(node.key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(node.key); + } + }, + + NewExpression: checkCallNew, + + ObjectExpression(node) { + node.properties + .filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR)) + .forEach(property => report(property.value)); + }, + + ObjectPattern(node) { + node.properties + .filter(property => { + const value = property.value; + + return canBeAssignmentTarget(value) && hasExcessParens(value); + }).forEach(property => report(property.value)); + }, + + Property(node) { + if (node.computed) { + const { key } = node; + + if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(key); + } + } + }, + + PropertyDefinition(node) { + if (node.computed && hasExcessParensWithPrecedence(node.key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(node.key); + } + + if (node.value && hasExcessParensWithPrecedence(node.value, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(node.value); + } + }, + + RestElement(node) { + const argument = node.argument; + + if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) { + report(argument); + } + }, + + ReturnStatement(node) { + const returnToken = sourceCode.getFirstToken(node); + + if (isReturnAssignException(node)) { + return; + } + + if (node.argument && + hasExcessParensNoLineTerminator(returnToken, node.argument) && + + // RegExp literal is allowed to have parens (#1589) + !(node.argument.type === "Literal" && node.argument.regex)) { + report(node.argument); + } + }, + + SequenceExpression(node) { + const precedenceOfNode = precedence(node); + + node.expressions + .filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode)) + .forEach(report); + }, + + SwitchCase(node) { + if (node.test && hasExcessParens(node.test)) { + report(node.test); + } + }, + + SwitchStatement(node) { + if (hasExcessParens(node.discriminant)) { + report(node.discriminant); + } + }, + + ThrowStatement(node) { + const throwToken = sourceCode.getFirstToken(node); + + if (hasExcessParensNoLineTerminator(throwToken, node.argument)) { + report(node.argument); + } + }, + + UnaryExpression: checkArgumentWithPrecedence, + UpdateExpression(node) { + if (node.prefix) { + checkArgumentWithPrecedence(node); + } else { + const { argument } = node; + const operatorToken = sourceCode.getLastToken(node); + + if (argument.loc.end.line === operatorToken.loc.start.line) { + checkArgumentWithPrecedence(node); + } else { + if (hasDoubleExcessParens(argument)) { + report(argument); + } + } + } + }, + AwaitExpression: checkArgumentWithPrecedence, + + VariableDeclarator(node) { + if ( + node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) && + + // RegExp literal is allowed to have parens (#1589) + !(node.init.type === "Literal" && node.init.regex) + ) { + report(node.init); + } + }, + + WhileStatement(node) { + if (hasExcessParens(node.test) && !isCondAssignException(node)) { + report(node.test); + } + }, + + WithStatement(node) { + if (hasExcessParens(node.object)) { + report(node.object); + } + }, + + YieldExpression(node) { + if (node.argument) { + const yieldToken = sourceCode.getFirstToken(node); + + if ((precedence(node.argument) >= precedence(node) && + hasExcessParensNoLineTerminator(yieldToken, node.argument)) || + hasDoubleExcessParens(node.argument)) { + report(node.argument); + } + } + }, + + ClassDeclaration: checkClass, + ClassExpression: checkClass, + + SpreadElement: checkSpreadOperator, + SpreadProperty: checkSpreadOperator, + ExperimentalSpreadProperty: checkSpreadOperator, + + TemplateLiteral(node) { + node.expressions + .filter(e => e && hasExcessParens(e)) + .forEach(report); + }, + + AssignmentPattern(node) { + const { left, right } = node; + + if (canBeAssignmentTarget(left) && hasExcessParens(left)) { + report(left); + } + + if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { + report(right); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-extra-semi.js b/node_modules/eslint/lib/rules/no-extra-semi.js new file mode 100644 index 0000000..3473df1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-semi.js @@ -0,0 +1,144 @@ +/** + * @fileoverview Rule to flag use of unnecessary semicolons + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary semicolons", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-extra-semi" + }, + + fixable: "code", + schema: [], + + messages: { + unexpected: "Unnecessary semicolon." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks if a node or token is fixable. + * A node is fixable if it can be removed without turning a subsequent statement into a directive after fixing other nodes. + * @param {Token} nodeOrToken The node or token to check. + * @returns {boolean} Whether or not the node is fixable. + */ + function isFixable(nodeOrToken) { + const nextToken = sourceCode.getTokenAfter(nodeOrToken); + + if (!nextToken || nextToken.type !== "String") { + return true; + } + const stringNode = sourceCode.getNodeByRangeIndex(nextToken.range[0]); + + return !astUtils.isTopLevelExpressionStatement(stringNode.parent); + } + + /** + * Reports an unnecessary semicolon error. + * @param {Node|Token} nodeOrToken A node or a token to be reported. + * @returns {void} + */ + function report(nodeOrToken) { + context.report({ + node: nodeOrToken, + messageId: "unexpected", + fix: isFixable(nodeOrToken) + ? fixer => + + /* + * Expand the replacement range to include the surrounding + * tokens to avoid conflicting with semi. + * https://github.com/eslint/eslint/issues/7928 + */ + new FixTracker(fixer, context.sourceCode) + .retainSurroundingTokens(nodeOrToken) + .remove(nodeOrToken) + : null + }); + } + + /** + * Checks for a part of a class body. + * This checks tokens from a specified token to a next MethodDefinition or the end of class body. + * @param {Token} firstToken The first token to check. + * @returns {void} + */ + function checkForPartOfClassBody(firstToken) { + for (let token = firstToken; + token.type === "Punctuator" && !astUtils.isClosingBraceToken(token); + token = sourceCode.getTokenAfter(token) + ) { + if (astUtils.isSemicolonToken(token)) { + report(token); + } + } + } + + return { + + /** + * Reports this empty statement, except if the parent node is a loop. + * @param {Node} node A EmptyStatement node to be reported. + * @returns {void} + */ + EmptyStatement(node) { + const parent = node.parent, + allowedParentTypes = [ + "ForStatement", + "ForInStatement", + "ForOfStatement", + "WhileStatement", + "DoWhileStatement", + "IfStatement", + "LabeledStatement", + "WithStatement" + ]; + + if (!allowedParentTypes.includes(parent.type)) { + report(node); + } + }, + + /** + * Checks tokens from the head of this class body to the first MethodDefinition or the end of this class body. + * @param {Node} node A ClassBody node to check. + * @returns {void} + */ + ClassBody(node) { + checkForPartOfClassBody(sourceCode.getFirstToken(node, 1)); // 0 is `{`. + }, + + /** + * Checks tokens from this MethodDefinition to the next MethodDefinition or the end of this class body. + * @param {Node} node A MethodDefinition node of the start point. + * @returns {void} + */ + "MethodDefinition, PropertyDefinition, StaticBlock"(node) { + checkForPartOfClassBody(sourceCode.getTokenAfter(node)); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-fallthrough.js b/node_modules/eslint/lib/rules/no-fallthrough.js new file mode 100644 index 0000000..bd2ee9b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-fallthrough.js @@ -0,0 +1,168 @@ +/** + * @fileoverview Rule to flag fall-through cases in switch statements. + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { directivesPattern } = require("../shared/directives"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu; + +/** + * Checks whether or not a given comment string is really a fallthrough comment and not an ESLint directive. + * @param {string} comment The comment string to check. + * @param {RegExp} fallthroughCommentPattern The regular expression used for checking for fallthrough comments. + * @returns {boolean} `true` if the comment string is truly a fallthrough comment. + */ +function isFallThroughComment(comment, fallthroughCommentPattern) { + return fallthroughCommentPattern.test(comment) && !directivesPattern.test(comment.trim()); +} + +/** + * Checks whether or not a given case has a fallthrough comment. + * @param {ASTNode} caseWhichFallsThrough SwitchCase node which falls through. + * @param {ASTNode} subsequentCase The case after caseWhichFallsThrough. + * @param {RuleContext} context A rule context which stores comments. + * @param {RegExp} fallthroughCommentPattern A pattern to match comment to. + * @returns {boolean} `true` if the case has a valid fallthrough comment. + */ +function hasFallthroughComment(caseWhichFallsThrough, subsequentCase, context, fallthroughCommentPattern) { + const sourceCode = context.sourceCode; + + if (caseWhichFallsThrough.consequent.length === 1 && caseWhichFallsThrough.consequent[0].type === "BlockStatement") { + const trailingCloseBrace = sourceCode.getLastToken(caseWhichFallsThrough.consequent[0]); + const commentInBlock = sourceCode.getCommentsBefore(trailingCloseBrace).pop(); + + if (commentInBlock && isFallThroughComment(commentInBlock.value, fallthroughCommentPattern)) { + return true; + } + } + + const comment = sourceCode.getCommentsBefore(subsequentCase).pop(); + + return Boolean(comment && isFallThroughComment(comment.value, fallthroughCommentPattern)); +} + +/** + * Checks whether or not a given code path segment is reachable. + * @param {CodePathSegment} segment A CodePathSegment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +/** + * Checks whether a node and a token are separated by blank lines + * @param {ASTNode} node The node to check + * @param {Token} token The token to compare against + * @returns {boolean} `true` if there are blank lines between node and token + */ +function hasBlankLinesBetween(node, token) { + return token.loc.start.line > node.loc.end.line + 1; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow fallthrough of `case` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-fallthrough" + }, + + schema: [ + { + type: "object", + properties: { + commentPattern: { + type: "string", + default: "" + }, + allowEmptyCase: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + messages: { + case: "Expected a 'break' statement before 'case'.", + default: "Expected a 'break' statement before 'default'." + } + }, + + create(context) { + const options = context.options[0] || {}; + let currentCodePath = null; + const sourceCode = context.sourceCode; + const allowEmptyCase = options.allowEmptyCase || false; + + /* + * We need to use leading comments of the next SwitchCase node because + * trailing comments is wrong if semicolons are omitted. + */ + let fallthroughCase = null; + let fallthroughCommentPattern = null; + + if (options.commentPattern) { + fallthroughCommentPattern = new RegExp(options.commentPattern, "u"); + } else { + fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT; + } + return { + onCodePathStart(codePath) { + currentCodePath = codePath; + }, + onCodePathEnd() { + currentCodePath = currentCodePath.upper; + }, + + SwitchCase(node) { + + /* + * Checks whether or not there is a fallthrough comment. + * And reports the previous fallthrough node if that does not exist. + */ + + if (fallthroughCase && (!hasFallthroughComment(fallthroughCase, node, context, fallthroughCommentPattern))) { + context.report({ + messageId: node.test ? "case" : "default", + node + }); + } + fallthroughCase = null; + }, + + "SwitchCase:exit"(node) { + const nextToken = sourceCode.getTokenAfter(node); + + /* + * `reachable` meant fall through because statements preceded by + * `break`, `return`, or `throw` are unreachable. + * And allows empty cases and the last case. + */ + if (currentCodePath.currentSegments.some(isReachable) && + (node.consequent.length > 0 || (!allowEmptyCase && hasBlankLinesBetween(node, nextToken))) && + node.parent.cases[node.parent.cases.length - 1] !== node) { + fallthroughCase = node; + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-floating-decimal.js b/node_modules/eslint/lib/rules/no-floating-decimal.js new file mode 100644 index 0000000..c268764 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-floating-decimal.js @@ -0,0 +1,70 @@ +/** + * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow leading or trailing decimal points in numeric literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-floating-decimal" + }, + + schema: [], + fixable: "code", + messages: { + leading: "A leading decimal point can be confused with a dot.", + trailing: "A trailing decimal point can be confused with a dot." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Literal(node) { + + if (typeof node.value === "number") { + if (node.raw.startsWith(".")) { + context.report({ + node, + messageId: "leading", + fix(fixer) { + const tokenBefore = sourceCode.getTokenBefore(node); + const needsSpaceBefore = tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, `0${node.raw}`); + + return fixer.insertTextBefore(node, needsSpaceBefore ? " 0" : "0"); + } + }); + } + if (node.raw.indexOf(".") === node.raw.length - 1) { + context.report({ + node, + messageId: "trailing", + fix: fixer => fixer.insertTextAfter(node, "0") + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-func-assign.js b/node_modules/eslint/lib/rules/no-func-assign.js new file mode 100644 index 0000000..8084af6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-func-assign.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Rule to flag use of function declaration identifiers as variables. + * @author Ian Christian Myers + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning `function` declarations", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-func-assign" + }, + + schema: [], + + messages: { + isAFunction: "'{{name}}' is a function." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Reports a reference if is non initializer and writable. + * @param {References} references Collection of reference to check. + * @returns {void} + */ + function checkReference(references) { + astUtils.getModifyingReferences(references).forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "isAFunction", + data: { + name: reference.identifier.name + } + }); + }); + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if (variable.defs[0].type === "FunctionName") { + checkReference(variable.references); + } + } + + /** + * Checks parameters of a given function node. + * @param {ASTNode} node A function node to check. + * @returns {void} + */ + function checkForFunction(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + FunctionDeclaration: checkForFunction, + FunctionExpression: checkForFunction + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-global-assign.js b/node_modules/eslint/lib/rules/no-global-assign.js new file mode 100644 index 0000000..99ae7a2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-global-assign.js @@ -0,0 +1,95 @@ +/** + * @fileoverview Rule to disallow assignments to native objects or read-only global variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow assignments to native objects or read-only global variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-global-assign" + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { type: "string" }, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + globalShouldNotBeModified: "Read-only global '{{name}}' should not be modified." + } + }, + + create(context) { + const config = context.options[0]; + const sourceCode = context.sourceCode; + const exceptions = (config && config.exceptions) || []; + + /** + * Reports write references. + * @param {Reference} reference A reference to check. + * @param {int} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if (reference.init === false && + reference.isWrite() && + + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + context.report({ + node: identifier, + messageId: "globalShouldNotBeModified", + data: { + name: identifier.name + } + }); + } + } + + /** + * Reports write references if a given variable is read-only builtin. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if (variable.writeable === false && !exceptions.includes(variable.name)) { + variable.references.forEach(checkReference); + } + } + + return { + Program(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.variables.forEach(checkVariable); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-implicit-coercion.js b/node_modules/eslint/lib/rules/no-implicit-coercion.js new file mode 100644 index 0000000..36baad3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implicit-coercion.js @@ -0,0 +1,380 @@ +/** + * @fileoverview A rule to disallow the type conversions with shorter notations. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/u; +const ALLOWABLE_OPERATORS = ["~", "!!", "+", "*"]; + +/** + * Parses and normalizes an option object. + * @param {Object} options An option object to parse. + * @returns {Object} The parsed and normalized option object. + */ +function parseOptions(options) { + return { + boolean: "boolean" in options ? options.boolean : true, + number: "number" in options ? options.number : true, + string: "string" in options ? options.string : true, + disallowTemplateShorthand: "disallowTemplateShorthand" in options ? options.disallowTemplateShorthand : false, + allow: options.allow || [] + }; +} + +/** + * Checks whether or not a node is a double logical negating. + * @param {ASTNode} node An UnaryExpression node to check. + * @returns {boolean} Whether or not the node is a double logical negating. + */ +function isDoubleLogicalNegating(node) { + return ( + node.operator === "!" && + node.argument.type === "UnaryExpression" && + node.argument.operator === "!" + ); +} + +/** + * Checks whether or not a node is a binary negating of `.indexOf()` method calling. + * @param {ASTNode} node An UnaryExpression node to check. + * @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling. + */ +function isBinaryNegatingOfIndexOf(node) { + if (node.operator !== "~") { + return false; + } + const callNode = astUtils.skipChainExpression(node.argument); + + return ( + callNode.type === "CallExpression" && + astUtils.isSpecificMemberAccess(callNode.callee, null, INDEX_OF_PATTERN) + ); +} + +/** + * Checks whether or not a node is a multiplying by one. + * @param {BinaryExpression} node A BinaryExpression node to check. + * @returns {boolean} Whether or not the node is a multiplying by one. + */ +function isMultiplyByOne(node) { + return node.operator === "*" && ( + node.left.type === "Literal" && node.left.value === 1 || + node.right.type === "Literal" && node.right.value === 1 + ); +} + +/** + * Checks whether the given node logically represents multiplication by a fraction of `1`. + * For example, `a * 1` in `a * 1 / b` is technically multiplication by `1`, but the + * whole expression can be logically interpreted as `a * (1 / b)` rather than `(a * 1) / b`. + * @param {BinaryExpression} node A BinaryExpression node to check. + * @param {SourceCode} sourceCode The source code object. + * @returns {boolean} Whether or not the node is a multiplying by a fraction of `1`. + */ +function isMultiplyByFractionOfOne(node, sourceCode) { + return node.type === "BinaryExpression" && + node.operator === "*" && + (node.right.type === "Literal" && node.right.value === 1) && + node.parent.type === "BinaryExpression" && + node.parent.operator === "/" && + node.parent.left === node && + !astUtils.isParenthesised(sourceCode, node); +} + +/** + * Checks whether the result of a node is numeric or not + * @param {ASTNode} node The node to test + * @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call + */ +function isNumeric(node) { + return ( + node.type === "Literal" && typeof node.value === "number" || + node.type === "CallExpression" && ( + node.callee.name === "Number" || + node.callee.name === "parseInt" || + node.callee.name === "parseFloat" + ) + ); +} + +/** + * Returns the first non-numeric operand in a BinaryExpression. Designed to be + * used from bottom to up since it walks up the BinaryExpression trees using + * node.parent to find the result. + * @param {BinaryExpression} node The BinaryExpression node to be walked up on + * @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null + */ +function getNonNumericOperand(node) { + const left = node.left, + right = node.right; + + if (right.type !== "BinaryExpression" && !isNumeric(right)) { + return right; + } + + if (left.type !== "BinaryExpression" && !isNumeric(left)) { + return left; + } + + return null; +} + +/** + * Checks whether an expression evaluates to a string. + * @param {ASTNode} node node that represents the expression to check. + * @returns {boolean} Whether or not the expression evaluates to a string. + */ +function isStringType(node) { + return astUtils.isStringLiteral(node) || + ( + node.type === "CallExpression" && + node.callee.type === "Identifier" && + node.callee.name === "String" + ); +} + +/** + * Checks whether a node is an empty string literal or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the passed in node is an + * empty string literal or not. + */ +function isEmptyString(node) { + return astUtils.isStringLiteral(node) && (node.value === "" || (node.type === "TemplateLiteral" && node.quasis.length === 1 && node.quasis[0].value.cooked === "")); +} + +/** + * Checks whether or not a node is a concatenating with an empty string. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {boolean} Whether or not the node is a concatenating with an empty string. + */ +function isConcatWithEmptyString(node) { + return node.operator === "+" && ( + (isEmptyString(node.left) && !isStringType(node.right)) || + (isEmptyString(node.right) && !isStringType(node.left)) + ); +} + +/** + * Checks whether or not a node is appended with an empty string. + * @param {ASTNode} node An AssignmentExpression node to check. + * @returns {boolean} Whether or not the node is appended with an empty string. + */ +function isAppendEmptyString(node) { + return node.operator === "+=" && isEmptyString(node.right); +} + +/** + * Returns the operand that is not an empty string from a flagged BinaryExpression. + * @param {ASTNode} node The flagged BinaryExpression node to check. + * @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression. + */ +function getNonEmptyOperand(node) { + return isEmptyString(node.left) ? node.right : node.left; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow shorthand type conversions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-implicit-coercion" + }, + + fixable: "code", + + schema: [{ + type: "object", + properties: { + boolean: { + type: "boolean", + default: true + }, + number: { + type: "boolean", + default: true + }, + string: { + type: "boolean", + default: true + }, + disallowTemplateShorthand: { + type: "boolean", + default: false + }, + allow: { + type: "array", + items: { + enum: ALLOWABLE_OPERATORS + }, + uniqueItems: true + } + }, + additionalProperties: false + }], + + messages: { + useRecommendation: "use `{{recommendation}}` instead." + } + }, + + create(context) { + const options = parseOptions(context.options[0] || {}); + const sourceCode = context.sourceCode; + + /** + * Reports an error and autofixes the node + * @param {ASTNode} node An ast node to report the error on. + * @param {string} recommendation The recommended code for the issue + * @param {bool} shouldFix Whether this report should fix the node + * @returns {void} + */ + function report(node, recommendation, shouldFix) { + context.report({ + node, + messageId: "useRecommendation", + data: { + recommendation + }, + fix(fixer) { + if (!shouldFix) { + return null; + } + + const tokenBefore = sourceCode.getTokenBefore(node); + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, recommendation) + ) { + return fixer.replaceText(node, ` ${recommendation}`); + } + return fixer.replaceText(node, recommendation); + } + }); + } + + return { + UnaryExpression(node) { + let operatorAllowed; + + // !!foo + operatorAllowed = options.allow.includes("!!"); + if (!operatorAllowed && options.boolean && isDoubleLogicalNegating(node)) { + const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`; + + report(node, recommendation, true); + } + + // ~foo.indexOf(bar) + operatorAllowed = options.allow.includes("~"); + if (!operatorAllowed && options.boolean && isBinaryNegatingOfIndexOf(node)) { + + // `foo?.indexOf(bar) !== -1` will be true (== found) if the `foo` is nullish. So use `>= 0` in that case. + const comparison = node.argument.type === "ChainExpression" ? ">= 0" : "!== -1"; + const recommendation = `${sourceCode.getText(node.argument)} ${comparison}`; + + report(node, recommendation, false); + } + + // +foo + operatorAllowed = options.allow.includes("+"); + if (!operatorAllowed && options.number && node.operator === "+" && !isNumeric(node.argument)) { + const recommendation = `Number(${sourceCode.getText(node.argument)})`; + + report(node, recommendation, true); + } + }, + + // Use `:exit` to prevent double reporting + "BinaryExpression:exit"(node) { + let operatorAllowed; + + // 1 * foo + operatorAllowed = options.allow.includes("*"); + const nonNumericOperand = !operatorAllowed && options.number && isMultiplyByOne(node) && !isMultiplyByFractionOfOne(node, sourceCode) && + getNonNumericOperand(node); + + if (nonNumericOperand) { + const recommendation = `Number(${sourceCode.getText(nonNumericOperand)})`; + + report(node, recommendation, true); + } + + // "" + foo + operatorAllowed = options.allow.includes("+"); + if (!operatorAllowed && options.string && isConcatWithEmptyString(node)) { + const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`; + + report(node, recommendation, true); + } + }, + + AssignmentExpression(node) { + + // foo += "" + const operatorAllowed = options.allow.includes("+"); + + if (!operatorAllowed && options.string && isAppendEmptyString(node)) { + const code = sourceCode.getText(getNonEmptyOperand(node)); + const recommendation = `${code} = String(${code})`; + + report(node, recommendation, true); + } + }, + + TemplateLiteral(node) { + if (!options.disallowTemplateShorthand) { + return; + } + + // tag`${foo}` + if (node.parent.type === "TaggedTemplateExpression") { + return; + } + + // `` or `${foo}${bar}` + if (node.expressions.length !== 1) { + return; + } + + + // `prefix${foo}` + if (node.quasis[0].value.cooked !== "") { + return; + } + + // `${foo}postfix` + if (node.quasis[1].value.cooked !== "") { + return; + } + + // if the expression is already a string, then this isn't a coercion + if (isStringType(node.expressions[0])) { + return; + } + + const code = sourceCode.getText(node.expressions[0]); + const recommendation = `String(${code})`; + + report(node, recommendation, true); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-implicit-globals.js b/node_modules/eslint/lib/rules/no-implicit-globals.js new file mode 100644 index 0000000..2a18247 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implicit-globals.js @@ -0,0 +1,146 @@ +/** + * @fileoverview Rule to check for implicit global variables, functions and classes. + * @author Joshua Peek + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow declarations in the global scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-implicit-globals" + }, + + schema: [{ + type: "object", + properties: { + lexicalBindings: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + + messages: { + globalNonLexicalBinding: "Unexpected {{kind}} declaration in the global scope, wrap in an IIFE for a local variable, assign as global property for a global variable.", + globalLexicalBinding: "Unexpected {{kind}} declaration in the global scope, wrap in a block or in an IIFE.", + globalVariableLeak: "Global variable leak, declare the variable if it is intended to be local.", + assignmentToReadonlyGlobal: "Unexpected assignment to read-only global variable.", + redeclarationOfReadonlyGlobal: "Unexpected redeclaration of read-only global variable." + } + }, + + create(context) { + + const checkLexicalBindings = context.options[0] && context.options[0].lexicalBindings === true; + const sourceCode = context.sourceCode; + + /** + * Reports the node. + * @param {ASTNode} node Node to report. + * @param {string} messageId Id of the message to report. + * @param {string|undefined} kind Declaration kind, can be 'var', 'const', 'let', function or class. + * @returns {void} + */ + function report(node, messageId, kind) { + context.report({ + node, + messageId, + data: { + kind + } + }); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + scope.variables.forEach(variable => { + + // Only ESLint global variables have the `writable` key. + const isReadonlyEslintGlobalVariable = variable.writeable === false; + const isWritableEslintGlobalVariable = variable.writeable === true; + + if (isWritableEslintGlobalVariable) { + + // Everything is allowed with writable ESLint global variables. + return; + } + + // Variables exported by "exported" block comments + if (variable.eslintExported) { + return; + } + + variable.defs.forEach(def => { + const defNode = def.node; + + if (def.type === "FunctionName" || (def.type === "Variable" && def.parent.kind === "var")) { + if (isReadonlyEslintGlobalVariable) { + report(defNode, "redeclarationOfReadonlyGlobal"); + } else { + report( + defNode, + "globalNonLexicalBinding", + def.type === "FunctionName" ? "function" : `'${def.parent.kind}'` + ); + } + } + + if (checkLexicalBindings) { + if (def.type === "ClassName" || + (def.type === "Variable" && (def.parent.kind === "let" || def.parent.kind === "const"))) { + if (isReadonlyEslintGlobalVariable) { + report(defNode, "redeclarationOfReadonlyGlobal"); + } else { + report( + defNode, + "globalLexicalBinding", + def.type === "ClassName" ? "class" : `'${def.parent.kind}'` + ); + } + } + } + }); + }); + + // Undeclared assigned variables. + scope.implicit.variables.forEach(variable => { + const scopeVariable = scope.set.get(variable.name); + let messageId; + + if (scopeVariable) { + + // ESLint global variable + if (scopeVariable.writeable) { + return; + } + messageId = "assignmentToReadonlyGlobal"; + + } else { + + // Reference to an unknown variable, possible global leak. + messageId = "globalVariableLeak"; + } + + // def.node is an AssignmentExpression, ForInStatement or ForOfStatement. + variable.defs.forEach(def => { + report(def.node, messageId); + }); + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-implied-eval.js b/node_modules/eslint/lib/rules/no-implied-eval.js new file mode 100644 index 0000000..9a84f8c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implied-eval.js @@ -0,0 +1,132 @@ +/** + * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { getStaticValue } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `eval()`-like methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-implied-eval" + }, + + schema: [], + + messages: { + impliedEval: "Implied eval. Consider passing a function instead of a string." + } + }, + + create(context) { + const GLOBAL_CANDIDATES = Object.freeze(["global", "window", "globalThis"]); + const EVAL_LIKE_FUNC_PATTERN = /^(?:set(?:Interval|Timeout)|execScript)$/u; + const sourceCode = context.sourceCode; + + /** + * Checks whether a node is evaluated as a string or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is evaluated as a string. + */ + function isEvaluatedString(node) { + if ( + (node.type === "Literal" && typeof node.value === "string") || + node.type === "TemplateLiteral" + ) { + return true; + } + if (node.type === "BinaryExpression" && node.operator === "+") { + return isEvaluatedString(node.left) || isEvaluatedString(node.right); + } + return false; + } + + /** + * Reports if the `CallExpression` node has evaluated argument. + * @param {ASTNode} node A CallExpression to check. + * @returns {void} + */ + function reportImpliedEvalCallExpression(node) { + const [firstArgument] = node.arguments; + + if (firstArgument) { + + const staticValue = getStaticValue(firstArgument, sourceCode.getScope(node)); + const isStaticString = staticValue && typeof staticValue.value === "string"; + const isString = isStaticString || isEvaluatedString(firstArgument); + + if (isString) { + context.report({ + node, + messageId: "impliedEval" + }); + } + } + + } + + /** + * Reports calls of `implied eval` via the global references. + * @param {Variable} globalVar A global variable to check. + * @returns {void} + */ + function reportImpliedEvalViaGlobal(globalVar) { + const { references, name } = globalVar; + + references.forEach(ref => { + const identifier = ref.identifier; + let node = identifier.parent; + + while (astUtils.isSpecificMemberAccess(node, null, name)) { + node = node.parent; + } + + if (astUtils.isSpecificMemberAccess(node, null, EVAL_LIKE_FUNC_PATTERN)) { + const calleeNode = node.parent.type === "ChainExpression" ? node.parent : node; + const parent = calleeNode.parent; + + if (parent.type === "CallExpression" && parent.callee === calleeNode) { + reportImpliedEvalCallExpression(parent); + } + } + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + CallExpression(node) { + if (astUtils.isSpecificId(node.callee, EVAL_LIKE_FUNC_PATTERN)) { + reportImpliedEvalCallExpression(node); + } + }, + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + GLOBAL_CANDIDATES + .map(candidate => astUtils.getVariableByName(globalScope, candidate)) + .filter(globalVar => !!globalVar && globalVar.defs.length === 0) + .forEach(reportImpliedEvalViaGlobal); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-import-assign.js b/node_modules/eslint/lib/rules/no-import-assign.js new file mode 100644 index 0000000..c699886 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-import-assign.js @@ -0,0 +1,241 @@ +/** + * @fileoverview Rule to flag updates of imported bindings. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const { findVariable } = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils"); + +const WellKnownMutationFunctions = { + Object: /^(?:assign|definePropert(?:y|ies)|freeze|setPrototypeOf)$/u, + Reflect: /^(?:(?:define|delete)Property|set(?:PrototypeOf)?)$/u +}; + +/** + * Check if a given node is LHS of an assignment node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is LHS. + */ +function isAssignmentLeft(node) { + const { parent } = node; + + return ( + ( + parent.type === "AssignmentExpression" && + parent.left === node + ) || + + // Destructuring assignments + parent.type === "ArrayPattern" || + ( + parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern" + ) || + parent.type === "RestElement" || + ( + parent.type === "AssignmentPattern" && + parent.left === node + ) + ); +} + +/** + * Check if a given node is the operand of mutation unary operator. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is the operand of mutation unary operator. + */ +function isOperandOfMutationUnaryOperator(node) { + const argumentNode = node.parent.type === "ChainExpression" + ? node.parent + : node; + const { parent } = argumentNode; + + return ( + ( + parent.type === "UpdateExpression" && + parent.argument === argumentNode + ) || + ( + parent.type === "UnaryExpression" && + parent.operator === "delete" && + parent.argument === argumentNode + ) + ); +} + +/** + * Check if a given node is the iteration variable of `for-in`/`for-of` syntax. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is the iteration variable. + */ +function isIterationVariable(node) { + const { parent } = node; + + return ( + ( + parent.type === "ForInStatement" && + parent.left === node + ) || + ( + parent.type === "ForOfStatement" && + parent.left === node + ) + ); +} + +/** + * Check if a given node is at the first argument of a well-known mutation function. + * - `Object.assign` + * - `Object.defineProperty` + * - `Object.defineProperties` + * - `Object.freeze` + * - `Object.setPrototypeOf` + * - `Reflect.defineProperty` + * - `Reflect.deleteProperty` + * - `Reflect.set` + * - `Reflect.setPrototypeOf` + * @param {ASTNode} node The node to check. + * @param {Scope} scope A `escope.Scope` object to find variable (whichever). + * @returns {boolean} `true` if the node is at the first argument of a well-known mutation function. + */ +function isArgumentOfWellKnownMutationFunction(node, scope) { + const { parent } = node; + + if (parent.type !== "CallExpression" || parent.arguments[0] !== node) { + return false; + } + const callee = astUtils.skipChainExpression(parent.callee); + + if ( + !astUtils.isSpecificMemberAccess(callee, "Object", WellKnownMutationFunctions.Object) && + !astUtils.isSpecificMemberAccess(callee, "Reflect", WellKnownMutationFunctions.Reflect) + ) { + return false; + } + const variable = findVariable(scope, callee.object); + + return variable !== null && variable.scope.type === "global"; +} + +/** + * Check if the identifier node is placed at to update members. + * @param {ASTNode} id The Identifier node to check. + * @param {Scope} scope A `escope.Scope` object to find variable (whichever). + * @returns {boolean} `true` if the member of `id` was updated. + */ +function isMemberWrite(id, scope) { + const { parent } = id; + + return ( + ( + parent.type === "MemberExpression" && + parent.object === id && + ( + isAssignmentLeft(parent) || + isOperandOfMutationUnaryOperator(parent) || + isIterationVariable(parent) + ) + ) || + isArgumentOfWellKnownMutationFunction(id, scope) + ); +} + +/** + * Get the mutation node. + * @param {ASTNode} id The Identifier node to get. + * @returns {ASTNode} The mutation node. + */ +function getWriteNode(id) { + let node = id.parent; + + while ( + node && + node.type !== "AssignmentExpression" && + node.type !== "UpdateExpression" && + node.type !== "UnaryExpression" && + node.type !== "CallExpression" && + node.type !== "ForInStatement" && + node.type !== "ForOfStatement" + ) { + node = node.parent; + } + + return node || id; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow assigning to imported bindings", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-import-assign" + }, + + schema: [], + + messages: { + readonly: "'{{name}}' is read-only.", + readonlyMember: "The members of '{{name}}' are read-only." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + ImportDeclaration(node) { + const scope = sourceCode.getScope(node); + + for (const variable of sourceCode.getDeclaredVariables(node)) { + const shouldCheckMembers = variable.defs.some( + d => d.node.type === "ImportNamespaceSpecifier" + ); + let prevIdNode = null; + + for (const reference of variable.references) { + const idNode = reference.identifier; + + /* + * AssignmentPattern (e.g. `[a = 0] = b`) makes two write + * references for the same identifier. This should skip + * the one of the two in order to prevent redundant reports. + */ + if (idNode === prevIdNode) { + continue; + } + prevIdNode = idNode; + + if (reference.isWrite()) { + context.report({ + node: getWriteNode(idNode), + messageId: "readonly", + data: { name: idNode.name } + }); + } else if (shouldCheckMembers && isMemberWrite(idNode, scope)) { + context.report({ + node: getWriteNode(idNode), + messageId: "readonlyMember", + data: { name: idNode.name } + }); + } + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-inline-comments.js b/node_modules/eslint/lib/rules/no-inline-comments.js new file mode 100644 index 0000000..d96e647 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-inline-comments.js @@ -0,0 +1,110 @@ +/** + * @fileoverview Enforces or disallows inline comments. + * @author Greg Cochard + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow inline comments after code", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-inline-comments" + }, + + schema: [ + { + type: "object", + properties: { + ignorePattern: { + type: "string" + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedInlineComment: "Unexpected comment inline with code." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = context.options[0]; + let customIgnoreRegExp; + + if (options && options.ignorePattern) { + customIgnoreRegExp = new RegExp(options.ignorePattern, "u"); + } + + /** + * Will check that comments are not on lines starting with or ending with code + * @param {ASTNode} node The comment node to check + * @private + * @returns {void} + */ + function testCodeAroundComment(node) { + + const startLine = String(sourceCode.lines[node.loc.start.line - 1]), + endLine = String(sourceCode.lines[node.loc.end.line - 1]), + preamble = startLine.slice(0, node.loc.start.column).trim(), + postamble = endLine.slice(node.loc.end.column).trim(), + isPreambleEmpty = !preamble, + isPostambleEmpty = !postamble; + + // Nothing on both sides + if (isPreambleEmpty && isPostambleEmpty) { + return; + } + + // Matches the ignore pattern + if (customIgnoreRegExp && customIgnoreRegExp.test(node.value)) { + return; + } + + // JSX Exception + if ( + (isPreambleEmpty || preamble === "{") && + (isPostambleEmpty || postamble === "}") + ) { + const enclosingNode = sourceCode.getNodeByRangeIndex(node.range[0]); + + if (enclosingNode && enclosingNode.type === "JSXEmptyExpression") { + return; + } + } + + // Don't report ESLint directive comments + if (astUtils.isDirectiveComment(node)) { + return; + } + + context.report({ + node, + messageId: "unexpectedInlineComment" + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + sourceCode.getAllComments() + .filter(token => token.type !== "Shebang") + .forEach(testCodeAroundComment); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-inner-declarations.js b/node_modules/eslint/lib/rules/no-inner-declarations.js new file mode 100644 index 0000000..f4bae43 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-inner-declarations.js @@ -0,0 +1,110 @@ +/** + * @fileoverview Rule to enforce declarations in program or function body root. + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const validParent = new Set(["Program", "StaticBlock", "ExportNamedDeclaration", "ExportDefaultDeclaration"]); +const validBlockStatementParent = new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]); + +/** + * Finds the nearest enclosing context where this rule allows declarations and returns its description. + * @param {ASTNode} node Node to search from. + * @returns {string} Description. One of "program", "function body", "class static block body". + */ +function getAllowedBodyDescription(node) { + let { parent } = node; + + while (parent) { + + if (parent.type === "StaticBlock") { + return "class static block body"; + } + + if (astUtils.isFunction(parent)) { + return "function body"; + } + + ({ parent } = parent); + } + + return "program"; +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow variable or `function` declarations in nested blocks", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-inner-declarations" + }, + + schema: [ + { + enum: ["functions", "both"] + } + ], + + messages: { + moveDeclToRoot: "Move {{type}} declaration to {{body}} root." + } + }, + + create(context) { + + /** + * Ensure that a given node is at a program or function body's root. + * @param {ASTNode} node Declaration node to check. + * @returns {void} + */ + function check(node) { + const parent = node.parent; + + if ( + parent.type === "BlockStatement" && validBlockStatementParent.has(parent.parent.type) + ) { + return; + } + + if (validParent.has(parent.type)) { + return; + } + + context.report({ + node, + messageId: "moveDeclToRoot", + data: { + type: (node.type === "FunctionDeclaration" ? "function" : "variable"), + body: getAllowedBodyDescription(node) + } + }); + } + + + return { + + FunctionDeclaration: check, + VariableDeclaration(node) { + if (context.options[0] === "both" && node.kind === "var") { + check(node); + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-invalid-regexp.js b/node_modules/eslint/lib/rules/no-invalid-regexp.js new file mode 100644 index 0000000..3c42a68 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-invalid-regexp.js @@ -0,0 +1,194 @@ +/** + * @fileoverview Validate strings passed to the RegExp constructor + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const RegExpValidator = require("@eslint-community/regexpp").RegExpValidator; +const validator = new RegExpValidator(); +const validFlags = /[dgimsuvy]/gu; +const undefined1 = void 0; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow invalid regular expression strings in `RegExp` constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-invalid-regexp" + }, + + schema: [{ + type: "object", + properties: { + allowConstructorFlags: { + type: "array", + items: { + type: "string" + } + } + }, + additionalProperties: false + }], + + messages: { + regexMessage: "{{message}}." + } + }, + + create(context) { + + const options = context.options[0]; + let allowedFlags = null; + + if (options && options.allowConstructorFlags) { + const temp = options.allowConstructorFlags.join("").replace(validFlags, ""); + + if (temp) { + allowedFlags = new RegExp(`[${temp}]`, "giu"); + } + } + + /** + * Reports error with the provided message. + * @param {ASTNode} node The node holding the invalid RegExp + * @param {string} message The message to report. + * @returns {void} + */ + function report(node, message) { + context.report({ + node, + messageId: "regexMessage", + data: { message } + }); + } + + /** + * Check if node is a string + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if its a string + * @private + */ + function isString(node) { + return node && node.type === "Literal" && typeof node.value === "string"; + } + + /** + * Gets flags of a regular expression created by the given `RegExp()` or `new RegExp()` call + * Examples: + * new RegExp(".") // => "" + * new RegExp(".", "gu") // => "gu" + * new RegExp(".", flags) // => null + * @param {ASTNode} node `CallExpression` or `NewExpression` node + * @returns {string|null} flags if they can be determined, `null` otherwise + * @private + */ + function getFlags(node) { + if (node.arguments.length < 2) { + return ""; + } + + if (isString(node.arguments[1])) { + return node.arguments[1].value; + } + + return null; + } + + /** + * Check syntax error in a given pattern. + * @param {string} pattern The RegExp pattern to validate. + * @param {Object} flags The RegExp flags to validate. + * @param {boolean} [flags.unicode] The Unicode flag. + * @param {boolean} [flags.unicodeSets] The UnicodeSets flag. + * @returns {string|null} The syntax error. + */ + function validateRegExpPattern(pattern, flags) { + try { + validator.validatePattern(pattern, undefined1, undefined1, flags); + return null; + } catch (err) { + return err.message; + } + } + + /** + * Check syntax error in a given flags. + * @param {string|null} flags The RegExp flags to validate. + * @returns {string|null} The syntax error. + */ + function validateRegExpFlags(flags) { + if (!flags) { + return null; + } + try { + validator.validateFlags(flags); + } catch { + return `Invalid flags supplied to RegExp constructor '${flags}'`; + } + + /* + * `regexpp` checks the combination of `u` and `v` flags when parsing `Pattern` according to `ecma262`, + * but this rule may check only the flag when the pattern is unidentifiable, so check it here. + * https://tc39.es/ecma262/multipage/text-processing.html#sec-parsepattern + */ + if (flags.includes("u") && flags.includes("v")) { + return "Regex 'u' and 'v' flags cannot be used together"; + } + return null; + } + + return { + "CallExpression, NewExpression"(node) { + if (node.callee.type !== "Identifier" || node.callee.name !== "RegExp") { + return; + } + + let flags = getFlags(node); + + if (flags && allowedFlags) { + flags = flags.replace(allowedFlags, ""); + } + + let message = validateRegExpFlags(flags); + + if (message) { + report(node, message); + return; + } + + if (!isString(node.arguments[0])) { + return; + } + + const pattern = node.arguments[0].value; + + message = ( + + // If flags are unknown, report the regex only if its pattern is invalid both with and without the "u" flag + flags === null + ? ( + validateRegExpPattern(pattern, { unicode: true, unicodeSets: false }) && + validateRegExpPattern(pattern, { unicode: false, unicodeSets: true }) && + validateRegExpPattern(pattern, { unicode: false, unicodeSets: false }) + ) + : validateRegExpPattern(pattern, { unicode: flags.includes("u"), unicodeSets: flags.includes("v") }) + ); + + if (message) { + report(node, message); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-invalid-this.js b/node_modules/eslint/lib/rules/no-invalid-this.js new file mode 100644 index 0000000..49ecbe5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-invalid-this.js @@ -0,0 +1,150 @@ +/** + * @fileoverview A rule to disallow `this` keywords in contexts where the value of `this` is `undefined`. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given code path is a code path with lexical `this` binding. + * That is, if `this` within the code path refers to `this` of surrounding code path. + * @param {CodePath} codePath Code path. + * @param {ASTNode} node Node that started the code path. + * @returns {boolean} `true` if it is a code path with lexical `this` binding. + */ +function isCodePathWithLexicalThis(codePath, node) { + return codePath.origin === "function" && node.type === "ArrowFunctionExpression"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow use of `this` in contexts where the value of `this` is `undefined`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-invalid-this" + }, + + schema: [ + { + type: "object", + properties: { + capIsConstructor: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedThis: "Unexpected 'this'." + } + }, + + create(context) { + const options = context.options[0] || {}; + const capIsConstructor = options.capIsConstructor !== false; + const stack = [], + sourceCode = context.sourceCode; + + /** + * Gets the current checking context. + * + * The return value has a flag that whether or not `this` keyword is valid. + * The flag is initialized when got at the first time. + * @returns {{valid: boolean}} + * an object which has a flag that whether or not `this` keyword is valid. + */ + stack.getCurrent = function() { + const current = this[this.length - 1]; + + if (!current.init) { + current.init = true; + current.valid = !astUtils.isDefaultThisBinding( + current.node, + sourceCode, + { capIsConstructor } + ); + } + return current; + }; + + return { + + onCodePathStart(codePath, node) { + if (isCodePathWithLexicalThis(codePath, node)) { + return; + } + + if (codePath.origin === "program") { + const scope = sourceCode.getScope(node); + const features = context.parserOptions.ecmaFeatures || {}; + + // `this` at the top level of scripts always refers to the global object + stack.push({ + init: true, + node, + valid: !( + node.sourceType === "module" || + (features.globalReturn && scope.childScopes[0].isStrict) + ) + }); + + return; + } + + /* + * `init: false` means that `valid` isn't determined yet. + * Most functions don't use `this`, and the calculation for `valid` + * is relatively costly, so we'll calculate it lazily when the first + * `this` within the function is traversed. A special case are non-strict + * functions, because `this` refers to the global object and therefore is + * always valid, so we can set `init: true` right away. + */ + stack.push({ + init: !sourceCode.getScope(node).isStrict, + node, + valid: true + }); + }, + + onCodePathEnd(codePath, node) { + if (isCodePathWithLexicalThis(codePath, node)) { + return; + } + + stack.pop(); + }, + + // Reports if `this` of the current context is invalid. + ThisExpression(node) { + const current = stack.getCurrent(); + + if (current && !current.valid) { + context.report({ + node, + messageId: "unexpectedThis" + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-irregular-whitespace.js b/node_modules/eslint/lib/rules/no-irregular-whitespace.js new file mode 100644 index 0000000..ab7ccac --- /dev/null +++ b/node_modules/eslint/lib/rules/no-irregular-whitespace.js @@ -0,0 +1,276 @@ +/** + * @fileoverview Rule to disallow whitespace that is not a tab or space, whitespace inside strings and comments are allowed + * @author Jonathan Kingston + * @author Christophe Porteneuve + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const ALL_IRREGULARS = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/u; +const IRREGULAR_WHITESPACE = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/mgu; +const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mgu; +const LINE_BREAK = astUtils.createGlobalLinebreakMatcher(); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow irregular whitespace", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-irregular-whitespace" + }, + + schema: [ + { + type: "object", + properties: { + skipComments: { + type: "boolean", + default: false + }, + skipStrings: { + type: "boolean", + default: true + }, + skipTemplates: { + type: "boolean", + default: false + }, + skipRegExps: { + type: "boolean", + default: false + }, + skipJSXText: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + noIrregularWhitespace: "Irregular whitespace not allowed." + } + }, + + create(context) { + + // Module store of errors that we have found + let errors = []; + + // Lookup the `skipComments` option, which defaults to `false`. + const options = context.options[0] || {}; + const skipComments = !!options.skipComments; + const skipStrings = options.skipStrings !== false; + const skipRegExps = !!options.skipRegExps; + const skipTemplates = !!options.skipTemplates; + const skipJSXText = !!options.skipJSXText; + + const sourceCode = context.sourceCode; + const commentNodes = sourceCode.getAllComments(); + + /** + * Removes errors that occur inside the given node + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeWhitespaceError(node) { + const locStart = node.loc.start; + const locEnd = node.loc.end; + + errors = errors.filter(({ loc: { start: errorLocStart } }) => ( + errorLocStart.line < locStart.line || + errorLocStart.line === locStart.line && errorLocStart.column < locStart.column || + errorLocStart.line === locEnd.line && errorLocStart.column >= locEnd.column || + errorLocStart.line > locEnd.line + )); + } + + /** + * Checks literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInLiteral(node) { + const shouldCheckStrings = skipStrings && (typeof node.value === "string"); + const shouldCheckRegExps = skipRegExps && Boolean(node.regex); + + if (shouldCheckStrings || shouldCheckRegExps) { + + // If we have irregular characters remove them from the errors list + if (ALL_IRREGULARS.test(node.raw)) { + removeWhitespaceError(node); + } + } + } + + /** + * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInTemplateLiteral(node) { + if (typeof node.value.raw === "string") { + if (ALL_IRREGULARS.test(node.value.raw)) { + removeWhitespaceError(node); + } + } + } + + /** + * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInComment(node) { + if (ALL_IRREGULARS.test(node.value)) { + removeWhitespaceError(node); + } + } + + /** + * Checks JSX nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInJSXText(node) { + if (ALL_IRREGULARS.test(node.raw)) { + removeWhitespaceError(node); + } + } + + /** + * Checks the program source for irregular whitespace + * @param {ASTNode} node The program node + * @returns {void} + * @private + */ + function checkForIrregularWhitespace(node) { + const sourceLines = sourceCode.lines; + + sourceLines.forEach((sourceLine, lineIndex) => { + const lineNumber = lineIndex + 1; + let match; + + while ((match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null) { + errors.push({ + node, + messageId: "noIrregularWhitespace", + loc: { + start: { + line: lineNumber, + column: match.index + }, + end: { + line: lineNumber, + column: match.index + match[0].length + } + } + }); + } + }); + } + + /** + * Checks the program source for irregular line terminators + * @param {ASTNode} node The program node + * @returns {void} + * @private + */ + function checkForIrregularLineTerminators(node) { + const source = sourceCode.getText(), + sourceLines = sourceCode.lines, + linebreaks = source.match(LINE_BREAK); + let lastLineIndex = -1, + match; + + while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) { + const lineIndex = linebreaks.indexOf(match[0], lastLineIndex + 1) || 0; + + errors.push({ + node, + messageId: "noIrregularWhitespace", + loc: { + start: { + line: lineIndex + 1, + column: sourceLines[lineIndex].length + }, + end: { + line: lineIndex + 2, + column: 0 + } + } + }); + + lastLineIndex = lineIndex; + } + } + + /** + * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`. + * @returns {void} + * @private + */ + function noop() {} + + const nodes = {}; + + if (ALL_IRREGULARS.test(sourceCode.getText())) { + nodes.Program = function(node) { + + /* + * As we can easily fire warnings for all white space issues with + * all the source its simpler to fire them here. + * This means we can check all the application code without having + * to worry about issues caused in the parser tokens. + * When writing this code also evaluating per node was missing out + * connecting tokens in some cases. + * We can later filter the errors when they are found to be not an + * issue in nodes we don't care about. + */ + checkForIrregularWhitespace(node); + checkForIrregularLineTerminators(node); + }; + + nodes.Literal = removeInvalidNodeErrorsInLiteral; + nodes.TemplateElement = skipTemplates ? removeInvalidNodeErrorsInTemplateLiteral : noop; + nodes.JSXText = skipJSXText ? removeInvalidNodeErrorsInJSXText : noop; + nodes["Program:exit"] = function() { + if (skipComments) { + + // First strip errors occurring in comment nodes. + commentNodes.forEach(removeInvalidNodeErrorsInComment); + } + + // If we have any errors remaining report on them + errors.forEach(error => context.report(error)); + }; + } else { + nodes.Program = noop; + } + + return nodes; + } +}; diff --git a/node_modules/eslint/lib/rules/no-iterator.js b/node_modules/eslint/lib/rules/no-iterator.js new file mode 100644 index 0000000..dcd9683 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-iterator.js @@ -0,0 +1,52 @@ +/** + * @fileoverview Rule to flag usage of __iterator__ property + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getStaticPropertyName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of the `__iterator__` property", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-iterator" + }, + + schema: [], + + messages: { + noIterator: "Reserved name '__iterator__'." + } + }, + + create(context) { + + return { + + MemberExpression(node) { + + if (getStaticPropertyName(node) === "__iterator__") { + context.report({ + node, + messageId: "noIterator" + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-label-var.js b/node_modules/eslint/lib/rules/no-label-var.js new file mode 100644 index 0000000..bf33cd1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-label-var.js @@ -0,0 +1,80 @@ +/** + * @fileoverview Rule to flag labels that are the same as an identifier + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow labels that share a name with a variable", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-label-var" + }, + + schema: [], + + messages: { + identifierClashWithLabel: "Found identifier with same name as label." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the identifier is present inside current scope + * @param {Object} scope current scope + * @param {string} name To evaluate + * @returns {boolean} True if its present + * @private + */ + function findIdentifier(scope, name) { + return astUtils.getVariableByName(scope, name) !== null; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + LabeledStatement(node) { + + // Fetch the innermost scope. + const scope = sourceCode.getScope(node); + + /* + * Recursively find the identifier walking up the scope, starting + * with the innermost scope. + */ + if (findIdentifier(scope, node.label.name)) { + context.report({ + node, + messageId: "identifierClashWithLabel" + }); + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-labels.js b/node_modules/eslint/lib/rules/no-labels.js new file mode 100644 index 0000000..d991a0a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-labels.js @@ -0,0 +1,149 @@ +/** + * @fileoverview Disallow Labeled Statements + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow labeled statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-labels" + }, + + schema: [ + { + type: "object", + properties: { + allowLoop: { + type: "boolean", + default: false + }, + allowSwitch: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedLabel: "Unexpected labeled statement.", + unexpectedLabelInBreak: "Unexpected label in break statement.", + unexpectedLabelInContinue: "Unexpected label in continue statement." + } + }, + + create(context) { + const options = context.options[0]; + const allowLoop = options && options.allowLoop; + const allowSwitch = options && options.allowSwitch; + let scopeInfo = null; + + /** + * Gets the kind of a given node. + * @param {ASTNode} node A node to get. + * @returns {string} The kind of the node. + */ + function getBodyKind(node) { + if (astUtils.isLoop(node)) { + return "loop"; + } + if (node.type === "SwitchStatement") { + return "switch"; + } + return "other"; + } + + /** + * Checks whether the label of a given kind is allowed or not. + * @param {string} kind A kind to check. + * @returns {boolean} `true` if the kind is allowed. + */ + function isAllowed(kind) { + switch (kind) { + case "loop": return allowLoop; + case "switch": return allowSwitch; + default: return false; + } + } + + /** + * Checks whether a given name is a label of a loop or not. + * @param {string} label A name of a label to check. + * @returns {boolean} `true` if the name is a label of a loop. + */ + function getKind(label) { + let info = scopeInfo; + + while (info) { + if (info.label === label) { + return info.kind; + } + info = info.upper; + } + + /* c8 ignore next */ + return "other"; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + LabeledStatement(node) { + scopeInfo = { + label: node.label.name, + kind: getBodyKind(node.body), + upper: scopeInfo + }; + }, + + "LabeledStatement:exit"(node) { + if (!isAllowed(scopeInfo.kind)) { + context.report({ + node, + messageId: "unexpectedLabel" + }); + } + + scopeInfo = scopeInfo.upper; + }, + + BreakStatement(node) { + if (node.label && !isAllowed(getKind(node.label.name))) { + context.report({ + node, + messageId: "unexpectedLabelInBreak" + }); + } + }, + + ContinueStatement(node) { + if (node.label && !isAllowed(getKind(node.label.name))) { + context.report({ + node, + messageId: "unexpectedLabelInContinue" + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-lone-blocks.js b/node_modules/eslint/lib/rules/no-lone-blocks.js new file mode 100644 index 0000000..767eec2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-lone-blocks.js @@ -0,0 +1,136 @@ +/** + * @fileoverview Rule to flag blocks with no reason to exist + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary nested blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-lone-blocks" + }, + + schema: [], + + messages: { + redundantBlock: "Block is redundant.", + redundantNestedBlock: "Nested block is redundant." + } + }, + + create(context) { + + // A stack of lone blocks to be checked for block-level bindings + const loneBlocks = []; + let ruleDef; + const sourceCode = context.sourceCode; + + /** + * Reports a node as invalid. + * @param {ASTNode} node The node to be reported. + * @returns {void} + */ + function report(node) { + const messageId = node.parent.type === "BlockStatement" || node.parent.type === "StaticBlock" + ? "redundantNestedBlock" + : "redundantBlock"; + + context.report({ + node, + messageId + }); + } + + /** + * Checks for any occurrence of a BlockStatement in a place where lists of statements can appear + * @param {ASTNode} node The node to check + * @returns {boolean} True if the node is a lone block. + */ + function isLoneBlock(node) { + return node.parent.type === "BlockStatement" || + node.parent.type === "StaticBlock" || + node.parent.type === "Program" || + + // Don't report blocks in switch cases if the block is the only statement of the case. + node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1); + } + + /** + * Checks the enclosing block of the current node for block-level bindings, + * and "marks it" as valid if any. + * @param {ASTNode} node The current node to check. + * @returns {void} + */ + function markLoneBlock(node) { + if (loneBlocks.length === 0) { + return; + } + + const block = node.parent; + + if (loneBlocks[loneBlocks.length - 1] === block) { + loneBlocks.pop(); + } + } + + // Default rule definition: report all lone blocks + ruleDef = { + BlockStatement(node) { + if (isLoneBlock(node)) { + report(node); + } + } + }; + + // ES6: report blocks without block-level bindings, or that's only child of another block + if (context.languageOptions.ecmaVersion >= 2015) { + ruleDef = { + BlockStatement(node) { + if (isLoneBlock(node)) { + loneBlocks.push(node); + } + }, + "BlockStatement:exit"(node) { + if (loneBlocks.length > 0 && loneBlocks[loneBlocks.length - 1] === node) { + loneBlocks.pop(); + report(node); + } else if ( + ( + node.parent.type === "BlockStatement" || + node.parent.type === "StaticBlock" + ) && + node.parent.body.length === 1 + ) { + report(node); + } + } + }; + + ruleDef.VariableDeclaration = function(node) { + if (node.kind === "let" || node.kind === "const") { + markLoneBlock(node); + } + }; + + ruleDef.FunctionDeclaration = function(node) { + if (sourceCode.getScope(node).isStrict) { + markLoneBlock(node); + } + }; + + ruleDef.ClassDeclaration = markLoneBlock; + } + + return ruleDef; + } +}; diff --git a/node_modules/eslint/lib/rules/no-lonely-if.js b/node_modules/eslint/lib/rules/no-lonely-if.js new file mode 100644 index 0000000..eefd2c6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-lonely-if.js @@ -0,0 +1,88 @@ +/** + * @fileoverview Rule to disallow if as the only statement in an else block + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `if` statements as the only statement in `else` blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-lonely-if" + }, + + schema: [], + fixable: "code", + + messages: { + unexpectedLonelyIf: "Unexpected if as the only statement in an else block." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + IfStatement(node) { + const parent = node.parent, + grandparent = parent.parent; + + if (parent && parent.type === "BlockStatement" && + parent.body.length === 1 && grandparent && + grandparent.type === "IfStatement" && + parent === grandparent.alternate) { + context.report({ + node, + messageId: "unexpectedLonelyIf", + fix(fixer) { + const openingElseCurly = sourceCode.getFirstToken(parent); + const closingElseCurly = sourceCode.getLastToken(parent); + const elseKeyword = sourceCode.getTokenBefore(openingElseCurly); + const tokenAfterElseBlock = sourceCode.getTokenAfter(closingElseCurly); + const lastIfToken = sourceCode.getLastToken(node.consequent); + const sourceText = sourceCode.getText(); + + if (sourceText.slice(openingElseCurly.range[1], + node.range[0]).trim() || sourceText.slice(node.range[1], closingElseCurly.range[0]).trim()) { + + // Don't fix if there are any non-whitespace characters interfering (e.g. comments) + return null; + } + + if ( + node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock && + ( + node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line || + /^[([/+`-]/u.test(tokenAfterElseBlock.value) || + lastIfToken.value === "++" || + lastIfToken.value === "--" + ) + ) { + + /* + * If the `if` statement has no block, and is not followed by a semicolon, make sure that fixing + * the issue would not change semantics due to ASI. If this would happen, don't do a fix. + */ + return null; + } + + return fixer.replaceTextRange( + [openingElseCurly.range[0], closingElseCurly.range[1]], + (elseKeyword.range[1] === openingElseCurly.range[0] ? " " : "") + sourceCode.getText(node) + ); + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-loop-func.js b/node_modules/eslint/lib/rules/no-loop-func.js new file mode 100644 index 0000000..48312fb --- /dev/null +++ b/node_modules/eslint/lib/rules/no-loop-func.js @@ -0,0 +1,206 @@ +/** + * @fileoverview Rule to flag creation of function inside a loop + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets the containing loop node of a specified node. + * + * We don't need to check nested functions, so this ignores those. + * `Scope.through` contains references of nested functions. + * @param {ASTNode} node An AST node to get. + * @returns {ASTNode|null} The containing loop node of the specified node, or + * `null`. + */ +function getContainingLoopNode(node) { + for (let currentNode = node; currentNode.parent; currentNode = currentNode.parent) { + const parent = currentNode.parent; + + switch (parent.type) { + case "WhileStatement": + case "DoWhileStatement": + return parent; + + case "ForStatement": + + // `init` is outside of the loop. + if (parent.init !== currentNode) { + return parent; + } + break; + + case "ForInStatement": + case "ForOfStatement": + + // `right` is outside of the loop. + if (parent.right !== currentNode) { + return parent; + } + break; + + case "ArrowFunctionExpression": + case "FunctionExpression": + case "FunctionDeclaration": + + // We don't need to check nested functions. + return null; + + default: + break; + } + } + + return null; +} + +/** + * Gets the containing loop node of a given node. + * If the loop was nested, this returns the most outer loop. + * @param {ASTNode} node A node to get. This is a loop node. + * @param {ASTNode|null} excludedNode A node that the result node should not + * include. + * @returns {ASTNode} The most outer loop node. + */ +function getTopLoopNode(node, excludedNode) { + const border = excludedNode ? excludedNode.range[1] : 0; + let retv = node; + let containingLoopNode = node; + + while (containingLoopNode && containingLoopNode.range[0] >= border) { + retv = containingLoopNode; + containingLoopNode = getContainingLoopNode(containingLoopNode); + } + + return retv; +} + +/** + * Checks whether a given reference which refers to an upper scope's variable is + * safe or not. + * @param {ASTNode} loopNode A containing loop node. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is safe or not. + */ +function isSafe(loopNode, reference) { + const variable = reference.resolved; + const definition = variable && variable.defs[0]; + const declaration = definition && definition.parent; + const kind = (declaration && declaration.type === "VariableDeclaration") + ? declaration.kind + : ""; + + // Variables which are declared by `const` is safe. + if (kind === "const") { + return true; + } + + /* + * Variables which are declared by `let` in the loop is safe. + * It's a different instance from the next loop step's. + */ + if (kind === "let" && + declaration.range[0] > loopNode.range[0] && + declaration.range[1] < loopNode.range[1] + ) { + return true; + } + + /* + * WriteReferences which exist after this border are unsafe because those + * can modify the variable. + */ + const border = getTopLoopNode( + loopNode, + (kind === "let") ? declaration : null + ).range[0]; + + /** + * Checks whether a given reference is safe or not. + * The reference is every reference of the upper scope's variable we are + * looking now. + * + * It's safe if the reference matches one of the following condition. + * - is readonly. + * - doesn't exist inside a local function and after the border. + * @param {eslint-scope.Reference} upperRef A reference to check. + * @returns {boolean} `true` if the reference is safe. + */ + function isSafeReference(upperRef) { + const id = upperRef.identifier; + + return ( + !upperRef.isWrite() || + variable.scope.variableScope === upperRef.from.variableScope && + id.range[0] < border + ); + } + + return Boolean(variable) && variable.references.every(isSafeReference); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow function declarations that contain unsafe references inside loop statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-loop-func" + }, + + schema: [], + + messages: { + unsafeRefs: "Function declared in a loop contains unsafe references to variable(s) {{ varNames }}." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Reports functions which match the following condition: + * + * - has a loop node in ancestors. + * - has any references which refers to an unsafe variable. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function checkForLoops(node) { + const loopNode = getContainingLoopNode(node); + + if (!loopNode) { + return; + } + + const references = sourceCode.getScope(node).through; + const unsafeRefs = references.filter(r => r.resolved && !isSafe(loopNode, r)).map(r => r.identifier.name); + + if (unsafeRefs.length > 0) { + context.report({ + node, + messageId: "unsafeRefs", + data: { varNames: `'${unsafeRefs.join("', '")}'` } + }); + } + } + + return { + ArrowFunctionExpression: checkForLoops, + FunctionExpression: checkForLoops, + FunctionDeclaration: checkForLoops + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-loss-of-precision.js b/node_modules/eslint/lib/rules/no-loss-of-precision.js new file mode 100644 index 0000000..b3635e3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-loss-of-precision.js @@ -0,0 +1,214 @@ +/** + * @fileoverview Rule to flag numbers that will lose significant figure precision at runtime + * @author Jacob Moore + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow literal numbers that lose precision", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-loss-of-precision" + }, + schema: [], + messages: { + noLossOfPrecision: "This number literal will lose precision at runtime." + } + }, + + create(context) { + + /** + * Returns whether the node is number literal + * @param {Node} node the node literal being evaluated + * @returns {boolean} true if the node is a number literal + */ + function isNumber(node) { + return typeof node.value === "number"; + } + + /** + * Gets the source code of the given number literal. Removes `_` numeric separators from the result. + * @param {Node} node the number `Literal` node + * @returns {string} raw source code of the literal, without numeric separators + */ + function getRaw(node) { + return node.raw.replace(/_/gu, ""); + } + + /** + * Checks whether the number is base ten + * @param {ASTNode} node the node being evaluated + * @returns {boolean} true if the node is in base ten + */ + function isBaseTen(node) { + const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"]; + + return prefixes.every(prefix => !node.raw.startsWith(prefix)) && + !/^0[0-7]+$/u.test(node.raw); + } + + /** + * Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ + function notBaseTenLosesPrecision(node) { + const rawString = getRaw(node).toUpperCase(); + let base = 0; + + if (rawString.startsWith("0B")) { + base = 2; + } else if (rawString.startsWith("0X")) { + base = 16; + } else { + base = 8; + } + + return !rawString.endsWith(node.value.toString(base).toUpperCase()); + } + + /** + * Adds a decimal point to the numeric string at index 1 + * @param {string} stringNumber the numeric string without any decimal point + * @returns {string} the numeric string with a decimal point in the proper place + */ + function addDecimalPointToNumber(stringNumber) { + return `${stringNumber[0]}.${stringNumber.slice(1)}`; + } + + /** + * Returns the number stripped of leading zeros + * @param {string} numberAsString the string representation of the number + * @returns {string} the stripped string + */ + function removeLeadingZeros(numberAsString) { + for (let i = 0; i < numberAsString.length; i++) { + if (numberAsString[i] !== "0") { + return numberAsString.slice(i); + } + } + return numberAsString; + } + + /** + * Returns the number stripped of trailing zeros + * @param {string} numberAsString the string representation of the number + * @returns {string} the stripped string + */ + function removeTrailingZeros(numberAsString) { + for (let i = numberAsString.length - 1; i >= 0; i--) { + if (numberAsString[i] !== "0") { + return numberAsString.slice(0, i + 1); + } + } + return numberAsString; + } + + /** + * Converts an integer to an object containing the integer's coefficient and order of magnitude + * @param {string} stringInteger the string representation of the integer being converted + * @returns {Object} the object containing the integer's coefficient and order of magnitude + */ + function normalizeInteger(stringInteger) { + const significantDigits = removeTrailingZeros(removeLeadingZeros(stringInteger)); + + return { + magnitude: stringInteger.startsWith("0") ? stringInteger.length - 2 : stringInteger.length - 1, + coefficient: addDecimalPointToNumber(significantDigits) + }; + } + + /** + * + * Converts a float to an object containing the floats's coefficient and order of magnitude + * @param {string} stringFloat the string representation of the float being converted + * @returns {Object} the object containing the integer's coefficient and order of magnitude + */ + function normalizeFloat(stringFloat) { + const trimmedFloat = removeLeadingZeros(stringFloat); + + if (trimmedFloat.startsWith(".")) { + const decimalDigits = trimmedFloat.slice(1); + const significantDigits = removeLeadingZeros(decimalDigits); + + return { + magnitude: significantDigits.length - decimalDigits.length - 1, + coefficient: addDecimalPointToNumber(significantDigits) + }; + + } + return { + magnitude: trimmedFloat.indexOf(".") - 1, + coefficient: addDecimalPointToNumber(trimmedFloat.replace(".", "")) + + }; + } + + /** + * Converts a base ten number to proper scientific notation + * @param {string} stringNumber the string representation of the base ten number to be converted + * @returns {string} the number converted to scientific notation + */ + function convertNumberToScientificNotation(stringNumber) { + const splitNumber = stringNumber.replace("E", "e").split("e"); + const originalCoefficient = splitNumber[0]; + const normalizedNumber = stringNumber.includes(".") ? normalizeFloat(originalCoefficient) + : normalizeInteger(originalCoefficient); + const normalizedCoefficient = normalizedNumber.coefficient; + const magnitude = splitNumber.length > 1 ? (parseInt(splitNumber[1], 10) + normalizedNumber.magnitude) + : normalizedNumber.magnitude; + + return `${normalizedCoefficient}e${magnitude}`; + } + + /** + * Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ + function baseTenLosesPrecision(node) { + const normalizedRawNumber = convertNumberToScientificNotation(getRaw(node)); + const requestedPrecision = normalizedRawNumber.split("e")[0].replace(".", "").length; + + if (requestedPrecision > 100) { + return true; + } + const storedNumber = node.value.toPrecision(requestedPrecision); + const normalizedStoredNumber = convertNumberToScientificNotation(storedNumber); + + return normalizedRawNumber !== normalizedStoredNumber; + } + + + /** + * Checks that the user-intended number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ + function losesPrecision(node) { + return isBaseTen(node) ? baseTenLosesPrecision(node) : notBaseTenLosesPrecision(node); + } + + + return { + Literal(node) { + if (node.value && isNumber(node) && losesPrecision(node)) { + context.report({ + messageId: "noLossOfPrecision", + node + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-magic-numbers.js b/node_modules/eslint/lib/rules/no-magic-numbers.js new file mode 100644 index 0000000..f48a62d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-magic-numbers.js @@ -0,0 +1,243 @@ +/** + * @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js) + * @author Vincent Lemeunier + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +// Maximum array length by the ECMAScript Specification. +const MAX_ARRAY_LENGTH = 2 ** 32 - 1; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Convert the value to bigint if it's a string. Otherwise return the value as-is. + * @param {bigint|number|string} x The value to normalize. + * @returns {bigint|number} The normalized value. + */ +function normalizeIgnoreValue(x) { + if (typeof x === "string") { + return BigInt(x.slice(0, -1)); + } + return x; +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow magic numbers", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-magic-numbers" + }, + + schema: [{ + type: "object", + properties: { + detectObjects: { + type: "boolean", + default: false + }, + enforceConst: { + type: "boolean", + default: false + }, + ignore: { + type: "array", + items: { + anyOf: [ + { type: "number" }, + { type: "string", pattern: "^[+-]?(?:0|[1-9][0-9]*)n$" } + ] + }, + uniqueItems: true + }, + ignoreArrayIndexes: { + type: "boolean", + default: false + }, + ignoreDefaultValues: { + type: "boolean", + default: false + }, + ignoreClassFieldInitialValues: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + + messages: { + useConst: "Number constants declarations must use 'const'.", + noMagic: "No magic number: {{raw}}." + } + }, + + create(context) { + const config = context.options[0] || {}, + detectObjects = !!config.detectObjects, + enforceConst = !!config.enforceConst, + ignore = new Set((config.ignore || []).map(normalizeIgnoreValue)), + ignoreArrayIndexes = !!config.ignoreArrayIndexes, + ignoreDefaultValues = !!config.ignoreDefaultValues, + ignoreClassFieldInitialValues = !!config.ignoreClassFieldInitialValues; + + const okTypes = detectObjects ? [] : ["ObjectExpression", "Property", "AssignmentExpression"]; + + /** + * Returns whether the rule is configured to ignore the given value + * @param {bigint|number} value The value to check + * @returns {boolean} true if the value is ignored + */ + function isIgnoredValue(value) { + return ignore.has(value); + } + + /** + * Returns whether the number is a default value assignment. + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the number is a default value + */ + function isDefaultValue(fullNumberNode) { + const parent = fullNumberNode.parent; + + return parent.type === "AssignmentPattern" && parent.right === fullNumberNode; + } + + /** + * Returns whether the number is the initial value of a class field. + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the number is the initial value of a class field. + */ + function isClassFieldInitialValue(fullNumberNode) { + const parent = fullNumberNode.parent; + + return parent.type === "PropertyDefinition" && parent.value === fullNumberNode; + } + + /** + * Returns whether the given node is used as a radix within parseInt() or Number.parseInt() + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the node is radix + */ + function isParseIntRadix(fullNumberNode) { + const parent = fullNumberNode.parent; + + return parent.type === "CallExpression" && fullNumberNode === parent.arguments[1] && + ( + astUtils.isSpecificId(parent.callee, "parseInt") || + astUtils.isSpecificMemberAccess(parent.callee, "Number", "parseInt") + ); + } + + /** + * Returns whether the given node is a direct child of a JSX node. + * In particular, it aims to detect numbers used as prop values in JSX tags. + * Example: + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the node is a JSX number + */ + function isJSXNumber(fullNumberNode) { + return fullNumberNode.parent.type.indexOf("JSX") === 0; + } + + /** + * Returns whether the given node is used as an array index. + * Value must coerce to a valid array index name: "0", "1", "2" ... "4294967294". + * + * All other values, like "-1", "2.5", or "4294967295", are just "normal" object properties, + * which can be created and accessed on an array in addition to the array index properties, + * but they don't affect array's length and are not considered by methods such as .map(), .forEach() etc. + * + * The maximum array length by the specification is 2 ** 32 - 1 = 4294967295, + * thus the maximum valid index is 2 ** 32 - 2 = 4294967294. + * + * All notations are allowed, as long as the value coerces to one of "0", "1", "2" ... "4294967294". + * + * Valid examples: + * a[0], a[1], a[1.2e1], a[0xAB], a[0n], a[1n] + * a[-0] (same as a[0] because -0 coerces to "0") + * a[-0n] (-0n evaluates to 0n) + * + * Invalid examples: + * a[-1], a[-0xAB], a[-1n], a[2.5], a[1.23e1], a[12e-1] + * a[4294967295] (above the max index, it's an access to a regular property a["4294967295"]) + * a[999999999999999999999] (even if it wasn't above the max index, it would be a["1e+21"]) + * a[1e310] (same as a["Infinity"]) + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @param {bigint|number} value Value expressed by the fullNumberNode + * @returns {boolean} true if the node is a valid array index + */ + function isArrayIndex(fullNumberNode, value) { + const parent = fullNumberNode.parent; + + return parent.type === "MemberExpression" && parent.property === fullNumberNode && + (Number.isInteger(value) || typeof value === "bigint") && + value >= 0 && value < MAX_ARRAY_LENGTH; + } + + return { + Literal(node) { + if (!astUtils.isNumericLiteral(node)) { + return; + } + + let fullNumberNode; + let value; + let raw; + + // Treat unary minus as a part of the number + if (node.parent.type === "UnaryExpression" && node.parent.operator === "-") { + fullNumberNode = node.parent; + value = -node.value; + raw = `-${node.raw}`; + } else { + fullNumberNode = node; + value = node.value; + raw = node.raw; + } + + const parent = fullNumberNode.parent; + + // Always allow radix arguments and JSX props + if ( + isIgnoredValue(value) || + (ignoreDefaultValues && isDefaultValue(fullNumberNode)) || + (ignoreClassFieldInitialValues && isClassFieldInitialValue(fullNumberNode)) || + isParseIntRadix(fullNumberNode) || + isJSXNumber(fullNumberNode) || + (ignoreArrayIndexes && isArrayIndex(fullNumberNode, value)) + ) { + return; + } + + if (parent.type === "VariableDeclarator") { + if (enforceConst && parent.parent.kind !== "const") { + context.report({ + node: fullNumberNode, + messageId: "useConst" + }); + } + } else if ( + !okTypes.includes(parent.type) || + (parent.type === "AssignmentExpression" && parent.left.type === "Identifier") + ) { + context.report({ + node: fullNumberNode, + messageId: "noMagic", + data: { + raw + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-misleading-character-class.js b/node_modules/eslint/lib/rules/no-misleading-character-class.js new file mode 100644 index 0000000..99aa940 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-misleading-character-class.js @@ -0,0 +1,250 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +const { CALL, CONSTRUCT, ReferenceTracker, getStringIfConstant } = require("@eslint-community/eslint-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); +const { isCombiningCharacter, isEmojiModifier, isRegionalIndicatorSymbol, isSurrogatePair } = require("./utils/unicode"); +const astUtils = require("./utils/ast-utils.js"); +const { isValidWithUnicodeFlag } = require("./utils/regular-expressions"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Iterate character sequences of a given nodes. + * + * CharacterClassRange syntax can steal a part of character sequence, + * so this function reverts CharacterClassRange syntax and restore the sequence. + * @param {import('@eslint-community/regexpp').AST.CharacterClassElement[]} nodes The node list to iterate character sequences. + * @returns {IterableIterator} The list of character sequences. + */ +function *iterateCharacterSequence(nodes) { + let seq = []; + + for (const node of nodes) { + switch (node.type) { + case "Character": + seq.push(node.value); + break; + + case "CharacterClassRange": + seq.push(node.min.value); + yield seq; + seq = [node.max.value]; + break; + + case "CharacterSet": + case "CharacterClass": // [[]] nesting character class + case "ClassStringDisjunction": // \q{...} + case "ExpressionCharacterClass": // [A--B] + if (seq.length > 0) { + yield seq; + seq = []; + } + break; + + // no default + } + } + + if (seq.length > 0) { + yield seq; + } +} + +const hasCharacterSequence = { + surrogatePairWithoutUFlag(chars) { + return chars.some((c, i) => i !== 0 && isSurrogatePair(chars[i - 1], c)); + }, + + combiningClass(chars) { + return chars.some((c, i) => ( + i !== 0 && + isCombiningCharacter(c) && + !isCombiningCharacter(chars[i - 1]) + )); + }, + + emojiModifier(chars) { + return chars.some((c, i) => ( + i !== 0 && + isEmojiModifier(c) && + !isEmojiModifier(chars[i - 1]) + )); + }, + + regionalIndicatorSymbol(chars) { + return chars.some((c, i) => ( + i !== 0 && + isRegionalIndicatorSymbol(c) && + isRegionalIndicatorSymbol(chars[i - 1]) + )); + }, + + zwj(chars) { + const lastIndex = chars.length - 1; + + return chars.some((c, i) => ( + i !== 0 && + i !== lastIndex && + c === 0x200d && + chars[i - 1] !== 0x200d && + chars[i + 1] !== 0x200d + )); + } +}; + +const kinds = Object.keys(hasCharacterSequence); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow characters which are made with multiple code points in character class syntax", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-misleading-character-class" + }, + + hasSuggestions: true, + + schema: [], + + messages: { + surrogatePairWithoutUFlag: "Unexpected surrogate pair in character class. Use 'u' flag.", + combiningClass: "Unexpected combined character in character class.", + emojiModifier: "Unexpected modified Emoji in character class.", + regionalIndicatorSymbol: "Unexpected national flag in character class.", + zwj: "Unexpected joined character sequence in character class.", + suggestUnicodeFlag: "Add unicode 'u' flag to regex." + } + }, + create(context) { + const sourceCode = context.sourceCode; + const parser = new RegExpParser(); + + /** + * Verify a given regular expression. + * @param {Node} node The node to report. + * @param {string} pattern The regular expression pattern to verify. + * @param {string} flags The flags of the regular expression. + * @param {Function} unicodeFixer Fixer for missing "u" flag. + * @returns {void} + */ + function verify(node, pattern, flags, unicodeFixer) { + let patternNode; + + try { + patternNode = parser.parsePattern( + pattern, + 0, + pattern.length, + { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v") + } + ); + } catch { + + // Ignore regular expressions with syntax errors + return; + } + + const foundKinds = new Set(); + + visitRegExpAST(patternNode, { + onCharacterClassEnter(ccNode) { + for (const chars of iterateCharacterSequence(ccNode.elements)) { + for (const kind of kinds) { + if (hasCharacterSequence[kind](chars)) { + foundKinds.add(kind); + } + } + } + } + }); + + for (const kind of foundKinds) { + let suggest; + + if (kind === "surrogatePairWithoutUFlag") { + suggest = [{ + messageId: "suggestUnicodeFlag", + fix: unicodeFixer + }]; + } + + context.report({ + node, + messageId: kind, + suggest + }); + } + } + + return { + "Literal[regex]"(node) { + verify(node, node.regex.pattern, node.regex.flags, fixer => { + if (!isValidWithUnicodeFlag(context.languageOptions.ecmaVersion, node.regex.pattern)) { + return null; + } + + return fixer.insertTextAfter(node, "u"); + }); + }, + "Program"(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + + /* + * Iterate calls of RegExp. + * E.g., `new RegExp()`, `RegExp()`, `new window.RegExp()`, + * `const {RegExp: a} = window; new a()`, etc... + */ + for (const { node: refNode } of tracker.iterateGlobalReferences({ + RegExp: { [CALL]: true, [CONSTRUCT]: true } + })) { + const [patternNode, flagsNode] = refNode.arguments; + const pattern = getStringIfConstant(patternNode, scope); + const flags = getStringIfConstant(flagsNode, scope); + + if (typeof pattern === "string") { + verify(refNode, pattern, flags || "", fixer => { + + if (!isValidWithUnicodeFlag(context.languageOptions.ecmaVersion, pattern)) { + return null; + } + + if (refNode.arguments.length === 1) { + const penultimateToken = sourceCode.getLastToken(refNode, { skip: 1 }); // skip closing parenthesis + + return fixer.insertTextAfter( + penultimateToken, + astUtils.isCommaToken(penultimateToken) + ? ' "u",' + : ', "u"' + ); + } + + if ((flagsNode.type === "Literal" && typeof flagsNode.value === "string") || flagsNode.type === "TemplateLiteral") { + const range = [flagsNode.range[0], flagsNode.range[1] - 1]; + + return fixer.insertTextAfterRange(range, "u"); + } + + return null; + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-operators.js b/node_modules/eslint/lib/rules/no-mixed-operators.js new file mode 100644 index 0000000..724abe0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-operators.js @@ -0,0 +1,226 @@ +/** + * @fileoverview Rule to disallow mixed binary operators. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const ARITHMETIC_OPERATORS = ["+", "-", "*", "/", "%", "**"]; +const BITWISE_OPERATORS = ["&", "|", "^", "~", "<<", ">>", ">>>"]; +const COMPARISON_OPERATORS = ["==", "!=", "===", "!==", ">", ">=", "<", "<="]; +const LOGICAL_OPERATORS = ["&&", "||"]; +const RELATIONAL_OPERATORS = ["in", "instanceof"]; +const TERNARY_OPERATOR = ["?:"]; +const COALESCE_OPERATOR = ["??"]; +const ALL_OPERATORS = [].concat( + ARITHMETIC_OPERATORS, + BITWISE_OPERATORS, + COMPARISON_OPERATORS, + LOGICAL_OPERATORS, + RELATIONAL_OPERATORS, + TERNARY_OPERATOR, + COALESCE_OPERATOR +); +const DEFAULT_GROUPS = [ + ARITHMETIC_OPERATORS, + BITWISE_OPERATORS, + COMPARISON_OPERATORS, + LOGICAL_OPERATORS, + RELATIONAL_OPERATORS +]; +const TARGET_NODE_TYPE = /^(?:Binary|Logical|Conditional)Expression$/u; + +/** + * Normalizes options. + * @param {Object|undefined} options A options object to normalize. + * @returns {Object} Normalized option object. + */ +function normalizeOptions(options = {}) { + const hasGroups = options.groups && options.groups.length > 0; + const groups = hasGroups ? options.groups : DEFAULT_GROUPS; + const allowSamePrecedence = options.allowSamePrecedence !== false; + + return { + groups, + allowSamePrecedence + }; +} + +/** + * Checks whether any group which includes both given operator exists or not. + * @param {Array} groups A list of groups to check. + * @param {string} left An operator. + * @param {string} right Another operator. + * @returns {boolean} `true` if such group existed. + */ +function includesBothInAGroup(groups, left, right) { + return groups.some(group => group.includes(left) && group.includes(right)); +} + +/** + * Checks whether the given node is a conditional expression and returns the test node else the left node. + * @param {ASTNode} node A node which can be a BinaryExpression or a LogicalExpression node. + * This parent node can be BinaryExpression, LogicalExpression + * , or a ConditionalExpression node + * @returns {ASTNode} node the appropriate node(left or test). + */ +function getChildNode(node) { + return node.type === "ConditionalExpression" ? node.test : node.left; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow mixed binary operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-mixed-operators" + }, + + schema: [ + { + type: "object", + properties: { + groups: { + type: "array", + items: { + type: "array", + items: { enum: ALL_OPERATORS }, + minItems: 2, + uniqueItems: true + }, + uniqueItems: true + }, + allowSamePrecedence: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedMixedOperator: "Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'. Use parentheses to clarify the intended order of operations." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = normalizeOptions(context.options[0]); + + /** + * Checks whether a given node should be ignored by options or not. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {boolean} `true` if the node should be ignored. + */ + function shouldIgnore(node) { + const a = node; + const b = node.parent; + + return ( + !includesBothInAGroup(options.groups, a.operator, b.type === "ConditionalExpression" ? "?:" : b.operator) || + ( + options.allowSamePrecedence && + astUtils.getPrecedence(a) === astUtils.getPrecedence(b) + ) + ); + } + + /** + * Checks whether the operator of a given node is mixed with parent + * node's operator or not. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {boolean} `true` if the node was mixed. + */ + function isMixedWithParent(node) { + + return ( + node.operator !== node.parent.operator && + !astUtils.isParenthesised(sourceCode, node) + ); + } + + /** + * Gets the operator token of a given node. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. + * @returns {Token} The operator token of the node. + */ + function getOperatorToken(node) { + return sourceCode.getTokenAfter(getChildNode(node), astUtils.isNotClosingParenToken); + } + + /** + * Reports both the operator of a given node and the operator of the + * parent node. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {void} + */ + function reportBothOperators(node) { + const parent = node.parent; + const left = (getChildNode(parent) === node) ? node : parent; + const right = (getChildNode(parent) !== node) ? node : parent; + const data = { + leftOperator: left.operator || "?:", + rightOperator: right.operator || "?:" + }; + + context.report({ + node: left, + loc: getOperatorToken(left).loc, + messageId: "unexpectedMixedOperator", + data + }); + context.report({ + node: right, + loc: getOperatorToken(right).loc, + messageId: "unexpectedMixedOperator", + data + }); + } + + /** + * Checks between the operator of this node and the operator of the + * parent node. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function check(node) { + if ( + TARGET_NODE_TYPE.test(node.parent.type) && + isMixedWithParent(node) && + !shouldIgnore(node) + ) { + reportBothOperators(node); + } + } + + return { + BinaryExpression: check, + LogicalExpression: check + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-requires.js b/node_modules/eslint/lib/rules/no-mixed-requires.js new file mode 100644 index 0000000..9e7b803 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-requires.js @@ -0,0 +1,238 @@ +/** + * @fileoverview Rule to enforce grouped require statements for Node.JS + * @author Raphael Pigulla + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Disallow `require` calls to be mixed with regular variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-mixed-requires" + }, + + schema: [ + { + oneOf: [ + { + type: "boolean" + }, + { + type: "object", + properties: { + grouping: { + type: "boolean" + }, + allowCall: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + noMixRequire: "Do not mix 'require' and other declarations.", + noMixCoreModuleFileComputed: "Do not mix core, module, file and computed requires." + } + }, + + create(context) { + + const options = context.options[0]; + let grouping = false, + allowCall = false; + + if (typeof options === "object") { + grouping = options.grouping; + allowCall = options.allowCall; + } else { + grouping = !!options; + } + + /** + * Returns the list of built-in modules. + * @returns {string[]} An array of built-in Node.js modules. + */ + function getBuiltinModules() { + + /* + * This list is generated using: + * `require("repl")._builtinLibs.concat('repl').sort()` + * This particular list is as per nodejs v0.12.2 and iojs v0.7.1 + */ + return [ + "assert", "buffer", "child_process", "cluster", "crypto", + "dgram", "dns", "domain", "events", "fs", "http", "https", + "net", "os", "path", "punycode", "querystring", "readline", + "repl", "smalloc", "stream", "string_decoder", "tls", "tty", + "url", "util", "v8", "vm", "zlib" + ]; + } + + const BUILTIN_MODULES = getBuiltinModules(); + + const DECL_REQUIRE = "require", + DECL_UNINITIALIZED = "uninitialized", + DECL_OTHER = "other"; + + const REQ_CORE = "core", + REQ_FILE = "file", + REQ_MODULE = "module", + REQ_COMPUTED = "computed"; + + /** + * Determines the type of a declaration statement. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The type of declaration represented by the expression. + */ + function getDeclarationType(initExpression) { + if (!initExpression) { + + // "var x;" + return DECL_UNINITIALIZED; + } + + if (initExpression.type === "CallExpression" && + initExpression.callee.type === "Identifier" && + initExpression.callee.name === "require" + ) { + + // "var x = require('util');" + return DECL_REQUIRE; + } + if (allowCall && + initExpression.type === "CallExpression" && + initExpression.callee.type === "CallExpression" + ) { + + // "var x = require('diagnose')('sub-module');" + return getDeclarationType(initExpression.callee); + } + if (initExpression.type === "MemberExpression") { + + // "var x = require('glob').Glob;" + return getDeclarationType(initExpression.object); + } + + // "var x = 42;" + return DECL_OTHER; + } + + /** + * Determines the type of module that is loaded via require. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The module type. + */ + function inferModuleType(initExpression) { + if (initExpression.type === "MemberExpression") { + + // "var x = require('glob').Glob;" + return inferModuleType(initExpression.object); + } + if (initExpression.arguments.length === 0) { + + // "var x = require();" + return REQ_COMPUTED; + } + + const arg = initExpression.arguments[0]; + + if (arg.type !== "Literal" || typeof arg.value !== "string") { + + // "var x = require(42);" + return REQ_COMPUTED; + } + + if (BUILTIN_MODULES.includes(arg.value)) { + + // "var fs = require('fs');" + return REQ_CORE; + } + if (/^\.{0,2}\//u.test(arg.value)) { + + // "var utils = require('./utils');" + return REQ_FILE; + } + + // "var async = require('async');" + return REQ_MODULE; + + } + + /** + * Check if the list of variable declarations is mixed, i.e. whether it + * contains both require and other declarations. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are mixed, false if not. + */ + function isMixed(declarations) { + const contains = {}; + + declarations.forEach(declaration => { + const type = getDeclarationType(declaration.init); + + contains[type] = true; + }); + + return !!( + contains[DECL_REQUIRE] && + (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER]) + ); + } + + /** + * Check if all require declarations in the given list are of the same + * type. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are grouped, false if not. + */ + function isGrouped(declarations) { + const found = {}; + + declarations.forEach(declaration => { + if (getDeclarationType(declaration.init) === DECL_REQUIRE) { + found[inferModuleType(declaration.init)] = true; + } + }); + + return Object.keys(found).length <= 1; + } + + + return { + + VariableDeclaration(node) { + + if (isMixed(node.declarations)) { + context.report({ + node, + messageId: "noMixRequire" + }); + } else if (grouping && !isGrouped(node.declarations)) { + context.report({ + node, + messageId: "noMixCoreModuleFileComputed" + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js new file mode 100644 index 0000000..a18e4f3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js @@ -0,0 +1,113 @@ +/** + * @fileoverview Disallow mixed spaces and tabs for indentation + * @author Jary Niebur + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow mixed spaces and tabs for indentation", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-mixed-spaces-and-tabs" + }, + + schema: [ + { + enum: ["smart-tabs", true, false] + } + ], + + messages: { + mixedSpacesAndTabs: "Mixed spaces and tabs." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + let smartTabs; + + switch (context.options[0]) { + case true: // Support old syntax, maybe add deprecation warning here + case "smart-tabs": + smartTabs = true; + break; + default: + smartTabs = false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program:exit"(node) { + const lines = sourceCode.lines, + comments = sourceCode.getAllComments(), + ignoredCommentLines = new Set(); + + // Add all lines except the first ones. + comments.forEach(comment => { + for (let i = comment.loc.start.line + 1; i <= comment.loc.end.line; i++) { + ignoredCommentLines.add(i); + } + }); + + /* + * At least one space followed by a tab + * or the reverse before non-tab/-space + * characters begin. + */ + let regex = /^(?=( +|\t+))\1(?:\t| )/u; + + if (smartTabs) { + + /* + * At least one space followed by a tab + * before non-tab/-space characters begin. + */ + regex = /^(?=(\t*))\1(?=( +))\2\t/u; + } + + lines.forEach((line, i) => { + const match = regex.exec(line); + + if (match) { + const lineNumber = i + 1; + const loc = { + start: { + line: lineNumber, + column: match[0].length - 2 + }, + end: { + line: lineNumber, + column: match[0].length + } + }; + + if (!ignoredCommentLines.has(lineNumber)) { + const containingNode = sourceCode.getNodeByRangeIndex(sourceCode.getIndexFromLoc(loc.start)); + + if (!(containingNode && ["Literal", "TemplateElement"].includes(containingNode.type))) { + context.report({ + node, + loc, + messageId: "mixedSpacesAndTabs" + }); + } + } + } + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-multi-assign.js b/node_modules/eslint/lib/rules/no-multi-assign.js new file mode 100644 index 0000000..a7a50c1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-assign.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Rule to check use of chained assignment expressions + * @author Stewart Rand + */ + +"use strict"; + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow use of chained assignment expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multi-assign" + }, + + schema: [{ + type: "object", + properties: { + ignoreNonDeclaration: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + + messages: { + unexpectedChain: "Unexpected chained assignment." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + const options = context.options[0] || { + ignoreNonDeclaration: false + }; + const selectors = [ + "VariableDeclarator > AssignmentExpression.init", + "PropertyDefinition > AssignmentExpression.value" + ]; + + if (!options.ignoreNonDeclaration) { + selectors.push("AssignmentExpression > AssignmentExpression.right"); + } + + return { + [selectors](node) { + context.report({ + node, + messageId: "unexpectedChain" + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-multi-spaces.js b/node_modules/eslint/lib/rules/no-multi-spaces.js new file mode 100644 index 0000000..62074e6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-spaces.js @@ -0,0 +1,138 @@ +/** + * @fileoverview Disallow use of multiple spaces. + * @author Nicholas C. Zakas + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow multiple spaces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multi-spaces" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "object", + patternProperties: { + "^([A-Z][a-z]*)+$": { + type: "boolean" + } + }, + additionalProperties: false + }, + ignoreEOLComments: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + multipleSpaces: "Multiple spaces found before '{{displayValue}}'." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = context.options[0] || {}; + const ignoreEOLComments = options.ignoreEOLComments; + const exceptions = Object.assign({ Property: true }, options.exceptions); + const hasExceptions = Object.keys(exceptions).some(key => exceptions[key]); + + /** + * Formats value of given comment token for error message by truncating its length. + * @param {Token} token comment token + * @returns {string} formatted value + * @private + */ + function formatReportedCommentValue(token) { + const valueLines = token.value.split("\n"); + const value = valueLines[0]; + const formattedValue = `${value.slice(0, 12)}...`; + + return valueLines.length === 1 && value.length <= 12 ? value : formattedValue; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + sourceCode.tokensAndComments.forEach((leftToken, leftIndex, tokensAndComments) => { + if (leftIndex === tokensAndComments.length - 1) { + return; + } + const rightToken = tokensAndComments[leftIndex + 1]; + + // Ignore tokens that don't have 2 spaces between them or are on different lines + if ( + !sourceCode.text.slice(leftToken.range[1], rightToken.range[0]).includes(" ") || + leftToken.loc.end.line < rightToken.loc.start.line + ) { + return; + } + + // Ignore comments that are the last token on their line if `ignoreEOLComments` is active. + if ( + ignoreEOLComments && + astUtils.isCommentToken(rightToken) && + ( + leftIndex === tokensAndComments.length - 2 || + rightToken.loc.end.line < tokensAndComments[leftIndex + 2].loc.start.line + ) + ) { + return; + } + + // Ignore tokens that are in a node in the "exceptions" object + if (hasExceptions) { + const parentNode = sourceCode.getNodeByRangeIndex(rightToken.range[0] - 1); + + if (parentNode && exceptions[parentNode.type]) { + return; + } + } + + let displayValue; + + if (rightToken.type === "Block") { + displayValue = `/*${formatReportedCommentValue(rightToken)}*/`; + } else if (rightToken.type === "Line") { + displayValue = `//${formatReportedCommentValue(rightToken)}`; + } else { + displayValue = rightToken.value; + } + + context.report({ + node: rightToken, + loc: { start: leftToken.loc.end, end: rightToken.loc.start }, + messageId: "multipleSpaces", + data: { displayValue }, + fix: fixer => fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], " ") + }); + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-multi-str.js b/node_modules/eslint/lib/rules/no-multi-str.js new file mode 100644 index 0000000..8011729 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-str.js @@ -0,0 +1,65 @@ +/** + * @fileoverview Rule to flag when using multiline strings + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow multiline strings", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multi-str" + }, + + schema: [], + + messages: { + multilineString: "Multiline support is limited to browsers supporting ES5 only." + } + }, + + create(context) { + + /** + * Determines if a given node is part of JSX syntax. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a JSX node, false if not. + * @private + */ + function isJSXElement(node) { + return node.type.indexOf("JSX") === 0; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + Literal(node) { + if (astUtils.LINEBREAK_MATCHER.test(node.raw) && !isJSXElement(node.parent)) { + context.report({ + node, + messageId: "multilineString" + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-multiple-empty-lines.js b/node_modules/eslint/lib/rules/no-multiple-empty-lines.js new file mode 100644 index 0000000..2c0fbf2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multiple-empty-lines.js @@ -0,0 +1,151 @@ +/** + * @fileoverview Disallows multiple blank lines. + * implementation adapted from the no-trailing-spaces rule. + * @author Greg Cochard + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow multiple empty lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multiple-empty-lines" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0 + }, + maxEOF: { + type: "integer", + minimum: 0 + }, + maxBOF: { + type: "integer", + minimum: 0 + } + }, + required: ["max"], + additionalProperties: false + } + ], + + messages: { + blankBeginningOfFile: "Too many blank lines at the beginning of file. Max of {{max}} allowed.", + blankEndOfFile: "Too many blank lines at the end of file. Max of {{max}} allowed.", + consecutiveBlank: "More than {{max}} blank {{pluralizedLines}} not allowed." + } + }, + + create(context) { + + // Use options.max or 2 as default + let max = 2, + maxEOF = max, + maxBOF = max; + + if (context.options.length) { + max = context.options[0].max; + maxEOF = typeof context.options[0].maxEOF !== "undefined" ? context.options[0].maxEOF : max; + maxBOF = typeof context.options[0].maxBOF !== "undefined" ? context.options[0].maxBOF : max; + } + + const sourceCode = context.sourceCode; + + // Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue + const allLines = sourceCode.lines[sourceCode.lines.length - 1] === "" ? sourceCode.lines.slice(0, -1) : sourceCode.lines; + const templateLiteralLines = new Set(); + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + TemplateLiteral(node) { + node.quasis.forEach(literalPart => { + + // Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines. + for (let ignoredLine = literalPart.loc.start.line; ignoredLine < literalPart.loc.end.line; ignoredLine++) { + templateLiteralLines.add(ignoredLine); + } + }); + }, + "Program:exit"(node) { + return allLines + + // Given a list of lines, first get a list of line numbers that are non-empty. + .reduce((nonEmptyLineNumbers, line, index) => { + if (line.trim() || templateLiteralLines.has(index + 1)) { + nonEmptyLineNumbers.push(index + 1); + } + return nonEmptyLineNumbers; + }, []) + + // Add a value at the end to allow trailing empty lines to be checked. + .concat(allLines.length + 1) + + // Given two line numbers of non-empty lines, report the lines between if the difference is too large. + .reduce((lastLineNumber, lineNumber) => { + let messageId, maxAllowed; + + if (lastLineNumber === 0) { + messageId = "blankBeginningOfFile"; + maxAllowed = maxBOF; + } else if (lineNumber === allLines.length + 1) { + messageId = "blankEndOfFile"; + maxAllowed = maxEOF; + } else { + messageId = "consecutiveBlank"; + maxAllowed = max; + } + + if (lineNumber - lastLineNumber - 1 > maxAllowed) { + context.report({ + node, + loc: { + start: { line: lastLineNumber + maxAllowed + 1, column: 0 }, + end: { line: lineNumber, column: 0 } + }, + messageId, + data: { + max: maxAllowed, + pluralizedLines: maxAllowed === 1 ? "line" : "lines" + }, + fix(fixer) { + const rangeStart = sourceCode.getIndexFromLoc({ line: lastLineNumber + 1, column: 0 }); + + /* + * The end of the removal range is usually the start index of the next line. + * However, at the end of the file there is no next line, so the end of the + * range is just the length of the text. + */ + const lineNumberAfterRemovedLines = lineNumber - maxAllowed; + const rangeEnd = lineNumberAfterRemovedLines <= allLines.length + ? sourceCode.getIndexFromLoc({ line: lineNumberAfterRemovedLines, column: 0 }) + : sourceCode.text.length; + + return fixer.removeRange([rangeStart, rangeEnd]); + } + }); + } + + return lineNumber; + }, 0); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-native-reassign.js b/node_modules/eslint/lib/rules/no-native-reassign.js new file mode 100644 index 0000000..e3fed44 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-native-reassign.js @@ -0,0 +1,98 @@ +/** + * @fileoverview Rule to disallow assignments to native objects or read-only global variables + * @author Ilya Volodin + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow assignments to native objects or read-only global variables", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-native-reassign" + }, + + deprecated: true, + + replacedBy: ["no-global-assign"], + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { type: "string" }, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + nativeReassign: "Read-only global '{{name}}' should not be modified." + } + }, + + create(context) { + const config = context.options[0]; + const exceptions = (config && config.exceptions) || []; + const sourceCode = context.sourceCode; + + /** + * Reports write references. + * @param {Reference} reference A reference to check. + * @param {int} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if (reference.init === false && + reference.isWrite() && + + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + context.report({ + node: identifier, + messageId: "nativeReassign", + data: identifier + }); + } + } + + /** + * Reports write references if a given variable is read-only builtin. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if (variable.writeable === false && !exceptions.includes(variable.name)) { + variable.references.forEach(checkReference); + } + } + + return { + Program(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.variables.forEach(checkVariable); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-negated-condition.js b/node_modules/eslint/lib/rules/no-negated-condition.js new file mode 100644 index 0000000..3cb7590 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-negated-condition.js @@ -0,0 +1,95 @@ +/** + * @fileoverview Rule to disallow a negated condition + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow negated conditions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-negated-condition" + }, + + schema: [], + + messages: { + unexpectedNegated: "Unexpected negated condition." + } + }, + + create(context) { + + /** + * Determines if a given node is an if-else without a condition on the else + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node has an else without an if. + * @private + */ + function hasElseWithoutCondition(node) { + return node.alternate && node.alternate.type !== "IfStatement"; + } + + /** + * Determines if a given node is a negated unary expression + * @param {Object} test The test object to check. + * @returns {boolean} True if the node is a negated unary expression. + * @private + */ + function isNegatedUnaryExpression(test) { + return test.type === "UnaryExpression" && test.operator === "!"; + } + + /** + * Determines if a given node is a negated binary expression + * @param {Test} test The test to check. + * @returns {boolean} True if the node is a negated binary expression. + * @private + */ + function isNegatedBinaryExpression(test) { + return test.type === "BinaryExpression" && + (test.operator === "!=" || test.operator === "!=="); + } + + /** + * Determines if a given node has a negated if expression + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node has a negated if expression. + * @private + */ + function isNegatedIf(node) { + return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test); + } + + return { + IfStatement(node) { + if (!hasElseWithoutCondition(node)) { + return; + } + + if (isNegatedIf(node)) { + context.report({ + node, + messageId: "unexpectedNegated" + }); + } + }, + ConditionalExpression(node) { + if (isNegatedIf(node)) { + context.report({ + node, + messageId: "unexpectedNegated" + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-negated-in-lhs.js b/node_modules/eslint/lib/rules/no-negated-in-lhs.js new file mode 100644 index 0000000..7a50be7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-negated-in-lhs.js @@ -0,0 +1,46 @@ +/** + * @fileoverview A rule to disallow negated left operands of the `in` operator + * @author Michael Ficarra + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow negating the left operand in `in` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-negated-in-lhs" + }, + + replacedBy: ["no-unsafe-negation"], + + deprecated: true, + schema: [], + + messages: { + negatedLHS: "The 'in' expression's left operand is negated." + } + }, + + create(context) { + + return { + + BinaryExpression(node) { + if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") { + context.report({ node, messageId: "negatedLHS" }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-nested-ternary.js b/node_modules/eslint/lib/rules/no-nested-ternary.js new file mode 100644 index 0000000..faf8041 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-nested-ternary.js @@ -0,0 +1,44 @@ +/** + * @fileoverview Rule to flag nested ternary expressions + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow nested ternary expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-nested-ternary" + }, + + schema: [], + + messages: { + noNestedTernary: "Do not nest ternary expressions." + } + }, + + create(context) { + + return { + ConditionalExpression(node) { + if (node.alternate.type === "ConditionalExpression" || + node.consequent.type === "ConditionalExpression") { + context.report({ + node, + messageId: "noNestedTernary" + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-new-func.js b/node_modules/eslint/lib/rules/no-new-func.js new file mode 100644 index 0000000..d58b2d7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-func.js @@ -0,0 +1,87 @@ +/** + * @fileoverview Rule to flag when using new Function + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const callMethods = new Set(["apply", "bind", "call"]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `new` operators with the `Function` object", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-func" + }, + + schema: [], + + messages: { + noFunctionConstructor: "The Function constructor is eval." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const variable = globalScope.set.get("Function"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const { parent } = idNode; + let evalNode; + + if (parent) { + if (idNode === parent.callee && ( + parent.type === "NewExpression" || + parent.type === "CallExpression" + )) { + evalNode = parent; + } else if ( + parent.type === "MemberExpression" && + idNode === parent.object && + callMethods.has(astUtils.getStaticPropertyName(parent)) + ) { + const maybeCallee = parent.parent.type === "ChainExpression" ? parent.parent : parent; + + if (maybeCallee.parent.type === "CallExpression" && maybeCallee.parent.callee === maybeCallee) { + evalNode = maybeCallee.parent; + } + } + } + + if (evalNode) { + context.report({ + node: evalNode, + messageId: "noFunctionConstructor" + }); + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js b/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js new file mode 100644 index 0000000..ee70d28 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js @@ -0,0 +1,66 @@ +/** + * @fileoverview Rule to disallow use of the new operator with global non-constructor functions + * @author Sosuke Suzuki + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const nonConstructorGlobalFunctionNames = ["Symbol", "BigInt"]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow `new` operators with global non-constructor functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-native-nonconstructor" + }, + + schema: [], + + messages: { + noNewNonconstructor: "`{{name}}` cannot be called as a constructor." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + for (const nonConstructorName of nonConstructorGlobalFunctionNames) { + const variable = globalScope.set.get(nonConstructorName); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const parent = idNode.parent; + + if (parent && parent.type === "NewExpression" && parent.callee === idNode) { + context.report({ + node: idNode, + messageId: "noNewNonconstructor", + data: { name: nonConstructorName } + }); + } + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-new-object.js b/node_modules/eslint/lib/rules/no-new-object.js new file mode 100644 index 0000000..08a482b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-object.js @@ -0,0 +1,60 @@ +/** + * @fileoverview A rule to disallow calls to the Object constructor + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `Object` constructors", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-object" + }, + + schema: [], + + messages: { + preferLiteral: "The object literal notation {} is preferable." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + return { + NewExpression(node) { + const variable = astUtils.getVariableByName( + sourceCode.getScope(node), + node.callee.name + ); + + if (variable && variable.identifiers.length > 0) { + return; + } + + if (node.callee.name === "Object") { + context.report({ + node, + messageId: "preferLiteral" + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-new-require.js b/node_modules/eslint/lib/rules/no-new-require.js new file mode 100644 index 0000000..6abfc17 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-require.js @@ -0,0 +1,50 @@ +/** + * @fileoverview Rule to disallow use of new operator with the `require` function + * @author Wil Moore III + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Disallow `new` operators with calls to `require`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-require" + }, + + schema: [], + + messages: { + noNewRequire: "Unexpected use of new with require." + } + }, + + create(context) { + + return { + + NewExpression(node) { + if (node.callee.type === "Identifier" && node.callee.name === "require") { + context.report({ + node, + messageId: "noNewRequire" + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-new-symbol.js b/node_modules/eslint/lib/rules/no-new-symbol.js new file mode 100644 index 0000000..9983022 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-symbol.js @@ -0,0 +1,56 @@ +/** + * @fileoverview Rule to disallow use of the new operator with the `Symbol` object + * @author Alberto Rodríguez + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow `new` operators with the `Symbol` object", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-new-symbol" + }, + + schema: [], + + messages: { + noNewSymbol: "`Symbol` cannot be called as a constructor." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const variable = globalScope.set.get("Symbol"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const parent = idNode.parent; + + if (parent && parent.type === "NewExpression" && parent.callee === idNode) { + context.report({ + node: idNode, + messageId: "noNewSymbol" + }); + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-new-wrappers.js b/node_modules/eslint/lib/rules/no-new-wrappers.js new file mode 100644 index 0000000..5050a98 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-wrappers.js @@ -0,0 +1,60 @@ +/** + * @fileoverview Rule to flag when using constructor for wrapper objects + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getVariableByName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `new` operators with the `String`, `Number`, and `Boolean` objects", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-wrappers" + }, + + schema: [], + + messages: { + noConstructor: "Do not use {{fn}} as a constructor." + } + }, + + create(context) { + const { sourceCode } = context; + + return { + + NewExpression(node) { + const wrapperObjects = ["String", "Number", "Boolean"]; + const { name } = node.callee; + + if (wrapperObjects.includes(name)) { + const variable = getVariableByName(sourceCode.getScope(node), name); + + if (variable && variable.identifiers.length === 0) { + context.report({ + node, + messageId: "noConstructor", + data: { fn: name } + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-new.js b/node_modules/eslint/lib/rules/no-new.js new file mode 100644 index 0000000..9e20bad --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to flag statements with function invocation preceded by + * "new" and not part of assignment + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `new` operators outside of assignments or comparisons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new" + }, + + schema: [], + + messages: { + noNewStatement: "Do not use 'new' for side effects." + } + }, + + create(context) { + + return { + "ExpressionStatement > NewExpression"(node) { + context.report({ + node: node.parent, + messageId: "noNewStatement" + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js b/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js new file mode 100644 index 0000000..5939390 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js @@ -0,0 +1,148 @@ +/** + * @fileoverview Rule to disallow `\8` and `\9` escape sequences in string literals. + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const QUICK_TEST_REGEX = /\\[89]/u; + +/** + * Returns unicode escape sequence that represents the given character. + * @param {string} character A single code unit. + * @returns {string} "\uXXXX" sequence. + */ +function getUnicodeEscape(character) { + return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `\\8` and `\\9` escape sequences in string literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-nonoctal-decimal-escape" + }, + + hasSuggestions: true, + + schema: [], + + messages: { + decimalEscape: "Don't use '{{decimalEscape}}' escape sequence.", + + // suggestions + refactor: "Replace '{{original}}' with '{{replacement}}'. This maintains the current functionality.", + escapeBackslash: "Replace '{{original}}' with '{{replacement}}' to include the actual backslash character." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Creates a new Suggestion object. + * @param {string} messageId "refactor" or "escapeBackslash". + * @param {int[]} range The range to replace. + * @param {string} replacement New text for the range. + * @returns {Object} Suggestion + */ + function createSuggestion(messageId, range, replacement) { + return { + messageId, + data: { + original: sourceCode.getText().slice(...range), + replacement + }, + fix(fixer) { + return fixer.replaceTextRange(range, replacement); + } + }; + } + + return { + Literal(node) { + if (typeof node.value !== "string") { + return; + } + + if (!QUICK_TEST_REGEX.test(node.raw)) { + return; + } + + const regex = /(?:[^\\]|(?\\.))*?(?\\[89])/suy; + let match; + + while ((match = regex.exec(node.raw))) { + const { previousEscape, decimalEscape } = match.groups; + const decimalEscapeRangeEnd = node.range[0] + match.index + match[0].length; + const decimalEscapeRangeStart = decimalEscapeRangeEnd - decimalEscape.length; + const decimalEscapeRange = [decimalEscapeRangeStart, decimalEscapeRangeEnd]; + const suggest = []; + + // When `regex` is matched, `previousEscape` can only capture characters adjacent to `decimalEscape` + if (previousEscape === "\\0") { + + /* + * Now we have a NULL escape "\0" immediately followed by a decimal escape, e.g.: "\0\8". + * Fixing this to "\08" would turn "\0" into a legacy octal escape. To avoid producing + * an octal escape while fixing a decimal escape, we provide different suggestions. + */ + suggest.push( + createSuggestion( // "\0\8" -> "\u00008" + "refactor", + [decimalEscapeRangeStart - previousEscape.length, decimalEscapeRangeEnd], + `${getUnicodeEscape("\0")}${decimalEscape[1]}` + ), + createSuggestion( // "\8" -> "\u0038" + "refactor", + decimalEscapeRange, + getUnicodeEscape(decimalEscape[1]) + ) + ); + } else { + suggest.push( + createSuggestion( // "\8" -> "8" + "refactor", + decimalEscapeRange, + decimalEscape[1] + ) + ); + } + + suggest.push( + createSuggestion( // "\8" -> "\\8" + "escapeBackslash", + decimalEscapeRange, + `\\${decimalEscape}` + ) + ); + + context.report({ + node, + loc: { + start: sourceCode.getLocFromIndex(decimalEscapeRangeStart), + end: sourceCode.getLocFromIndex(decimalEscapeRangeEnd) + }, + messageId: "decimalEscape", + data: { + decimalEscape + }, + suggest + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-obj-calls.js b/node_modules/eslint/lib/rules/no-obj-calls.js new file mode 100644 index 0000000..ee767ea --- /dev/null +++ b/node_modules/eslint/lib/rules/no-obj-calls.js @@ -0,0 +1,86 @@ +/** + * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { CALL, CONSTRUCT, ReferenceTracker } = require("@eslint-community/eslint-utils"); +const getPropertyName = require("./utils/ast-utils").getStaticPropertyName; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const nonCallableGlobals = ["Atomics", "JSON", "Math", "Reflect", "Intl"]; + +/** + * Returns the name of the node to report + * @param {ASTNode} node A node to report + * @returns {string} name to report + */ +function getReportNodeName(node) { + if (node.type === "ChainExpression") { + return getReportNodeName(node.expression); + } + if (node.type === "MemberExpression") { + return getPropertyName(node); + } + return node.name; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow calling global object properties as functions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-obj-calls" + }, + + schema: [], + + messages: { + unexpectedCall: "'{{name}}' is not a function.", + unexpectedRefCall: "'{{name}}' is reference to '{{ref}}', which is not a function." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = {}; + + for (const g of nonCallableGlobals) { + traceMap[g] = { + [CALL]: true, + [CONSTRUCT]: true + }; + } + + for (const { node: refNode, path } of tracker.iterateGlobalReferences(traceMap)) { + const name = getReportNodeName(refNode.callee); + const ref = path[0]; + const messageId = name === ref ? "unexpectedCall" : "unexpectedRefCall"; + + context.report({ node: refNode, messageId, data: { name, ref } }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-octal-escape.js b/node_modules/eslint/lib/rules/no-octal-escape.js new file mode 100644 index 0000000..6924d54 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-octal-escape.js @@ -0,0 +1,56 @@ +/** + * @fileoverview Rule to flag octal escape sequences in string literals. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow octal escape sequences in string literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-octal-escape" + }, + + schema: [], + + messages: { + octalEscapeSequence: "Don't use octal: '\\{{sequence}}'. Use '\\u....' instead." + } + }, + + create(context) { + + return { + + Literal(node) { + if (typeof node.value !== "string") { + return; + } + + // \0 represents a valid NULL character if it isn't followed by a digit. + const match = node.raw.match( + /^(?:[^\\]|\\.)*?\\([0-3][0-7]{1,2}|[4-7][0-7]|0(?=[89])|[1-7])/su + ); + + if (match) { + context.report({ + node, + messageId: "octalEscapeSequence", + data: { sequence: match[1] } + }); + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-octal.js b/node_modules/eslint/lib/rules/no-octal.js new file mode 100644 index 0000000..dc02769 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-octal.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Rule to flag when initializing octal literal + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow octal literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-octal" + }, + + schema: [], + + messages: { + noOctal: "Octal literals should not be used." + } + }, + + create(context) { + + return { + + Literal(node) { + if (typeof node.value === "number" && /^0[0-9]/u.test(node.raw)) { + context.report({ + node, + messageId: "noOctal" + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-param-reassign.js b/node_modules/eslint/lib/rules/no-param-reassign.js new file mode 100644 index 0000000..607cafd --- /dev/null +++ b/node_modules/eslint/lib/rules/no-param-reassign.js @@ -0,0 +1,230 @@ +/** + * @fileoverview Disallow reassignment of function parameters. + * @author Nat Burns + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const stopNodePattern = /(?:Statement|Declaration|Function(?:Expression)?|Program)$/u; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow reassigning `function` parameters", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-param-reassign" + }, + + schema: [ + { + oneOf: [ + { + type: "object", + properties: { + props: { + enum: [false] + } + }, + additionalProperties: false + }, + { + type: "object", + properties: { + props: { + enum: [true] + }, + ignorePropertyModificationsFor: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + }, + ignorePropertyModificationsForRegex: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + assignmentToFunctionParam: "Assignment to function parameter '{{name}}'.", + assignmentToFunctionParamProp: "Assignment to property of function parameter '{{name}}'." + } + }, + + create(context) { + const props = context.options[0] && context.options[0].props; + const ignoredPropertyAssignmentsFor = context.options[0] && context.options[0].ignorePropertyModificationsFor || []; + const ignoredPropertyAssignmentsForRegex = context.options[0] && context.options[0].ignorePropertyModificationsForRegex || []; + const sourceCode = context.sourceCode; + + /** + * Checks whether or not the reference modifies properties of its variable. + * @param {Reference} reference A reference to check. + * @returns {boolean} Whether or not the reference modifies properties of its variable. + */ + function isModifyingProp(reference) { + let node = reference.identifier; + let parent = node.parent; + + while (parent && (!stopNodePattern.test(parent.type) || + parent.type === "ForInStatement" || parent.type === "ForOfStatement")) { + switch (parent.type) { + + // e.g. foo.a = 0; + case "AssignmentExpression": + return parent.left === node; + + // e.g. ++foo.a; + case "UpdateExpression": + return true; + + // e.g. delete foo.a; + case "UnaryExpression": + if (parent.operator === "delete") { + return true; + } + break; + + // e.g. for (foo.a in b) {} + case "ForInStatement": + case "ForOfStatement": + if (parent.left === node) { + return true; + } + + // this is a stop node for parent.right and parent.body + return false; + + // EXCLUDES: e.g. cache.get(foo.a).b = 0; + case "CallExpression": + if (parent.callee !== node) { + return false; + } + break; + + // EXCLUDES: e.g. cache[foo.a] = 0; + case "MemberExpression": + if (parent.property === node) { + return false; + } + break; + + // EXCLUDES: e.g. ({ [foo]: a }) = bar; + case "Property": + if (parent.key === node) { + return false; + } + + break; + + // EXCLUDES: e.g. (foo ? a : b).c = bar; + case "ConditionalExpression": + if (parent.test === node) { + return false; + } + + break; + + // no default + } + + node = parent; + parent = node.parent; + } + + return false; + } + + /** + * Tests that an identifier name matches any of the ignored property assignments. + * First we test strings in ignoredPropertyAssignmentsFor. + * Then we instantiate and test RegExp objects from ignoredPropertyAssignmentsForRegex strings. + * @param {string} identifierName A string that describes the name of an identifier to + * ignore property assignments for. + * @returns {boolean} Whether the string matches an ignored property assignment regular expression or not. + */ + function isIgnoredPropertyAssignment(identifierName) { + return ignoredPropertyAssignmentsFor.includes(identifierName) || + ignoredPropertyAssignmentsForRegex.some(ignored => new RegExp(ignored, "u").test(identifierName)); + } + + /** + * Reports a reference if is non initializer and writable. + * @param {Reference} reference A reference to check. + * @param {int} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if (identifier && + !reference.init && + + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + if (reference.isWrite()) { + context.report({ + node: identifier, + messageId: "assignmentToFunctionParam", + data: { name: identifier.name } + }); + } else if (props && isModifyingProp(reference) && !isIgnoredPropertyAssignment(identifier.name)) { + context.report({ + node: identifier, + messageId: "assignmentToFunctionParamProp", + data: { name: identifier.name } + }); + } + } + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if (variable.defs[0].type === "Parameter") { + variable.references.forEach(checkReference); + } + } + + /** + * Checks parameters of a given function node. + * @param {ASTNode} node A function node to check. + * @returns {void} + */ + function checkForFunction(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + + // `:exit` is needed for the `node.parent` property of identifier nodes. + "FunctionDeclaration:exit": checkForFunction, + "FunctionExpression:exit": checkForFunction, + "ArrowFunctionExpression:exit": checkForFunction + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-path-concat.js b/node_modules/eslint/lib/rules/no-path-concat.js new file mode 100644 index 0000000..2e4a3a2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-path-concat.js @@ -0,0 +1,64 @@ +/** + * @fileoverview Disallow string concatenation when using __dirname and __filename + * @author Nicholas C. Zakas + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Disallow string concatenation with `__dirname` and `__filename`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-path-concat" + }, + + schema: [], + + messages: { + usePathFunctions: "Use path.join() or path.resolve() instead of + to create paths." + } + }, + + create(context) { + + const MATCHER = /^__(?:dir|file)name$/u; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + BinaryExpression(node) { + + const left = node.left, + right = node.right; + + if (node.operator === "+" && + ((left.type === "Identifier" && MATCHER.test(left.name)) || + (right.type === "Identifier" && MATCHER.test(right.name))) + ) { + + context.report({ + node, + messageId: "usePathFunctions" + }); + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-plusplus.js b/node_modules/eslint/lib/rules/no-plusplus.js new file mode 100644 index 0000000..22a6fd0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-plusplus.js @@ -0,0 +1,105 @@ +/** + * @fileoverview Rule to flag use of unary increment and decrement operators. + * @author Ian Christian Myers + * @author Brody McKee (github.com/mrmckeb) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is the update node of a `ForStatement`. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `ForStatement` update. + */ +function isForStatementUpdate(node) { + const parent = node.parent; + + return parent.type === "ForStatement" && parent.update === node; +} + +/** + * Determines whether the given node is considered to be a for loop "afterthought" by the logic of this rule. + * In particular, it returns `true` if the given node is either: + * - The update node of a `ForStatement`: for (;; i++) {} + * - An operand of a sequence expression that is the update node: for (;; foo(), i++) {} + * - An operand of a sequence expression that is child of another sequence expression, etc., + * up to the sequence expression that is the update node: for (;; foo(), (bar(), (baz(), i++))) {} + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a for loop afterthought. + */ +function isForLoopAfterthought(node) { + const parent = node.parent; + + if (parent.type === "SequenceExpression") { + return isForLoopAfterthought(parent); + } + + return isForStatementUpdate(node); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the unary operators `++` and `--`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-plusplus" + }, + + schema: [ + { + type: "object", + properties: { + allowForLoopAfterthoughts: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedUnaryOp: "Unary operator '{{operator}}' used." + } + }, + + create(context) { + + const config = context.options[0]; + let allowForLoopAfterthoughts = false; + + if (typeof config === "object") { + allowForLoopAfterthoughts = config.allowForLoopAfterthoughts === true; + } + + return { + + UpdateExpression(node) { + if (allowForLoopAfterthoughts && isForLoopAfterthought(node)) { + return; + } + + context.report({ + node, + messageId: "unexpectedUnaryOp", + data: { + operator: node.operator + } + }); + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-process-env.js b/node_modules/eslint/lib/rules/no-process-env.js new file mode 100644 index 0000000..8dac648 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-process-env.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Disallow the use of process.env() + * @author Vignesh Anand + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Disallow the use of `process.env`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-process-env" + }, + + schema: [], + + messages: { + unexpectedProcessEnv: "Unexpected use of process.env." + } + }, + + create(context) { + + return { + + MemberExpression(node) { + const objectName = node.object.name, + propertyName = node.property.name; + + if (objectName === "process" && !node.computed && propertyName && propertyName === "env") { + context.report({ node, messageId: "unexpectedProcessEnv" }); + } + + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-process-exit.js b/node_modules/eslint/lib/rules/no-process-exit.js new file mode 100644 index 0000000..fa398a7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-process-exit.js @@ -0,0 +1,47 @@ +/** + * @fileoverview Disallow the use of process.exit() + * @author Nicholas C. Zakas + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Disallow the use of `process.exit()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-process-exit" + }, + + schema: [], + + messages: { + noProcessExit: "Don't use process.exit(); throw an error instead." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "CallExpression > MemberExpression.callee[object.name = 'process'][property.name = 'exit']"(node) { + context.report({ node: node.parent, messageId: "noProcessExit" }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-promise-executor-return.js b/node_modules/eslint/lib/rules/no-promise-executor-return.js new file mode 100644 index 0000000..d46a730 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-promise-executor-return.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Rule to disallow returning values from Promise executor functions + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { findVariable } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const functionTypesToCheck = new Set(["ArrowFunctionExpression", "FunctionExpression"]); + +/** + * Determines whether the given identifier node is a reference to a global variable. + * @param {ASTNode} node `Identifier` node to check. + * @param {Scope} scope Scope to which the node belongs. + * @returns {boolean} True if the identifier is a reference to a global variable. + */ +function isGlobalReference(node, scope) { + const variable = findVariable(scope, node); + + return variable !== null && variable.scope.type === "global" && variable.defs.length === 0; +} + +/** + * Finds function's outer scope. + * @param {Scope} scope Function's own scope. + * @returns {Scope} Function's outer scope. + */ +function getOuterScope(scope) { + const upper = scope.upper; + + if (upper.type === "function-expression-name") { + return upper.upper; + } + return upper; +} + +/** + * Determines whether the given function node is used as a Promise executor. + * @param {ASTNode} node The node to check. + * @param {Scope} scope Function's own scope. + * @returns {boolean} `true` if the node is a Promise executor. + */ +function isPromiseExecutor(node, scope) { + const parent = node.parent; + + return parent.type === "NewExpression" && + parent.arguments[0] === node && + parent.callee.type === "Identifier" && + parent.callee.name === "Promise" && + isGlobalReference(parent.callee, getOuterScope(scope)); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow returning values from Promise executor functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-promise-executor-return" + }, + + schema: [], + + messages: { + returnsValue: "Return values from promise executor functions cannot be read." + } + }, + + create(context) { + + let funcInfo = null; + const sourceCode = context.sourceCode; + + /** + * Reports the given node. + * @param {ASTNode} node Node to report. + * @returns {void} + */ + function report(node) { + context.report({ node, messageId: "returnsValue" }); + } + + return { + + onCodePathStart(_, node) { + funcInfo = { + upper: funcInfo, + shouldCheck: functionTypesToCheck.has(node.type) && isPromiseExecutor(node, sourceCode.getScope(node)) + }; + + if (funcInfo.shouldCheck && node.type === "ArrowFunctionExpression" && node.expression) { + report(node.body); + } + }, + + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + ReturnStatement(node) { + if (funcInfo.shouldCheck && node.argument) { + report(node); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-proto.js b/node_modules/eslint/lib/rules/no-proto.js new file mode 100644 index 0000000..28320d5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-proto.js @@ -0,0 +1,48 @@ +/** + * @fileoverview Rule to flag usage of __proto__ property + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getStaticPropertyName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of the `__proto__` property", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-proto" + }, + + schema: [], + + messages: { + unexpectedProto: "The '__proto__' property is deprecated." + } + }, + + create(context) { + + return { + + MemberExpression(node) { + if (getStaticPropertyName(node) === "__proto__") { + context.report({ node, messageId: "unexpectedProto" }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-prototype-builtins.js b/node_modules/eslint/lib/rules/no-prototype-builtins.js new file mode 100644 index 0000000..a7a57bc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-prototype-builtins.js @@ -0,0 +1,71 @@ +/** + * @fileoverview Rule to disallow use of Object.prototype builtins on objects + * @author Andrew Levine + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow calling some `Object.prototype` methods directly on objects", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-prototype-builtins" + }, + + schema: [], + + messages: { + prototypeBuildIn: "Do not access Object.prototype method '{{prop}}' from target object." + } + }, + + create(context) { + const DISALLOWED_PROPS = new Set([ + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable" + ]); + + /** + * Reports if a disallowed property is used in a CallExpression + * @param {ASTNode} node The CallExpression node. + * @returns {void} + */ + function disallowBuiltIns(node) { + + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type !== "MemberExpression") { + return; + } + + const propName = astUtils.getStaticPropertyName(callee); + + if (propName !== null && DISALLOWED_PROPS.has(propName)) { + context.report({ + messageId: "prototypeBuildIn", + loc: callee.property.loc, + data: { prop: propName }, + node + }); + } + } + + return { + CallExpression: disallowBuiltIns + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-redeclare.js b/node_modules/eslint/lib/rules/no-redeclare.js new file mode 100644 index 0000000..8a4877e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-redeclare.js @@ -0,0 +1,174 @@ +/** + * @fileoverview Rule to flag when the same variable is declared more then once. + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow variable redeclaration", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-redeclare" + }, + + messages: { + redeclared: "'{{id}}' is already defined.", + redeclaredAsBuiltin: "'{{id}}' is already defined as a built-in global variable.", + redeclaredBySyntax: "'{{id}}' is already defined by a variable declaration." + }, + + schema: [ + { + type: "object", + properties: { + builtinGlobals: { type: "boolean", default: true } + }, + additionalProperties: false + } + ] + }, + + create(context) { + const options = { + builtinGlobals: Boolean( + context.options.length === 0 || + context.options[0].builtinGlobals + ) + }; + const sourceCode = context.sourceCode; + + /** + * Iterate declarations of a given variable. + * @param {escope.variable} variable The variable object to iterate declarations. + * @returns {IterableIterator<{type:string,node:ASTNode,loc:SourceLocation}>} The declarations. + */ + function *iterateDeclarations(variable) { + if (options.builtinGlobals && ( + variable.eslintImplicitGlobalSetting === "readonly" || + variable.eslintImplicitGlobalSetting === "writable" + )) { + yield { type: "builtin" }; + } + + for (const id of variable.identifiers) { + yield { type: "syntax", node: id, loc: id.loc }; + } + + if (variable.eslintExplicitGlobalComments) { + for (const comment of variable.eslintExplicitGlobalComments) { + yield { + type: "comment", + node: comment, + loc: astUtils.getNameLocationInGlobalDirectiveComment( + sourceCode, + comment, + variable.name + ) + }; + } + } + } + + /** + * Find variables in a given scope and flag redeclared ones. + * @param {Scope} scope An eslint-scope scope object. + * @returns {void} + * @private + */ + function findVariablesInScope(scope) { + for (const variable of scope.variables) { + const [ + declaration, + ...extraDeclarations + ] = iterateDeclarations(variable); + + if (extraDeclarations.length === 0) { + continue; + } + + /* + * If the type of a declaration is different from the type of + * the first declaration, it shows the location of the first + * declaration. + */ + const detailMessageId = declaration.type === "builtin" + ? "redeclaredAsBuiltin" + : "redeclaredBySyntax"; + const data = { id: variable.name }; + + // Report extra declarations. + for (const { type, node, loc } of extraDeclarations) { + const messageId = type === declaration.type + ? "redeclared" + : detailMessageId; + + context.report({ node, loc, messageId, data }); + } + } + } + + /** + * Find variables in the current scope. + * @param {ASTNode} node The node of the current scope. + * @returns {void} + * @private + */ + function checkForBlock(node) { + const scope = sourceCode.getScope(node); + + /* + * In ES5, some node type such as `BlockStatement` doesn't have that scope. + * `scope.block` is a different node in such a case. + */ + if (scope.block === node) { + findVariablesInScope(scope); + } + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + findVariablesInScope(scope); + + // Node.js or ES modules has a special scope. + if ( + scope.type === "global" && + scope.childScopes[0] && + + // The special scope's block is the Program node. + scope.block === scope.childScopes[0].block + ) { + findVariablesInScope(scope.childScopes[0]); + } + }, + + FunctionDeclaration: checkForBlock, + FunctionExpression: checkForBlock, + ArrowFunctionExpression: checkForBlock, + + StaticBlock: checkForBlock, + + BlockStatement: checkForBlock, + ForStatement: checkForBlock, + ForInStatement: checkForBlock, + ForOfStatement: checkForBlock, + SwitchStatement: checkForBlock + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-regex-spaces.js b/node_modules/eslint/lib/rules/no-regex-spaces.js new file mode 100644 index 0000000..cb25010 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-regex-spaces.js @@ -0,0 +1,197 @@ +/** + * @fileoverview Rule to count multiple spaces in regular expressions + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const regexpp = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const regExpParser = new regexpp.RegExpParser(); +const DOUBLE_SPACE = / {2}/u; + +/** + * Check if node is a string + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if its a string + * @private + */ +function isString(node) { + return node && node.type === "Literal" && typeof node.value === "string"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow multiple spaces in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-regex-spaces" + }, + + schema: [], + fixable: "code", + + messages: { + multipleSpaces: "Spaces are hard to count. Use {{{length}}}." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Validate regular expression + * @param {ASTNode} nodeToReport Node to report. + * @param {string} pattern Regular expression pattern to validate. + * @param {string} rawPattern Raw representation of the pattern in the source code. + * @param {number} rawPatternStartRange Start range of the pattern in the source code. + * @param {string} flags Regular expression flags. + * @returns {void} + * @private + */ + function checkRegex(nodeToReport, pattern, rawPattern, rawPatternStartRange, flags) { + + // Skip if there are no consecutive spaces in the source code, to avoid reporting e.g., RegExp(' \ '). + if (!DOUBLE_SPACE.test(rawPattern)) { + return; + } + + const characterClassNodes = []; + let regExpAST; + + try { + regExpAST = regExpParser.parsePattern(pattern, 0, pattern.length, { unicode: flags.includes("u"), unicodeSets: flags.includes("v") }); + } catch { + + // Ignore regular expressions with syntax errors + return; + } + + regexpp.visitRegExpAST(regExpAST, { + onCharacterClassEnter(ccNode) { + characterClassNodes.push(ccNode); + } + }); + + const spacesPattern = /( {2,})(?: [+*{?]|[^+*{?]|$)/gu; + let match; + + while ((match = spacesPattern.exec(pattern))) { + const { 1: { length }, index } = match; + + // Report only consecutive spaces that are not in character classes. + if ( + characterClassNodes.every(({ start, end }) => index < start || end <= index) + ) { + context.report({ + node: nodeToReport, + messageId: "multipleSpaces", + data: { length }, + fix(fixer) { + if (pattern !== rawPattern) { + return null; + } + return fixer.replaceTextRange( + [rawPatternStartRange + index, rawPatternStartRange + index + length], + ` {${length}}` + ); + } + }); + + // Report only the first occurrence of consecutive spaces + return; + } + } + } + + /** + * Validate regular expression literals + * @param {ASTNode} node node to validate + * @returns {void} + * @private + */ + function checkLiteral(node) { + if (node.regex) { + const pattern = node.regex.pattern; + const rawPattern = node.raw.slice(1, node.raw.lastIndexOf("/")); + const rawPatternStartRange = node.range[0] + 1; + const flags = node.regex.flags; + + checkRegex( + node, + pattern, + rawPattern, + rawPatternStartRange, + flags + ); + } + } + + /** + * Validate strings passed to the RegExp constructor + * @param {ASTNode} node node to validate + * @returns {void} + * @private + */ + function checkFunction(node) { + const scope = sourceCode.getScope(node); + const regExpVar = astUtils.getVariableByName(scope, "RegExp"); + const shadowed = regExpVar && regExpVar.defs.length > 0; + const patternNode = node.arguments[0]; + + if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(patternNode) && !shadowed) { + const pattern = patternNode.value; + const rawPattern = patternNode.raw.slice(1, -1); + const rawPatternStartRange = patternNode.range[0] + 1; + let flags; + + if (node.arguments.length < 2) { + + // It has no flags. + flags = ""; + } else { + const flagsNode = node.arguments[1]; + + if (isString(flagsNode)) { + flags = flagsNode.value; + } else { + + // The flags cannot be determined. + return; + } + } + + checkRegex( + node, + pattern, + rawPattern, + rawPatternStartRange, + flags + ); + } + } + + return { + Literal: checkLiteral, + CallExpression: checkFunction, + NewExpression: checkFunction + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-exports.js b/node_modules/eslint/lib/rules/no-restricted-exports.js new file mode 100644 index 0000000..a1d54b0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-exports.js @@ -0,0 +1,193 @@ +/** + * @fileoverview Rule to disallow specified names in exports + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified names in exports", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-exports" + }, + + schema: [{ + anyOf: [ + { + type: "object", + properties: { + restrictedNamedExports: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + } + }, + additionalProperties: false + }, + { + type: "object", + properties: { + restrictedNamedExports: { + type: "array", + items: { + type: "string", + pattern: "^(?!default$)" + }, + uniqueItems: true + }, + restrictDefaultExports: { + type: "object", + properties: { + + // Allow/Disallow `export default foo; export default 42; export default function foo() {}` format + direct: { + type: "boolean" + }, + + // Allow/Disallow `export { foo as default };` declarations + named: { + type: "boolean" + }, + + // Allow/Disallow `export { default } from "mod"; export { default as default } from "mod";` declarations + defaultFrom: { + type: "boolean" + }, + + // Allow/Disallow `export { foo as default } from "mod";` declarations + namedFrom: { + type: "boolean" + }, + + // Allow/Disallow `export * as default from "mod"`; declarations + namespaceFrom: { + type: "boolean" + } + }, + additionalProperties: false + } + }, + additionalProperties: false + } + ] + }], + + messages: { + restrictedNamed: "'{{name}}' is restricted from being used as an exported name.", + restrictedDefault: "Exporting 'default' is restricted." + } + }, + + create(context) { + + const restrictedNames = new Set(context.options[0] && context.options[0].restrictedNamedExports); + const restrictDefaultExports = context.options[0] && context.options[0].restrictDefaultExports; + const sourceCode = context.sourceCode; + + /** + * Checks and reports given exported name. + * @param {ASTNode} node exported `Identifier` or string `Literal` node to check. + * @returns {void} + */ + function checkExportedName(node) { + const name = astUtils.getModuleExportName(node); + + if (restrictedNames.has(name)) { + context.report({ + node, + messageId: "restrictedNamed", + data: { name } + }); + return; + } + + if (name === "default") { + if (node.parent.type === "ExportAllDeclaration") { + if (restrictDefaultExports && restrictDefaultExports.namespaceFrom) { + context.report({ + node, + messageId: "restrictedDefault" + }); + } + + } else { // ExportSpecifier + const isSourceSpecified = !!node.parent.parent.source; + const specifierLocalName = astUtils.getModuleExportName(node.parent.local); + + if (!isSourceSpecified && restrictDefaultExports && restrictDefaultExports.named) { + context.report({ + node, + messageId: "restrictedDefault" + }); + return; + } + + if (isSourceSpecified && restrictDefaultExports) { + if ( + (specifierLocalName === "default" && restrictDefaultExports.defaultFrom) || + (specifierLocalName !== "default" && restrictDefaultExports.namedFrom) + ) { + context.report({ + node, + messageId: "restrictedDefault" + }); + } + } + } + } + } + + return { + ExportAllDeclaration(node) { + if (node.exported) { + checkExportedName(node.exported); + } + }, + + ExportDefaultDeclaration(node) { + if (restrictDefaultExports && restrictDefaultExports.direct) { + context.report({ + node, + messageId: "restrictedDefault" + }); + } + }, + + ExportNamedDeclaration(node) { + const declaration = node.declaration; + + if (declaration) { + if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") { + checkExportedName(declaration.id); + } else if (declaration.type === "VariableDeclaration") { + sourceCode.getDeclaredVariables(declaration) + .map(v => v.defs.find(d => d.parent === declaration)) + .map(d => d.name) // Identifier nodes + .forEach(checkExportedName); + } + } else { + node.specifiers + .map(s => s.exported) + .forEach(checkExportedName); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-globals.js b/node_modules/eslint/lib/rules/no-restricted-globals.js new file mode 100644 index 0000000..919a8ee --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-globals.js @@ -0,0 +1,124 @@ +/** + * @fileoverview Restrict usage of specified globals. + * @author Benoît Zugmeyer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified global variables", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-globals" + }, + + schema: { + type: "array", + items: { + oneOf: [ + { + type: "string" + }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { type: "string" } + }, + required: ["name"], + additionalProperties: false + } + ] + }, + uniqueItems: true, + minItems: 0 + }, + + messages: { + defaultMessage: "Unexpected use of '{{name}}'.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + customMessage: "Unexpected use of '{{name}}'. {{customMessage}}" + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + // If no globals are restricted, we don't need to do anything + if (context.options.length === 0) { + return {}; + } + + const restrictedGlobalMessages = context.options.reduce((memo, option) => { + if (typeof option === "string") { + memo[option] = null; + } else { + memo[option.name] = option.message; + } + + return memo; + }, {}); + + /** + * Report a variable to be used as a restricted global. + * @param {Reference} reference the variable reference + * @returns {void} + * @private + */ + function reportReference(reference) { + const name = reference.identifier.name, + customMessage = restrictedGlobalMessages[name], + messageId = customMessage + ? "customMessage" + : "defaultMessage"; + + context.report({ + node: reference.identifier, + messageId, + data: { + name, + customMessage + } + }); + } + + /** + * Check if the given name is a restricted global name. + * @param {string} name name of a variable + * @returns {boolean} whether the variable is a restricted global or not + * @private + */ + function isRestricted(name) { + return Object.prototype.hasOwnProperty.call(restrictedGlobalMessages, name); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + // Report variables declared elsewhere (ex: variables defined as "global" by eslint) + scope.variables.forEach(variable => { + if (!variable.defs.length && isRestricted(variable.name)) { + variable.references.forEach(reportReference); + } + }); + + // Report variables not declared at all + scope.through.forEach(reference => { + if (isRestricted(reference.identifier.name)) { + reportReference(reference); + } + }); + + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-imports.js b/node_modules/eslint/lib/rules/no-restricted-imports.js new file mode 100644 index 0000000..6abfcac --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-imports.js @@ -0,0 +1,387 @@ +/** + * @fileoverview Restrict usage of specified node imports. + * @author Guy Ellis + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const ignore = require("ignore"); + +const arrayOfStringsOrObjects = { + type: "array", + items: { + anyOf: [ + { type: "string" }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { + type: "string", + minLength: 1 + }, + importNames: { + type: "array", + items: { + type: "string" + } + } + }, + additionalProperties: false, + required: ["name"] + } + ] + }, + uniqueItems: true +}; + +const arrayOfStringsOrObjectPatterns = { + anyOf: [ + { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + }, + { + type: "array", + items: { + type: "object", + properties: { + importNames: { + type: "array", + items: { + type: "string" + }, + minItems: 1, + uniqueItems: true + }, + group: { + type: "array", + items: { + type: "string" + }, + minItems: 1, + uniqueItems: true + }, + message: { + type: "string", + minLength: 1 + }, + caseSensitive: { + type: "boolean" + } + }, + additionalProperties: false, + required: ["group"] + }, + uniqueItems: true + } + ] +}; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified modules when loaded by `import`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-imports" + }, + + messages: { + path: "'{{importSource}}' import is restricted from being used.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + pathWithCustomMessage: "'{{importSource}}' import is restricted from being used. {{customMessage}}", + + patterns: "'{{importSource}}' import is restricted from being used by a pattern.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + patternWithCustomMessage: "'{{importSource}}' import is restricted from being used by a pattern. {{customMessage}}", + + patternAndImportName: "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + patternAndImportNameWithCustomMessage: "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}", + + patternAndEverything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted from being used by a pattern.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + patternAndEverythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}", + + everything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + everythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted. {{customMessage}}", + + importName: "'{{importName}}' import from '{{importSource}}' is restricted.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + importNameWithCustomMessage: "'{{importName}}' import from '{{importSource}}' is restricted. {{customMessage}}" + }, + + schema: { + anyOf: [ + arrayOfStringsOrObjects, + { + type: "array", + items: [{ + type: "object", + properties: { + paths: arrayOfStringsOrObjects, + patterns: arrayOfStringsOrObjectPatterns + }, + additionalProperties: false + }], + additionalItems: false + } + ] + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = Array.isArray(context.options) ? context.options : []; + const isPathAndPatternsObject = + typeof options[0] === "object" && + (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns")); + + const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || []; + const restrictedPathMessages = restrictedPaths.reduce((memo, importSource) => { + if (typeof importSource === "string") { + memo[importSource] = { message: null }; + } else { + memo[importSource.name] = { + message: importSource.message, + importNames: importSource.importNames + }; + } + return memo; + }, {}); + + // Handle patterns too, either as strings or groups + let restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || []; + + // standardize to array of objects if we have an array of strings + if (restrictedPatterns.length > 0 && typeof restrictedPatterns[0] === "string") { + restrictedPatterns = [{ group: restrictedPatterns }]; + } + + // relative paths are supported for this rule + const restrictedPatternGroups = restrictedPatterns.map(({ group, message, caseSensitive, importNames }) => ({ + matcher: ignore({ allowRelativePaths: true, ignorecase: !caseSensitive }).add(group), + customMessage: message, + importNames + })); + + // if no imports are restricted we don't need to check + if (Object.keys(restrictedPaths).length === 0 && restrictedPatternGroups.length === 0) { + return {}; + } + + /** + * Report a restricted path. + * @param {string} importSource path of the import + * @param {Map} importNames Map of import names that are being imported + * @param {node} node representing the restricted path reference + * @returns {void} + * @private + */ + function checkRestrictedPathAndReport(importSource, importNames, node) { + if (!Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource)) { + return; + } + + const customMessage = restrictedPathMessages[importSource].message; + const restrictedImportNames = restrictedPathMessages[importSource].importNames; + + if (restrictedImportNames) { + if (importNames.has("*")) { + const specifierData = importNames.get("*")[0]; + + context.report({ + node, + messageId: customMessage ? "everythingWithCustomMessage" : "everything", + loc: specifierData.loc, + data: { + importSource, + importNames: restrictedImportNames, + customMessage + } + }); + } + + restrictedImportNames.forEach(importName => { + if (importNames.has(importName)) { + const specifiers = importNames.get(importName); + + specifiers.forEach(specifier => { + context.report({ + node, + messageId: customMessage ? "importNameWithCustomMessage" : "importName", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName + } + }); + }); + } + }); + } else { + context.report({ + node, + messageId: customMessage ? "pathWithCustomMessage" : "path", + data: { + importSource, + customMessage + } + }); + } + } + + /** + * Report a restricted path specifically for patterns. + * @param {node} node representing the restricted path reference + * @param {Object} group contains an Ignore instance for paths, the customMessage to show on failure, + * and any restricted import names that have been specified in the config + * @param {Map} importNames Map of import names that are being imported + * @returns {void} + * @private + */ + function reportPathForPatterns(node, group, importNames) { + const importSource = node.source.value.trim(); + + const customMessage = group.customMessage; + const restrictedImportNames = group.importNames; + + /* + * If we are not restricting to any specific import names and just the pattern itself, + * report the error and move on + */ + if (!restrictedImportNames) { + context.report({ + node, + messageId: customMessage ? "patternWithCustomMessage" : "patterns", + data: { + importSource, + customMessage + } + }); + return; + } + + if (importNames.has("*")) { + const specifierData = importNames.get("*")[0]; + + context.report({ + node, + messageId: customMessage ? "patternAndEverythingWithCustomMessage" : "patternAndEverything", + loc: specifierData.loc, + data: { + importSource, + importNames: restrictedImportNames, + customMessage + } + }); + } + + restrictedImportNames.forEach(importName => { + if (!importNames.has(importName)) { + return; + } + + const specifiers = importNames.get(importName); + + specifiers.forEach(specifier => { + context.report({ + node, + messageId: customMessage ? "patternAndImportNameWithCustomMessage" : "patternAndImportName", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName + } + }); + }); + }); + } + + /** + * Check if the given importSource is restricted by a pattern. + * @param {string} importSource path of the import + * @param {Object} group contains a Ignore instance for paths, and the customMessage to show if it fails + * @returns {boolean} whether the variable is a restricted pattern or not + * @private + */ + function isRestrictedPattern(importSource, group) { + return group.matcher.ignores(importSource); + } + + /** + * Checks a node to see if any problems should be reported. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkNode(node) { + const importSource = node.source.value.trim(); + const importNames = new Map(); + + if (node.type === "ExportAllDeclaration") { + const starToken = sourceCode.getFirstToken(node, 1); + + importNames.set("*", [{ loc: starToken.loc }]); + } else if (node.specifiers) { + for (const specifier of node.specifiers) { + let name; + const specifierData = { loc: specifier.loc }; + + if (specifier.type === "ImportDefaultSpecifier") { + name = "default"; + } else if (specifier.type === "ImportNamespaceSpecifier") { + name = "*"; + } else if (specifier.imported) { + name = astUtils.getModuleExportName(specifier.imported); + } else if (specifier.local) { + name = astUtils.getModuleExportName(specifier.local); + } + + if (typeof name === "string") { + if (importNames.has(name)) { + importNames.get(name).push(specifierData); + } else { + importNames.set(name, [specifierData]); + } + } + } + } + + checkRestrictedPathAndReport(importSource, importNames, node); + restrictedPatternGroups.forEach(group => { + if (isRestrictedPattern(importSource, group)) { + reportPathForPatterns(node, group, importNames); + } + }); + } + + return { + ImportDeclaration: checkNode, + ExportNamedDeclaration(node) { + if (node.source) { + checkNode(node); + } + }, + ExportAllDeclaration: checkNode + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-modules.js b/node_modules/eslint/lib/rules/no-restricted-modules.js new file mode 100644 index 0000000..4a9b0a4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-modules.js @@ -0,0 +1,213 @@ +/** + * @fileoverview Restrict usage of specified node modules. + * @author Christian Schulz + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const ignore = require("ignore"); + +const arrayOfStrings = { + type: "array", + items: { type: "string" }, + uniqueItems: true +}; + +const arrayOfStringsOrObjects = { + type: "array", + items: { + anyOf: [ + { type: "string" }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { + type: "string", + minLength: 1 + } + }, + additionalProperties: false, + required: ["name"] + } + ] + }, + uniqueItems: true +}; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Disallow specified modules when loaded by `require`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-modules" + }, + + schema: { + anyOf: [ + arrayOfStringsOrObjects, + { + type: "array", + items: { + type: "object", + properties: { + paths: arrayOfStringsOrObjects, + patterns: arrayOfStrings + }, + additionalProperties: false + }, + additionalItems: false + } + ] + }, + + messages: { + defaultMessage: "'{{name}}' module is restricted from being used.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + customMessage: "'{{name}}' module is restricted from being used. {{customMessage}}", + patternMessage: "'{{name}}' module is restricted from being used by a pattern." + } + }, + + create(context) { + const options = Array.isArray(context.options) ? context.options : []; + const isPathAndPatternsObject = + typeof options[0] === "object" && + (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns")); + + const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || []; + const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || []; + + const restrictedPathMessages = restrictedPaths.reduce((memo, importName) => { + if (typeof importName === "string") { + memo[importName] = null; + } else { + memo[importName.name] = importName.message; + } + return memo; + }, {}); + + // if no imports are restricted we don't need to check + if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) { + return {}; + } + + // relative paths are supported for this rule + const ig = ignore({ allowRelativePaths: true }).add(restrictedPatterns); + + + /** + * Function to check if a node is a string literal. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a string literal. + */ + function isStringLiteral(node) { + return node && node.type === "Literal" && typeof node.value === "string"; + } + + /** + * Function to check if a node is a require call. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a require call. + */ + function isRequireCall(node) { + return node.callee.type === "Identifier" && node.callee.name === "require"; + } + + /** + * Extract string from Literal or TemplateLiteral node + * @param {ASTNode} node The node to extract from + * @returns {string|null} Extracted string or null if node doesn't represent a string + */ + function getFirstArgumentString(node) { + if (isStringLiteral(node)) { + return node.value.trim(); + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return node.quasis[0].value.cooked.trim(); + } + + return null; + } + + /** + * Report a restricted path. + * @param {node} node representing the restricted path reference + * @param {string} name restricted path + * @returns {void} + * @private + */ + function reportPath(node, name) { + const customMessage = restrictedPathMessages[name]; + const messageId = customMessage + ? "customMessage" + : "defaultMessage"; + + context.report({ + node, + messageId, + data: { + name, + customMessage + } + }); + } + + /** + * Check if the given name is a restricted path name + * @param {string} name name of a variable + * @returns {boolean} whether the variable is a restricted path or not + * @private + */ + function isRestrictedPath(name) { + return Object.prototype.hasOwnProperty.call(restrictedPathMessages, name); + } + + return { + CallExpression(node) { + if (isRequireCall(node)) { + + // node has arguments + if (node.arguments.length) { + const name = getFirstArgumentString(node.arguments[0]); + + // if first argument is a string literal or a static string template literal + if (name) { + + // check if argument value is in restricted modules array + if (isRestrictedPath(name)) { + reportPath(node, name); + } + + if (restrictedPatterns.length > 0 && ig.ignores(name)) { + context.report({ + node, + messageId: "patternMessage", + data: { name } + }); + } + } + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-properties.js b/node_modules/eslint/lib/rules/no-restricted-properties.js new file mode 100644 index 0000000..b076632 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-properties.js @@ -0,0 +1,181 @@ +/** + * @fileoverview Rule to disallow certain object properties + * @author Will Klein & Eli White + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow certain properties on certain objects", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-properties" + }, + + schema: { + type: "array", + items: { + anyOf: [ // `object` and `property` are both optional, but at least one of them must be provided. + { + type: "object", + properties: { + object: { + type: "string" + }, + property: { + type: "string" + }, + message: { + type: "string" + } + }, + additionalProperties: false, + required: ["object"] + }, + { + type: "object", + properties: { + object: { + type: "string" + }, + property: { + type: "string" + }, + message: { + type: "string" + } + }, + additionalProperties: false, + required: ["property"] + } + ] + }, + uniqueItems: true + }, + + messages: { + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + restrictedObjectProperty: "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + restrictedProperty: "'{{propertyName}}' is restricted from being used.{{message}}" + } + }, + + create(context) { + const restrictedCalls = context.options; + + if (restrictedCalls.length === 0) { + return {}; + } + + const restrictedProperties = new Map(); + const globallyRestrictedObjects = new Map(); + const globallyRestrictedProperties = new Map(); + + restrictedCalls.forEach(option => { + const objectName = option.object; + const propertyName = option.property; + + if (typeof objectName === "undefined") { + globallyRestrictedProperties.set(propertyName, { message: option.message }); + } else if (typeof propertyName === "undefined") { + globallyRestrictedObjects.set(objectName, { message: option.message }); + } else { + if (!restrictedProperties.has(objectName)) { + restrictedProperties.set(objectName, new Map()); + } + + restrictedProperties.get(objectName).set(propertyName, { + message: option.message + }); + } + }); + + /** + * Checks to see whether a property access is restricted, and reports it if so. + * @param {ASTNode} node The node to report + * @param {string} objectName The name of the object + * @param {string} propertyName The name of the property + * @returns {undefined} + */ + function checkPropertyAccess(node, objectName, propertyName) { + if (propertyName === null) { + return; + } + const matchedObject = restrictedProperties.get(objectName); + const matchedObjectProperty = matchedObject ? matchedObject.get(propertyName) : globallyRestrictedObjects.get(objectName); + const globalMatchedProperty = globallyRestrictedProperties.get(propertyName); + + if (matchedObjectProperty) { + const message = matchedObjectProperty.message ? ` ${matchedObjectProperty.message}` : ""; + + context.report({ + node, + messageId: "restrictedObjectProperty", + data: { + objectName, + propertyName, + message + } + }); + } else if (globalMatchedProperty) { + const message = globalMatchedProperty.message ? ` ${globalMatchedProperty.message}` : ""; + + context.report({ + node, + messageId: "restrictedProperty", + data: { + propertyName, + message + } + }); + } + } + + /** + * Checks property accesses in a destructuring assignment expression, e.g. `var foo; ({foo} = bar);` + * @param {ASTNode} node An AssignmentExpression or AssignmentPattern node + * @returns {undefined} + */ + function checkDestructuringAssignment(node) { + if (node.right.type === "Identifier") { + const objectName = node.right.name; + + if (node.left.type === "ObjectPattern") { + node.left.properties.forEach(property => { + checkPropertyAccess(node.left, objectName, astUtils.getStaticPropertyName(property)); + }); + } + } + } + + return { + MemberExpression(node) { + checkPropertyAccess(node, node.object && node.object.name, astUtils.getStaticPropertyName(node)); + }, + VariableDeclarator(node) { + if (node.init && node.init.type === "Identifier") { + const objectName = node.init.name; + + if (node.id.type === "ObjectPattern") { + node.id.properties.forEach(property => { + checkPropertyAccess(node.id, objectName, astUtils.getStaticPropertyName(property)); + }); + } + } + }, + AssignmentExpression: checkDestructuringAssignment, + AssignmentPattern: checkDestructuringAssignment + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-syntax.js b/node_modules/eslint/lib/rules/no-restricted-syntax.js new file mode 100644 index 0000000..930882c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-syntax.js @@ -0,0 +1,70 @@ +/** + * @fileoverview Rule to flag use of certain node types + * @author Burak Yigit Kaya + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified syntax", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-syntax" + }, + + schema: { + type: "array", + items: { + oneOf: [ + { + type: "string" + }, + { + type: "object", + properties: { + selector: { type: "string" }, + message: { type: "string" } + }, + required: ["selector"], + additionalProperties: false + } + ] + }, + uniqueItems: true, + minItems: 0 + }, + + messages: { + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + restrictedSyntax: "{{message}}" + } + }, + + create(context) { + return context.options.reduce((result, selectorOrObject) => { + const isStringFormat = (typeof selectorOrObject === "string"); + const hasCustomMessage = !isStringFormat && Boolean(selectorOrObject.message); + + const selector = isStringFormat ? selectorOrObject : selectorOrObject.selector; + const message = hasCustomMessage ? selectorOrObject.message : `Using '${selector}' is not allowed.`; + + return Object.assign(result, { + [selector](node) { + context.report({ + node, + messageId: "restrictedSyntax", + data: { message } + }); + } + }); + }, {}); + + } +}; diff --git a/node_modules/eslint/lib/rules/no-return-assign.js b/node_modules/eslint/lib/rules/no-return-assign.js new file mode 100644 index 0000000..73caf0e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-return-assign.js @@ -0,0 +1,80 @@ +/** + * @fileoverview Rule to flag when return statement contains assignment + * @author Ilya Volodin + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow assignment operators in `return` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-return-assign" + }, + + schema: [ + { + enum: ["except-parens", "always"] + } + ], + + messages: { + returnAssignment: "Return statement should not contain assignment.", + arrowAssignment: "Arrow function should not return assignment." + } + }, + + create(context) { + const always = (context.options[0] || "except-parens") !== "except-parens"; + const sourceCode = context.sourceCode; + + return { + AssignmentExpression(node) { + if (!always && astUtils.isParenthesised(sourceCode, node)) { + return; + } + + let currentChild = node; + let parent = currentChild.parent; + + // Find ReturnStatement or ArrowFunctionExpression in ancestors. + while (parent && !SENTINEL_TYPE.test(parent.type)) { + currentChild = parent; + parent = parent.parent; + } + + // Reports. + if (parent && parent.type === "ReturnStatement") { + context.report({ + node: parent, + messageId: "returnAssignment" + }); + } else if (parent && parent.type === "ArrowFunctionExpression" && parent.body === currentChild) { + context.report({ + node: parent, + messageId: "arrowAssignment" + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-return-await.js b/node_modules/eslint/lib/rules/no-return-await.js new file mode 100644 index 0000000..77abda0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-return-await.js @@ -0,0 +1,135 @@ +/** + * @fileoverview Disallows unnecessary `return await` + * @author Jordan Harband + * @deprecated in ESLint v8.46.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + docs: { + description: "Disallow unnecessary `return await`", + + recommended: false, + + url: "https://eslint.org/docs/latest/rules/no-return-await" + }, + + fixable: null, + + deprecated: true, + + replacedBy: [], + + schema: [ + ], + + messages: { + removeAwait: "Remove redundant `await`.", + redundantUseOfAwait: "Redundant use of `await` on a return value." + } + }, + + create(context) { + + /** + * Reports a found unnecessary `await` expression. + * @param {ASTNode} node The node representing the `await` expression to report + * @returns {void} + */ + function reportUnnecessaryAwait(node) { + context.report({ + node: context.sourceCode.getFirstToken(node), + loc: node.loc, + messageId: "redundantUseOfAwait", + suggest: [ + { + messageId: "removeAwait", + fix(fixer) { + const sourceCode = context.sourceCode; + const [awaitToken, tokenAfterAwait] = sourceCode.getFirstTokens(node, 2); + + const areAwaitAndAwaitedExpressionOnTheSameLine = awaitToken.loc.start.line === tokenAfterAwait.loc.start.line; + + if (!areAwaitAndAwaitedExpressionOnTheSameLine) { + return null; + } + + const [startOfAwait, endOfAwait] = awaitToken.range; + + const characterAfterAwait = sourceCode.text[endOfAwait]; + const trimLength = characterAfterAwait === " " ? 1 : 0; + + const range = [startOfAwait, endOfAwait + trimLength]; + + return fixer.removeRange(range); + } + } + ] + + }); + } + + /** + * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting + * this function. For example, a statement in a `try` block will always have an error handler. A statement in + * a `catch` block will only have an error handler if there is also a `finally` block. + * @param {ASTNode} node A node representing a location where an could be thrown + * @returns {boolean} `true` if a thrown error will be caught/handled in this function + */ + function hasErrorHandler(node) { + let ancestor = node; + + while (!astUtils.isFunction(ancestor) && ancestor.type !== "Program") { + if (ancestor.parent.type === "TryStatement" && (ancestor === ancestor.parent.block || ancestor === ancestor.parent.handler && ancestor.parent.finalizer)) { + return true; + } + ancestor = ancestor.parent; + } + return false; + } + + /** + * Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression, + * an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position. + * @param {ASTNode} node A node representing the `await` expression to check + * @returns {boolean} The checking result + */ + function isInTailCallPosition(node) { + if (node.parent.type === "ArrowFunctionExpression") { + return true; + } + if (node.parent.type === "ReturnStatement") { + return !hasErrorHandler(node.parent); + } + if (node.parent.type === "ConditionalExpression" && (node === node.parent.consequent || node === node.parent.alternate)) { + return isInTailCallPosition(node.parent); + } + if (node.parent.type === "LogicalExpression" && node === node.parent.right) { + return isInTailCallPosition(node.parent); + } + if (node.parent.type === "SequenceExpression" && node === node.parent.expressions[node.parent.expressions.length - 1]) { + return isInTailCallPosition(node.parent); + } + return false; + } + + return { + AwaitExpression(node) { + if (isInTailCallPosition(node) && !hasErrorHandler(node)) { + reportUnnecessaryAwait(node); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-script-url.js b/node_modules/eslint/lib/rules/no-script-url.js new file mode 100644 index 0000000..1d16bde --- /dev/null +++ b/node_modules/eslint/lib/rules/no-script-url.js @@ -0,0 +1,61 @@ +/** + * @fileoverview Rule to flag when using javascript: urls + * @author Ilya Volodin + */ +/* eslint no-script-url: 0 -- Code is checking to report such URLs */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `javascript:` urls", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-script-url" + }, + + schema: [], + + messages: { + unexpectedScriptURL: "Script URL is a form of eval." + } + }, + + create(context) { + + /** + * Check whether a node's static value starts with "javascript:" or not. + * And report an error for unexpected script URL. + * @param {ASTNode} node node to check + * @returns {void} + */ + function check(node) { + const value = astUtils.getStaticStringValue(node); + + if (typeof value === "string" && value.toLowerCase().indexOf("javascript:") === 0) { + context.report({ node, messageId: "unexpectedScriptURL" }); + } + } + return { + Literal(node) { + if (node.value && typeof node.value === "string") { + check(node); + } + }, + TemplateLiteral(node) { + if (!(node.parent && node.parent.type === "TaggedTemplateExpression")) { + check(node); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-self-assign.js b/node_modules/eslint/lib/rules/no-self-assign.js new file mode 100644 index 0000000..33ac8fb --- /dev/null +++ b/node_modules/eslint/lib/rules/no-self-assign.js @@ -0,0 +1,183 @@ +/** + * @fileoverview Rule to disallow assignments where both sides are exactly the same + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SPACES = /\s+/gu; + +/** + * Traverses 2 Pattern nodes in parallel, then reports self-assignments. + * @param {ASTNode|null} left A left node to traverse. This is a Pattern or + * a Property. + * @param {ASTNode|null} right A right node to traverse. This is a Pattern or + * a Property. + * @param {boolean} props The flag to check member expressions as well. + * @param {Function} report A callback function to report. + * @returns {void} + */ +function eachSelfAssignment(left, right, props, report) { + if (!left || !right) { + + // do nothing + } else if ( + left.type === "Identifier" && + right.type === "Identifier" && + left.name === right.name + ) { + report(right); + } else if ( + left.type === "ArrayPattern" && + right.type === "ArrayExpression" + ) { + const end = Math.min(left.elements.length, right.elements.length); + + for (let i = 0; i < end; ++i) { + const leftElement = left.elements[i]; + const rightElement = right.elements[i]; + + // Avoid cases such as [...a] = [...a, 1] + if ( + leftElement && + leftElement.type === "RestElement" && + i < right.elements.length - 1 + ) { + break; + } + + eachSelfAssignment(leftElement, rightElement, props, report); + + // After a spread element, those indices are unknown. + if (rightElement && rightElement.type === "SpreadElement") { + break; + } + } + } else if ( + left.type === "RestElement" && + right.type === "SpreadElement" + ) { + eachSelfAssignment(left.argument, right.argument, props, report); + } else if ( + left.type === "ObjectPattern" && + right.type === "ObjectExpression" && + right.properties.length >= 1 + ) { + + /* + * Gets the index of the last spread property. + * It's possible to overwrite properties followed by it. + */ + let startJ = 0; + + for (let i = right.properties.length - 1; i >= 0; --i) { + const propType = right.properties[i].type; + + if (propType === "SpreadElement" || propType === "ExperimentalSpreadProperty") { + startJ = i + 1; + break; + } + } + + for (let i = 0; i < left.properties.length; ++i) { + for (let j = startJ; j < right.properties.length; ++j) { + eachSelfAssignment( + left.properties[i], + right.properties[j], + props, + report + ); + } + } + } else if ( + left.type === "Property" && + right.type === "Property" && + right.kind === "init" && + !right.method + ) { + const leftName = astUtils.getStaticPropertyName(left); + + if (leftName !== null && leftName === astUtils.getStaticPropertyName(right)) { + eachSelfAssignment(left.value, right.value, props, report); + } + } else if ( + props && + astUtils.skipChainExpression(left).type === "MemberExpression" && + astUtils.skipChainExpression(right).type === "MemberExpression" && + astUtils.isSameReference(left, right) + ) { + report(right); + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow assignments where both sides are exactly the same", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-self-assign" + }, + + schema: [ + { + type: "object", + properties: { + props: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + selfAssignment: "'{{name}}' is assigned to itself." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ props = true } = {}] = context.options; + + /** + * Reports a given node as self assignments. + * @param {ASTNode} node A node to report. This is an Identifier node. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "selfAssignment", + data: { + name: sourceCode.getText(node).replace(SPACES, "") + } + }); + } + + return { + AssignmentExpression(node) { + if (["=", "&&=", "||=", "??="].includes(node.operator)) { + eachSelfAssignment(node.left, node.right, props, report); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-self-compare.js b/node_modules/eslint/lib/rules/no-self-compare.js new file mode 100644 index 0000000..3b076eb --- /dev/null +++ b/node_modules/eslint/lib/rules/no-self-compare.js @@ -0,0 +1,60 @@ +/** + * @fileoverview Rule to flag comparison where left part is the same as the right + * part. + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow comparisons where both sides are exactly the same", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-self-compare" + }, + + schema: [], + + messages: { + comparingToSelf: "Comparing to itself is potentially pointless." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether two nodes are composed of the same tokens. + * @param {ASTNode} nodeA The first node + * @param {ASTNode} nodeB The second node + * @returns {boolean} true if the nodes have identical token representations + */ + function hasSameTokens(nodeA, nodeB) { + const tokensA = sourceCode.getTokens(nodeA); + const tokensB = sourceCode.getTokens(nodeB); + + return tokensA.length === tokensB.length && + tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value); + } + + return { + + BinaryExpression(node) { + const operators = new Set(["===", "==", "!==", "!=", ">", "<", ">=", "<="]); + + if (operators.has(node.operator) && hasSameTokens(node.left, node.right)) { + context.report({ node, messageId: "comparingToSelf" }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-sequences.js b/node_modules/eslint/lib/rules/no-sequences.js new file mode 100644 index 0000000..cd21fc7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sequences.js @@ -0,0 +1,138 @@ +/** + * @fileoverview Rule to flag use of comma operator + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_OPTIONS = { + allowInParentheses: true +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow comma operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-sequences" + }, + + schema: [{ + properties: { + allowInParentheses: { + type: "boolean", + default: true + } + }, + additionalProperties: false + }], + + messages: { + unexpectedCommaExpression: "Unexpected use of comma operator." + } + }, + + create(context) { + const options = Object.assign({}, DEFAULT_OPTIONS, context.options[0]); + const sourceCode = context.sourceCode; + + /** + * Parts of the grammar that are required to have parens. + */ + const parenthesized = { + DoWhileStatement: "test", + IfStatement: "test", + SwitchStatement: "discriminant", + WhileStatement: "test", + WithStatement: "object", + ArrowFunctionExpression: "body" + + /* + * Omitting CallExpression - commas are parsed as argument separators + * Omitting NewExpression - commas are parsed as argument separators + * Omitting ForInStatement - parts aren't individually parenthesised + * Omitting ForStatement - parts aren't individually parenthesised + */ + }; + + /** + * Determines whether a node is required by the grammar to be wrapped in + * parens, e.g. the test of an if statement. + * @param {ASTNode} node The AST node + * @returns {boolean} True if parens around node belong to parent node. + */ + function requiresExtraParens(node) { + return node.parent && parenthesized[node.parent.type] && + node === node.parent[parenthesized[node.parent.type]]; + } + + /** + * Check if a node is wrapped in parens. + * @param {ASTNode} node The AST node + * @returns {boolean} True if the node has a paren on each side. + */ + function isParenthesised(node) { + return astUtils.isParenthesised(sourceCode, node); + } + + /** + * Check if a node is wrapped in two levels of parens. + * @param {ASTNode} node The AST node + * @returns {boolean} True if two parens surround the node on each side. + */ + function isParenthesisedTwice(node) { + const previousToken = sourceCode.getTokenBefore(node, 1), + nextToken = sourceCode.getTokenAfter(node, 1); + + return isParenthesised(node) && previousToken && nextToken && + astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && + astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1]; + } + + return { + SequenceExpression(node) { + + // Always allow sequences in for statement update + if (node.parent.type === "ForStatement" && + (node === node.parent.init || node === node.parent.update)) { + return; + } + + // Wrapping a sequence in extra parens indicates intent + if (options.allowInParentheses) { + if (requiresExtraParens(node)) { + if (isParenthesisedTwice(node)) { + return; + } + } else { + if (isParenthesised(node)) { + return; + } + } + } + + const firstCommaToken = sourceCode.getTokenAfter(node.expressions[0], astUtils.isCommaToken); + + context.report({ node, loc: firstCommaToken.loc, messageId: "unexpectedCommaExpression" }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-setter-return.js b/node_modules/eslint/lib/rules/no-setter-return.js new file mode 100644 index 0000000..a5abaaa --- /dev/null +++ b/node_modules/eslint/lib/rules/no-setter-return.js @@ -0,0 +1,226 @@ +/** + * @fileoverview Rule to disallow returning values from setters + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { findVariable } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given identifier node is a reference to a global variable. + * @param {ASTNode} node `Identifier` node to check. + * @param {Scope} scope Scope to which the node belongs. + * @returns {boolean} True if the identifier is a reference to a global variable. + */ +function isGlobalReference(node, scope) { + const variable = findVariable(scope, node); + + return variable !== null && variable.scope.type === "global" && variable.defs.length === 0; +} + +/** + * Determines whether the given node is an argument of the specified global method call, at the given `index` position. + * E.g., for given `index === 1`, this function checks for `objectName.methodName(foo, node)`, where objectName is a global variable. + * @param {ASTNode} node The node to check. + * @param {Scope} scope Scope to which the node belongs. + * @param {string} objectName Name of the global object. + * @param {string} methodName Name of the method. + * @param {number} index The given position. + * @returns {boolean} `true` if the node is argument at the given position. + */ +function isArgumentOfGlobalMethodCall(node, scope, objectName, methodName, index) { + const callNode = node.parent; + + return callNode.type === "CallExpression" && + callNode.arguments[index] === node && + astUtils.isSpecificMemberAccess(callNode.callee, objectName, methodName) && + isGlobalReference(astUtils.skipChainExpression(callNode.callee).object, scope); +} + +/** + * Determines whether the given node is used as a property descriptor. + * @param {ASTNode} node The node to check. + * @param {Scope} scope Scope to which the node belongs. + * @returns {boolean} `true` if the node is a property descriptor. + */ +function isPropertyDescriptor(node, scope) { + if ( + isArgumentOfGlobalMethodCall(node, scope, "Object", "defineProperty", 2) || + isArgumentOfGlobalMethodCall(node, scope, "Reflect", "defineProperty", 2) + ) { + return true; + } + + const parent = node.parent; + + if ( + parent.type === "Property" && + parent.value === node + ) { + const grandparent = parent.parent; + + if ( + grandparent.type === "ObjectExpression" && + ( + isArgumentOfGlobalMethodCall(grandparent, scope, "Object", "create", 1) || + isArgumentOfGlobalMethodCall(grandparent, scope, "Object", "defineProperties", 1) + ) + ) { + return true; + } + } + + return false; +} + +/** + * Determines whether the given function node is used as a setter function. + * @param {ASTNode} node The node to check. + * @param {Scope} scope Scope to which the node belongs. + * @returns {boolean} `true` if the node is a setter. + */ +function isSetter(node, scope) { + const parent = node.parent; + + if ( + (parent.type === "Property" || parent.type === "MethodDefinition") && + parent.kind === "set" && + parent.value === node + ) { + + // Setter in an object literal or in a class + return true; + } + + if ( + parent.type === "Property" && + parent.value === node && + astUtils.getStaticPropertyName(parent) === "set" && + parent.parent.type === "ObjectExpression" && + isPropertyDescriptor(parent.parent, scope) + ) { + + // Setter in a property descriptor + return true; + } + + return false; +} + +/** + * Finds function's outer scope. + * @param {Scope} scope Function's own scope. + * @returns {Scope} Function's outer scope. + */ +function getOuterScope(scope) { + const upper = scope.upper; + + if (upper.type === "function-expression-name") { + return upper.upper; + } + + return upper; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow returning values from setters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-setter-return" + }, + + schema: [], + + messages: { + returnsValue: "Setter cannot return a value." + } + }, + + create(context) { + let funcInfo = null; + const sourceCode = context.sourceCode; + + /** + * Creates and pushes to the stack a function info object for the given function node. + * @param {ASTNode} node The function node. + * @returns {void} + */ + function enterFunction(node) { + const outerScope = getOuterScope(sourceCode.getScope(node)); + + funcInfo = { + upper: funcInfo, + isSetter: isSetter(node, outerScope) + }; + } + + /** + * Pops the current function info object from the stack. + * @returns {void} + */ + function exitFunction() { + funcInfo = funcInfo.upper; + } + + /** + * Reports the given node. + * @param {ASTNode} node Node to report. + * @returns {void} + */ + function report(node) { + context.report({ node, messageId: "returnsValue" }); + } + + return { + + /* + * Function declarations cannot be setters, but we still have to track them in the `funcInfo` stack to avoid + * false positives, because a ReturnStatement node can belong to a function declaration inside a setter. + * + * Note: A previously declared function can be referenced and actually used as a setter in a property descriptor, + * but that's out of scope for this rule. + */ + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression(node) { + enterFunction(node); + + if (funcInfo.isSetter && node.expression) { + + // { set: foo => bar } property descriptor. Report implicit return 'bar' as the equivalent for a return statement. + report(node.body); + } + }, + + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + ReturnStatement(node) { + + // Global returns (e.g., at the top level of a Node module) don't have `funcInfo`. + if (funcInfo && funcInfo.isSetter && node.argument) { + report(node); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-shadow-restricted-names.js b/node_modules/eslint/lib/rules/no-shadow-restricted-names.js new file mode 100644 index 0000000..29560ff --- /dev/null +++ b/node_modules/eslint/lib/rules/no-shadow-restricted-names.js @@ -0,0 +1,65 @@ +/** + * @fileoverview Disallow shadowing of NaN, undefined, and Infinity (ES5 section 15.1.1) + * @author Michael Ficarra + */ +"use strict"; + +/** + * Determines if a variable safely shadows undefined. + * This is the case when a variable named `undefined` is never assigned to a value (i.e. it always shares the same value + * as the global). + * @param {eslintScope.Variable} variable The variable to check + * @returns {boolean} true if this variable safely shadows `undefined` + */ +function safelyShadowsUndefined(variable) { + return variable.name === "undefined" && + variable.references.every(ref => !ref.isWrite()) && + variable.defs.every(def => def.node.type === "VariableDeclarator" && def.node.init === null); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow identifiers from shadowing restricted names", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-shadow-restricted-names" + }, + + schema: [], + + messages: { + shadowingRestrictedName: "Shadowing of global property '{{name}}'." + } + }, + + create(context) { + + + const RESTRICTED = new Set(["undefined", "NaN", "Infinity", "arguments", "eval"]); + const sourceCode = context.sourceCode; + + return { + "VariableDeclaration, :function, CatchClause"(node) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if (variable.defs.length > 0 && RESTRICTED.has(variable.name) && !safelyShadowsUndefined(variable)) { + context.report({ + node: variable.defs[0].name, + messageId: "shadowingRestrictedName", + data: { + name: variable.name + } + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-shadow.js b/node_modules/eslint/lib/rules/no-shadow.js new file mode 100644 index 0000000..3e4d998 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-shadow.js @@ -0,0 +1,336 @@ +/** + * @fileoverview Rule to flag on declaring variables already declared in the outer scope + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const FUNC_EXPR_NODE_TYPES = new Set(["ArrowFunctionExpression", "FunctionExpression"]); +const CALL_EXPR_NODE_TYPE = new Set(["CallExpression"]); +const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u; +const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow variable declarations from shadowing variables declared in the outer scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-shadow" + }, + + schema: [ + { + type: "object", + properties: { + builtinGlobals: { type: "boolean", default: false }, + hoist: { enum: ["all", "functions", "never"], default: "functions" }, + allow: { + type: "array", + items: { + type: "string" + } + }, + ignoreOnInitialization: { type: "boolean", default: false } + }, + additionalProperties: false + } + ], + + messages: { + noShadow: "'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.", + noShadowGlobal: "'{{name}}' is already a global variable." + } + }, + + create(context) { + + const options = { + builtinGlobals: context.options[0] && context.options[0].builtinGlobals, + hoist: (context.options[0] && context.options[0].hoist) || "functions", + allow: (context.options[0] && context.options[0].allow) || [], + ignoreOnInitialization: context.options[0] && context.options[0].ignoreOnInitialization + }; + const sourceCode = context.sourceCode; + + /** + * Checks whether or not a given location is inside of the range of a given node. + * @param {ASTNode} node An node to check. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of the range of the node. + */ + function isInRange(node, location) { + return node && node.range[0] <= location && location <= node.range[1]; + } + + /** + * Searches from the current node through its ancestry to find a matching node. + * @param {ASTNode} node a node to get. + * @param {(node: ASTNode) => boolean} match a callback that checks whether or not the node verifies its condition or not. + * @returns {ASTNode|null} the matching node. + */ + function findSelfOrAncestor(node, match) { + let currentNode = node; + + while (currentNode && !match(currentNode)) { + currentNode = currentNode.parent; + } + return currentNode; + } + + /** + * Finds function's outer scope. + * @param {Scope} scope Function's own scope. + * @returns {Scope} Function's outer scope. + */ + function getOuterScope(scope) { + const upper = scope.upper; + + if (upper.type === "function-expression-name") { + return upper.upper; + } + return upper; + } + + /** + * Checks if a variable and a shadowedVariable have the same init pattern ancestor. + * @param {Object} variable a variable to check. + * @param {Object} shadowedVariable a shadowedVariable to check. + * @returns {boolean} Whether or not the variable and the shadowedVariable have the same init pattern ancestor. + */ + function isInitPatternNode(variable, shadowedVariable) { + const outerDef = shadowedVariable.defs[0]; + + if (!outerDef) { + return false; + } + + const { variableScope } = variable.scope; + + + if (!(FUNC_EXPR_NODE_TYPES.has(variableScope.block.type) && getOuterScope(variableScope) === shadowedVariable.scope)) { + return false; + } + + const fun = variableScope.block; + const { parent } = fun; + + const callExpression = findSelfOrAncestor( + parent, + node => CALL_EXPR_NODE_TYPE.has(node.type) + ); + + if (!callExpression) { + return false; + } + + let node = outerDef.name; + const location = callExpression.range[1]; + + while (node) { + if (node.type === "VariableDeclarator") { + if (isInRange(node.init, location)) { + return true; + } + if (FOR_IN_OF_TYPE.test(node.parent.parent.type) && + isInRange(node.parent.parent.right, location) + ) { + return true; + } + break; + } else if (node.type === "AssignmentPattern") { + if (isInRange(node.right, location)) { + return true; + } + } else if (SENTINEL_TYPE.test(node.type)) { + break; + } + + node = node.parent; + } + + return false; + } + + /** + * Check if variable name is allowed. + * @param {ASTNode} variable The variable to check. + * @returns {boolean} Whether or not the variable name is allowed. + */ + function isAllowed(variable) { + return options.allow.includes(variable.name); + } + + /** + * Checks if a variable of the class name in the class scope of ClassDeclaration. + * + * ClassDeclaration creates two variables of its name into its outer scope and its class scope. + * So we should ignore the variable in the class scope. + * @param {Object} variable The variable to check. + * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration. + */ + function isDuplicatedClassNameVariable(variable) { + const block = variable.scope.block; + + return block.type === "ClassDeclaration" && block.id === variable.identifiers[0]; + } + + /** + * Checks if a variable is inside the initializer of scopeVar. + * + * To avoid reporting at declarations such as `var a = function a() {};`. + * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`. + * @param {Object} variable The variable to check. + * @param {Object} scopeVar The scope variable to look for. + * @returns {boolean} Whether or not the variable is inside initializer of scopeVar. + */ + function isOnInitializer(variable, scopeVar) { + const outerScope = scopeVar.scope; + const outerDef = scopeVar.defs[0]; + const outer = outerDef && outerDef.parent && outerDef.parent.range; + const innerScope = variable.scope; + const innerDef = variable.defs[0]; + const inner = innerDef && innerDef.name.range; + + return ( + outer && + inner && + outer[0] < inner[0] && + inner[1] < outer[1] && + ((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") && + outerScope === innerScope.upper + ); + } + + /** + * Get a range of a variable's identifier node. + * @param {Object} variable The variable to get. + * @returns {Array|undefined} The range of the variable's identifier node. + */ + function getNameRange(variable) { + const def = variable.defs[0]; + + return def && def.name.range; + } + + /** + * Get declared line and column of a variable. + * @param {eslint-scope.Variable} variable The variable to get. + * @returns {Object} The declared line and column of the variable. + */ + function getDeclaredLocation(variable) { + const identifier = variable.identifiers[0]; + let obj; + + if (identifier) { + obj = { + global: false, + line: identifier.loc.start.line, + column: identifier.loc.start.column + 1 + }; + } else { + obj = { + global: true + }; + } + return obj; + } + + /** + * Checks if a variable is in TDZ of scopeVar. + * @param {Object} variable The variable to check. + * @param {Object} scopeVar The variable of TDZ. + * @returns {boolean} Whether or not the variable is in TDZ of scopeVar. + */ + function isInTdz(variable, scopeVar) { + const outerDef = scopeVar.defs[0]; + const inner = getNameRange(variable); + const outer = getNameRange(scopeVar); + + return ( + inner && + outer && + inner[1] < outer[0] && + + // Excepts FunctionDeclaration if is {"hoist":"function"}. + (options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration") + ); + } + + /** + * Checks the current context for shadowed variables. + * @param {Scope} scope Fixme + * @returns {void} + */ + function checkForShadows(scope) { + const variables = scope.variables; + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration. + if (variable.identifiers.length === 0 || + isDuplicatedClassNameVariable(variable) || + isAllowed(variable) + ) { + continue; + } + + // Gets shadowed variable. + const shadowed = astUtils.getVariableByName(scope.upper, variable.name); + + if (shadowed && + (shadowed.identifiers.length > 0 || (options.builtinGlobals && "writeable" in shadowed)) && + !isOnInitializer(variable, shadowed) && + !(options.ignoreOnInitialization && isInitPatternNode(variable, shadowed)) && + !(options.hoist !== "all" && isInTdz(variable, shadowed)) + ) { + const location = getDeclaredLocation(shadowed); + const messageId = location.global ? "noShadowGlobal" : "noShadow"; + const data = { name: variable.name }; + + if (!location.global) { + data.shadowedLine = location.line; + data.shadowedColumn = location.column; + } + context.report({ + node: variable.identifiers[0], + messageId, + data + }); + } + } + } + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const stack = globalScope.childScopes.slice(); + + while (stack.length) { + const scope = stack.pop(); + + stack.push(...scope.childScopes); + checkForShadows(scope); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-spaced-func.js b/node_modules/eslint/lib/rules/no-spaced-func.js new file mode 100644 index 0000000..d79c184 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-spaced-func.js @@ -0,0 +1,83 @@ +/** + * @fileoverview Rule to check that spaced function application + * @author Matt DuVall + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow spacing between function identifiers and their applications (deprecated)", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-spaced-func" + }, + + deprecated: true, + + replacedBy: ["func-call-spacing"], + + fixable: "whitespace", + schema: [], + + messages: { + noSpacedFunction: "Unexpected space between function name and paren." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Check if open space is present in a function name + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function detectOpenSpaces(node) { + const lastCalleeToken = sourceCode.getLastToken(node.callee); + let prevToken = lastCalleeToken, + parenToken = sourceCode.getTokenAfter(lastCalleeToken); + + // advances to an open parenthesis. + while ( + parenToken && + parenToken.range[1] < node.range[1] && + parenToken.value !== "(" + ) { + prevToken = parenToken; + parenToken = sourceCode.getTokenAfter(parenToken); + } + + // look for a space between the callee and the open paren + if (parenToken && + parenToken.range[1] < node.range[1] && + sourceCode.isSpaceBetweenTokens(prevToken, parenToken) + ) { + context.report({ + node, + loc: lastCalleeToken.loc.start, + messageId: "noSpacedFunction", + fix(fixer) { + return fixer.removeRange([prevToken.range[1], parenToken.range[0]]); + } + }); + } + } + + return { + CallExpression: detectOpenSpaces, + NewExpression: detectOpenSpaces + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-sparse-arrays.js b/node_modules/eslint/lib/rules/no-sparse-arrays.js new file mode 100644 index 0000000..c65b0ab --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sparse-arrays.js @@ -0,0 +1,50 @@ +/** + * @fileoverview Disallow sparse arrays + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow sparse arrays", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-sparse-arrays" + }, + + schema: [], + + messages: { + unexpectedSparseArray: "Unexpected comma in middle of array." + } + }, + + create(context) { + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + ArrayExpression(node) { + + const emptySpot = node.elements.includes(null); + + if (emptySpot) { + context.report({ node, messageId: "unexpectedSparseArray" }); + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-sync.js b/node_modules/eslint/lib/rules/no-sync.js new file mode 100644 index 0000000..8f79a36 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sync.js @@ -0,0 +1,64 @@ +/** + * @fileoverview Rule to check for properties whose identifier ends with the string Sync + * @author Matt DuVall + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "Disallow synchronous methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-sync" + }, + + schema: [ + { + type: "object", + properties: { + allowAtRootLevel: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + noSync: "Unexpected sync method: '{{propertyName}}'." + } + }, + + create(context) { + const selector = context.options[0] && context.options[0].allowAtRootLevel + ? ":function MemberExpression[property.name=/.*Sync$/]" + : "MemberExpression[property.name=/.*Sync$/]"; + + return { + [selector](node) { + context.report({ + node, + messageId: "noSync", + data: { + propertyName: node.property.name + } + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-tabs.js b/node_modules/eslint/lib/rules/no-tabs.js new file mode 100644 index 0000000..b33690c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-tabs.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Rule to check for tabs inside a file + * @author Gyandeep Singh + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const tabRegex = /\t+/gu; +const anyNonWhitespaceRegex = /\S/u; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow all tabs", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-tabs" + }, + schema: [{ + type: "object", + properties: { + allowIndentationTabs: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + + messages: { + unexpectedTab: "Unexpected tab character." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const allowIndentationTabs = context.options && context.options[0] && context.options[0].allowIndentationTabs; + + return { + Program(node) { + sourceCode.getLines().forEach((line, index) => { + let match; + + while ((match = tabRegex.exec(line)) !== null) { + if (allowIndentationTabs && !anyNonWhitespaceRegex.test(line.slice(0, match.index))) { + continue; + } + + context.report({ + node, + loc: { + start: { + line: index + 1, + column: match.index + }, + end: { + line: index + 1, + column: match.index + match[0].length + } + }, + messageId: "unexpectedTab" + }); + } + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-template-curly-in-string.js b/node_modules/eslint/lib/rules/no-template-curly-in-string.js new file mode 100644 index 0000000..92b4c1c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-template-curly-in-string.js @@ -0,0 +1,44 @@ +/** + * @fileoverview Warn when using template string syntax in regular strings + * @author Jeroen Engels + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow template literal placeholder syntax in regular strings", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-template-curly-in-string" + }, + + schema: [], + + messages: { + unexpectedTemplateExpression: "Unexpected template string expression." + } + }, + + create(context) { + const regex = /\$\{[^}]+\}/u; + + return { + Literal(node) { + if (typeof node.value === "string" && regex.test(node.value)) { + context.report({ + node, + messageId: "unexpectedTemplateExpression" + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-ternary.js b/node_modules/eslint/lib/rules/no-ternary.js new file mode 100644 index 0000000..4d43c7e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-ternary.js @@ -0,0 +1,41 @@ +/** + * @fileoverview Rule to flag use of ternary operators. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow ternary operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-ternary" + }, + + schema: [], + + messages: { + noTernaryOperator: "Ternary operator used." + } + }, + + create(context) { + + return { + + ConditionalExpression(node) { + context.report({ node, messageId: "noTernaryOperator" }); + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-this-before-super.js b/node_modules/eslint/lib/rules/no-this-before-super.js new file mode 100644 index 0000000..139bb66 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-this-before-super.js @@ -0,0 +1,304 @@ +/** + * @fileoverview A rule to disallow using `this`/`super` before `super()`. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a constructor. + * @param {ASTNode} node A node to check. This node type is one of + * `Program`, `FunctionDeclaration`, `FunctionExpression`, and + * `ArrowFunctionExpression`. + * @returns {boolean} `true` if the node is a constructor. + */ +function isConstructorFunction(node) { + return ( + node.type === "FunctionExpression" && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor" + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow `this`/`super` before calling `super()` in constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-this-before-super" + }, + + schema: [], + + messages: { + noBeforeSuper: "'{{kind}}' is not allowed before 'super()'." + } + }, + + create(context) { + + /* + * Information for each constructor. + * - upper: Information of the upper constructor. + * - hasExtends: A flag which shows whether the owner class has a valid + * `extends` part. + * - scope: The scope of the owner class. + * - codePath: The code path of this constructor. + */ + let funcInfo = null; + + /* + * Information for each code path segment. + * Each key is the id of a code path segment. + * Each value is an object: + * - superCalled: The flag which shows `super()` called in all code paths. + * - invalidNodes: The array of invalid ThisExpression and Super nodes. + */ + let segInfoMap = Object.create(null); + + /** + * Gets whether or not `super()` is called in a given code path segment. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} `true` if `super()` is called. + */ + function isCalled(segment) { + return !segment.reachable || segInfoMap[segment.id].superCalled; + } + + /** + * Checks whether or not this is in a constructor. + * @returns {boolean} `true` if this is in a constructor. + */ + function isInConstructorOfDerivedClass() { + return Boolean(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends); + } + + /** + * Checks whether or not this is before `super()` is called. + * @returns {boolean} `true` if this is before `super()` is called. + */ + function isBeforeCallOfSuper() { + return ( + isInConstructorOfDerivedClass() && + !funcInfo.codePath.currentSegments.every(isCalled) + ); + } + + /** + * Sets a given node as invalid. + * @param {ASTNode} node A node to set as invalid. This is one of + * a ThisExpression and a Super. + * @returns {void} + */ + function setInvalid(node) { + const segments = funcInfo.codePath.currentSegments; + + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + if (segment.reachable) { + segInfoMap[segment.id].invalidNodes.push(node); + } + } + } + + /** + * Sets the current segment as `super` was called. + * @returns {void} + */ + function setSuperCalled() { + const segments = funcInfo.codePath.currentSegments; + + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + if (segment.reachable) { + segInfoMap[segment.id].superCalled = true; + } + } + } + + return { + + /** + * Adds information of a constructor into the stack. + * @param {CodePath} codePath A code path which was started. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathStart(codePath, node) { + if (isConstructorFunction(node)) { + + // Class > ClassBody > MethodDefinition > FunctionExpression + const classNode = node.parent.parent.parent; + + funcInfo = { + upper: funcInfo, + isConstructor: true, + hasExtends: Boolean( + classNode.superClass && + !astUtils.isNullOrUndefined(classNode.superClass) + ), + codePath + }; + } else { + funcInfo = { + upper: funcInfo, + isConstructor: false, + hasExtends: false, + codePath + }; + } + }, + + /** + * Removes the top of stack item. + * + * And this traverses all segments of this code path then reports every + * invalid node. + * @param {CodePath} codePath A code path which was ended. + * @returns {void} + */ + onCodePathEnd(codePath) { + const isDerivedClass = funcInfo.hasExtends; + + funcInfo = funcInfo.upper; + if (!isDerivedClass) { + return; + } + + codePath.traverseSegments((segment, controller) => { + const info = segInfoMap[segment.id]; + + for (let i = 0; i < info.invalidNodes.length; ++i) { + const invalidNode = info.invalidNodes[i]; + + context.report({ + messageId: "noBeforeSuper", + node: invalidNode, + data: { + kind: invalidNode.type === "Super" ? "super" : "this" + } + }); + } + + if (info.superCalled) { + controller.skip(); + } + }); + }, + + /** + * Initialize information of a given code path segment. + * @param {CodePathSegment} segment A code path segment to initialize. + * @returns {void} + */ + onCodePathSegmentStart(segment) { + if (!isInConstructorOfDerivedClass()) { + return; + } + + // Initialize info. + segInfoMap[segment.id] = { + superCalled: ( + segment.prevSegments.length > 0 && + segment.prevSegments.every(isCalled) + ), + invalidNodes: [] + }; + }, + + /** + * Update information of the code path segment when a code path was + * looped. + * @param {CodePathSegment} fromSegment The code path segment of the + * end of a loop. + * @param {CodePathSegment} toSegment A code path segment of the head + * of a loop. + * @returns {void} + */ + onCodePathSegmentLoop(fromSegment, toSegment) { + if (!isInConstructorOfDerivedClass()) { + return; + } + + // Update information inside of the loop. + funcInfo.codePath.traverseSegments( + { first: toSegment, last: fromSegment }, + (segment, controller) => { + const info = segInfoMap[segment.id]; + + if (info.superCalled) { + info.invalidNodes = []; + controller.skip(); + } else if ( + segment.prevSegments.length > 0 && + segment.prevSegments.every(isCalled) + ) { + info.superCalled = true; + info.invalidNodes = []; + } + } + ); + }, + + /** + * Reports if this is before `super()`. + * @param {ASTNode} node A target node. + * @returns {void} + */ + ThisExpression(node) { + if (isBeforeCallOfSuper()) { + setInvalid(node); + } + }, + + /** + * Reports if this is before `super()`. + * @param {ASTNode} node A target node. + * @returns {void} + */ + Super(node) { + if (!astUtils.isCallee(node) && isBeforeCallOfSuper()) { + setInvalid(node); + } + }, + + /** + * Marks `super()` called. + * @param {ASTNode} node A target node. + * @returns {void} + */ + "CallExpression:exit"(node) { + if (node.callee.type === "Super" && isBeforeCallOfSuper()) { + setSuperCalled(); + } + }, + + /** + * Resets state. + * @returns {void} + */ + "Program:exit"() { + segInfoMap = Object.create(null); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-throw-literal.js b/node_modules/eslint/lib/rules/no-throw-literal.js new file mode 100644 index 0000000..07a0df6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-throw-literal.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Rule to restrict what can be thrown as an exception. + * @author Dieter Oberkofler + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow throwing literals as exceptions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-throw-literal" + }, + + schema: [], + + messages: { + object: "Expected an error object to be thrown.", + undef: "Do not throw undefined." + } + }, + + create(context) { + + return { + + ThrowStatement(node) { + if (!astUtils.couldBeError(node.argument)) { + context.report({ node, messageId: "object" }); + } else if (node.argument.type === "Identifier") { + if (node.argument.name === "undefined") { + context.report({ node, messageId: "undef" }); + } + } + + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-trailing-spaces.js b/node_modules/eslint/lib/rules/no-trailing-spaces.js new file mode 100644 index 0000000..1674de5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-trailing-spaces.js @@ -0,0 +1,190 @@ +/** + * @fileoverview Disallow trailing spaces at the end of lines. + * @author Nodeca Team + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow trailing whitespace at the end of lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-trailing-spaces" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + skipBlankLines: { + type: "boolean", + default: false + }, + ignoreComments: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + trailingSpace: "Trailing spaces not allowed." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + const BLANK_CLASS = "[ \t\u00a0\u2000-\u200b\u3000]", + SKIP_BLANK = `^${BLANK_CLASS}*$`, + NONBLANK = `${BLANK_CLASS}+$`; + + const options = context.options[0] || {}, + skipBlankLines = options.skipBlankLines || false, + ignoreComments = options.ignoreComments || false; + + /** + * Report the error message + * @param {ASTNode} node node to report + * @param {int[]} location range information + * @param {int[]} fixRange Range based on the whole program + * @returns {void} + */ + function report(node, location, fixRange) { + + /* + * Passing node is a bit dirty, because message data will contain big + * text in `source`. But... who cares :) ? + * One more kludge will not make worse the bloody wizardry of this + * plugin. + */ + context.report({ + node, + loc: location, + messageId: "trailingSpace", + fix(fixer) { + return fixer.removeRange(fixRange); + } + }); + } + + /** + * Given a list of comment nodes, return the line numbers for those comments. + * @param {Array} comments An array of comment nodes. + * @returns {number[]} An array of line numbers containing comments. + */ + function getCommentLineNumbers(comments) { + const lines = new Set(); + + comments.forEach(comment => { + const endLine = comment.type === "Block" + ? comment.loc.end.line - 1 + : comment.loc.end.line; + + for (let i = comment.loc.start.line; i <= endLine; i++) { + lines.add(i); + } + }); + + return lines; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + Program: function checkTrailingSpaces(node) { + + /* + * Let's hack. Since Espree does not return whitespace nodes, + * fetch the source code and do matching via regexps. + */ + + const re = new RegExp(NONBLANK, "u"), + skipMatch = new RegExp(SKIP_BLANK, "u"), + lines = sourceCode.lines, + linebreaks = sourceCode.getText().match(astUtils.createGlobalLinebreakMatcher()), + comments = sourceCode.getAllComments(), + commentLineNumbers = getCommentLineNumbers(comments); + + let totalLength = 0, + fixRange = []; + + for (let i = 0, ii = lines.length; i < ii; i++) { + const lineNumber = i + 1; + + /* + * Always add linebreak length to line length to accommodate for line break (\n or \r\n) + * Because during the fix time they also reserve one spot in the array. + * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF) + */ + const linebreakLength = linebreaks && linebreaks[i] ? linebreaks[i].length : 1; + const lineLength = lines[i].length + linebreakLength; + + const matches = re.exec(lines[i]); + + if (matches) { + const location = { + start: { + line: lineNumber, + column: matches.index + }, + end: { + line: lineNumber, + column: lineLength - linebreakLength + } + }; + + const rangeStart = totalLength + location.start.column; + const rangeEnd = totalLength + location.end.column; + const containingNode = sourceCode.getNodeByRangeIndex(rangeStart); + + if (containingNode && containingNode.type === "TemplateElement" && + rangeStart > containingNode.parent.range[0] && + rangeEnd < containingNode.parent.range[1]) { + totalLength += lineLength; + continue; + } + + /* + * If the line has only whitespace, and skipBlankLines + * is true, don't report it + */ + if (skipBlankLines && skipMatch.test(lines[i])) { + totalLength += lineLength; + continue; + } + + fixRange = [rangeStart, rangeEnd]; + + if (!ignoreComments || !commentLineNumbers.has(lineNumber)) { + report(node, location, fixRange); + } + } + + totalLength += lineLength; + } + } + + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-undef-init.js b/node_modules/eslint/lib/rules/no-undef-init.js new file mode 100644 index 0000000..be19d6f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undef-init.js @@ -0,0 +1,75 @@ +/** + * @fileoverview Rule to flag when initializing to undefined + * @author Ilya Volodin + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow initializing variables to `undefined`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-undef-init" + }, + + schema: [], + fixable: "code", + + messages: { + unnecessaryUndefinedInit: "It's not necessary to initialize '{{name}}' to undefined." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + return { + + VariableDeclarator(node) { + const name = sourceCode.getText(node.id), + init = node.init && node.init.name, + scope = sourceCode.getScope(node), + undefinedVar = astUtils.getVariableByName(scope, "undefined"), + shadowed = undefinedVar && undefinedVar.defs.length > 0, + lastToken = sourceCode.getLastToken(node); + + if (init === "undefined" && node.parent.kind !== "const" && !shadowed) { + context.report({ + node, + messageId: "unnecessaryUndefinedInit", + data: { name }, + fix(fixer) { + if (node.parent.kind === "var") { + return null; + } + + if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") { + + // Don't fix destructuring assignment to `undefined`. + return null; + } + + if (sourceCode.commentsExistBetween(node.id, lastToken)) { + return null; + } + + return fixer.removeRange([node.id.range[1], node.range[1]]); + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-undef.js b/node_modules/eslint/lib/rules/no-undef.js new file mode 100644 index 0000000..fe47028 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undef.js @@ -0,0 +1,79 @@ +/** + * @fileoverview Rule to flag references to undeclared variables. + * @author Mark Macdonald + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given node is the argument of a typeof operator. + * @param {ASTNode} node The AST node being checked. + * @returns {boolean} Whether or not the node is the argument of a typeof operator. + */ +function hasTypeOfOperator(node) { + const parent = node.parent; + + return parent.type === "UnaryExpression" && parent.operator === "typeof"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow the use of undeclared variables unless mentioned in `/*global */` comments", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-undef" + }, + + schema: [ + { + type: "object", + properties: { + typeof: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + messages: { + undef: "'{{name}}' is not defined." + } + }, + + create(context) { + const options = context.options[0]; + const considerTypeOf = options && options.typeof === true || false; + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.through.forEach(ref => { + const identifier = ref.identifier; + + if (!considerTypeOf && hasTypeOfOperator(identifier)) { + return; + } + + context.report({ + node: identifier, + messageId: "undef", + data: identifier + }); + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-undefined.js b/node_modules/eslint/lib/rules/no-undefined.js new file mode 100644 index 0000000..8f47ca1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undefined.js @@ -0,0 +1,86 @@ +/** + * @fileoverview Rule to flag references to the undefined variable. + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `undefined` as an identifier", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-undefined" + }, + + schema: [], + + messages: { + unexpectedUndefined: "Unexpected use of undefined." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Report an invalid "undefined" identifier node. + * @param {ASTNode} node The node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "unexpectedUndefined" + }); + } + + /** + * Checks the given scope for references to `undefined` and reports + * all references found. + * @param {eslint-scope.Scope} scope The scope to check. + * @returns {void} + */ + function checkScope(scope) { + const undefinedVar = scope.set.get("undefined"); + + if (!undefinedVar) { + return; + } + + const references = undefinedVar.references; + + const defs = undefinedVar.defs; + + // Report non-initializing references (those are covered in defs below) + references + .filter(ref => !ref.init) + .forEach(ref => report(ref.identifier)); + + defs.forEach(def => report(def.name)); + } + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + const stack = [globalScope]; + + while (stack.length) { + const scope = stack.pop(); + + stack.push(...scope.childScopes); + checkScope(scope); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-underscore-dangle.js b/node_modules/eslint/lib/rules/no-underscore-dangle.js new file mode 100644 index 0000000..a0e05c6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-underscore-dangle.js @@ -0,0 +1,335 @@ +/** + * @fileoverview Rule to flag dangling underscores in variable declarations. + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow dangling underscores in identifiers", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-underscore-dangle" + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + type: "string" + } + }, + allowAfterThis: { + type: "boolean", + default: false + }, + allowAfterSuper: { + type: "boolean", + default: false + }, + allowAfterThisConstructor: { + type: "boolean", + default: false + }, + enforceInMethodNames: { + type: "boolean", + default: false + }, + allowFunctionParams: { + type: "boolean", + default: true + }, + enforceInClassFields: { + type: "boolean", + default: false + }, + allowInArrayDestructuring: { + type: "boolean", + default: true + }, + allowInObjectDestructuring: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedUnderscore: "Unexpected dangling '_' in '{{identifier}}'." + } + }, + + create(context) { + + const options = context.options[0] || {}; + const ALLOWED_VARIABLES = options.allow ? options.allow : []; + const allowAfterThis = typeof options.allowAfterThis !== "undefined" ? options.allowAfterThis : false; + const allowAfterSuper = typeof options.allowAfterSuper !== "undefined" ? options.allowAfterSuper : false; + const allowAfterThisConstructor = typeof options.allowAfterThisConstructor !== "undefined" ? options.allowAfterThisConstructor : false; + const enforceInMethodNames = typeof options.enforceInMethodNames !== "undefined" ? options.enforceInMethodNames : false; + const enforceInClassFields = typeof options.enforceInClassFields !== "undefined" ? options.enforceInClassFields : false; + const allowFunctionParams = typeof options.allowFunctionParams !== "undefined" ? options.allowFunctionParams : true; + const allowInArrayDestructuring = typeof options.allowInArrayDestructuring !== "undefined" ? options.allowInArrayDestructuring : true; + const allowInObjectDestructuring = typeof options.allowInObjectDestructuring !== "undefined" ? options.allowInObjectDestructuring : true; + const sourceCode = context.sourceCode; + + //------------------------------------------------------------------------- + // Helpers + //------------------------------------------------------------------------- + + /** + * Check if identifier is present inside the allowed option + * @param {string} identifier name of the node + * @returns {boolean} true if its is present + * @private + */ + function isAllowed(identifier) { + return ALLOWED_VARIABLES.includes(identifier); + } + + /** + * Check if identifier has a dangling underscore + * @param {string} identifier name of the node + * @returns {boolean} true if its is present + * @private + */ + function hasDanglingUnderscore(identifier) { + const len = identifier.length; + + return identifier !== "_" && (identifier[0] === "_" || identifier[len - 1] === "_"); + } + + /** + * Check if identifier is a special case member expression + * @param {string} identifier name of the node + * @returns {boolean} true if its is a special case + * @private + */ + function isSpecialCaseIdentifierForMemberExpression(identifier) { + return identifier === "__proto__"; + } + + /** + * Check if identifier is a special case variable expression + * @param {string} identifier name of the node + * @returns {boolean} true if its is a special case + * @private + */ + function isSpecialCaseIdentifierInVariableExpression(identifier) { + + // Checks for the underscore library usage here + return identifier === "_"; + } + + /** + * Check if a node is a member reference of this.constructor + * @param {ASTNode} node node to evaluate + * @returns {boolean} true if it is a reference on this.constructor + * @private + */ + function isThisConstructorReference(node) { + return node.object.type === "MemberExpression" && + node.object.property.name === "constructor" && + node.object.object.type === "ThisExpression"; + } + + /** + * Check if function parameter has a dangling underscore. + * @param {ASTNode} node function node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInFunctionParameters(node) { + if (!allowFunctionParams) { + node.params.forEach(param => { + const { type } = param; + let nodeToCheck; + + if (type === "RestElement") { + nodeToCheck = param.argument; + } else if (type === "AssignmentPattern") { + nodeToCheck = param.left; + } else { + nodeToCheck = param; + } + + if (nodeToCheck.type === "Identifier") { + const identifier = nodeToCheck.name; + + if (hasDanglingUnderscore(identifier) && !isAllowed(identifier)) { + context.report({ + node: param, + messageId: "unexpectedUnderscore", + data: { + identifier + } + }); + } + } + }); + } + } + + /** + * Check if function has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInFunction(node) { + if (node.type === "FunctionDeclaration" && node.id) { + const identifier = node.id.name; + + if (typeof identifier !== "undefined" && hasDanglingUnderscore(identifier) && !isAllowed(identifier)) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier + } + }); + } + } + checkForDanglingUnderscoreInFunctionParameters(node); + } + + + /** + * Check if variable expression has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInVariableExpression(node) { + sourceCode.getDeclaredVariables(node).forEach(variable => { + const definition = variable.defs.find(def => def.node === node); + const identifierNode = definition.name; + const identifier = identifierNode.name; + let parent = identifierNode.parent; + + while (!["VariableDeclarator", "ArrayPattern", "ObjectPattern"].includes(parent.type)) { + parent = parent.parent; + } + + if ( + hasDanglingUnderscore(identifier) && + !isSpecialCaseIdentifierInVariableExpression(identifier) && + !isAllowed(identifier) && + !(allowInArrayDestructuring && parent.type === "ArrayPattern") && + !(allowInObjectDestructuring && parent.type === "ObjectPattern") + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier + } + }); + } + }); + } + + /** + * Check if member expression has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInMemberExpression(node) { + const identifier = node.property.name, + isMemberOfThis = node.object.type === "ThisExpression", + isMemberOfSuper = node.object.type === "Super", + isMemberOfThisConstructor = isThisConstructorReference(node); + + if (typeof identifier !== "undefined" && hasDanglingUnderscore(identifier) && + !(isMemberOfThis && allowAfterThis) && + !(isMemberOfSuper && allowAfterSuper) && + !(isMemberOfThisConstructor && allowAfterThisConstructor) && + !isSpecialCaseIdentifierForMemberExpression(identifier) && !isAllowed(identifier)) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier + } + }); + } + } + + /** + * Check if method declaration or method property has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInMethod(node) { + const identifier = node.key.name; + const isMethod = node.type === "MethodDefinition" || node.type === "Property" && node.method; + + if (typeof identifier !== "undefined" && enforceInMethodNames && isMethod && hasDanglingUnderscore(identifier) && !isAllowed(identifier)) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier: node.key.type === "PrivateIdentifier" + ? `#${identifier}` + : identifier + } + }); + } + } + + /** + * Check if a class field has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInClassField(node) { + const identifier = node.key.name; + + if (typeof identifier !== "undefined" && hasDanglingUnderscore(identifier) && + enforceInClassFields && + !isAllowed(identifier)) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier: node.key.type === "PrivateIdentifier" + ? `#${identifier}` + : identifier + } + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: checkForDanglingUnderscoreInFunction, + VariableDeclarator: checkForDanglingUnderscoreInVariableExpression, + MemberExpression: checkForDanglingUnderscoreInMemberExpression, + MethodDefinition: checkForDanglingUnderscoreInMethod, + PropertyDefinition: checkForDanglingUnderscoreInClassField, + Property: checkForDanglingUnderscoreInMethod, + FunctionExpression: checkForDanglingUnderscoreInFunction, + ArrowFunctionExpression: checkForDanglingUnderscoreInFunction + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-unexpected-multiline.js b/node_modules/eslint/lib/rules/no-unexpected-multiline.js new file mode 100644 index 0000000..810c08b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unexpected-multiline.js @@ -0,0 +1,120 @@ +/** + * @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not. + * @author Glen Mailer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow confusing multiline expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unexpected-multiline" + }, + + schema: [], + messages: { + function: "Unexpected newline between function and ( of function call.", + property: "Unexpected newline between object and [ of property access.", + taggedTemplate: "Unexpected newline between template tag and template literal.", + division: "Unexpected newline between numerator and division operator." + } + }, + + create(context) { + + const REGEX_FLAG_MATCHER = /^[gimsuy]+$/u; + + const sourceCode = context.sourceCode; + + /** + * Check to see if there is a newline between the node and the following open bracket + * line's expression + * @param {ASTNode} node The node to check. + * @param {string} messageId The error messageId to use. + * @returns {void} + * @private + */ + function checkForBreakAfter(node, messageId) { + const openParen = sourceCode.getTokenAfter(node, astUtils.isNotClosingParenToken); + const nodeExpressionEnd = sourceCode.getTokenBefore(openParen); + + if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { + context.report({ + node, + loc: openParen.loc, + messageId + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + MemberExpression(node) { + if (!node.computed || node.optional) { + return; + } + checkForBreakAfter(node.object, "property"); + }, + + TaggedTemplateExpression(node) { + const { quasi } = node; + + // handles common tags, parenthesized tags, and typescript's generic type arguments + const tokenBefore = sourceCode.getTokenBefore(quasi); + + if (tokenBefore.loc.end.line !== quasi.loc.start.line) { + context.report({ + node, + loc: { + start: quasi.loc.start, + end: { + line: quasi.loc.start.line, + column: quasi.loc.start.column + 1 + } + }, + messageId: "taggedTemplate" + }); + } + }, + + CallExpression(node) { + if (node.arguments.length === 0 || node.optional) { + return; + } + checkForBreakAfter(node.callee, "function"); + }, + + "BinaryExpression[operator='/'] > BinaryExpression[operator='/'].left"(node) { + const secondSlash = sourceCode.getTokenAfter(node, token => token.value === "/"); + const tokenAfterOperator = sourceCode.getTokenAfter(secondSlash); + + if ( + tokenAfterOperator.type === "Identifier" && + REGEX_FLAG_MATCHER.test(tokenAfterOperator.value) && + secondSlash.range[1] === tokenAfterOperator.range[0] + ) { + checkForBreakAfter(node.left, "division"); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js b/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js new file mode 100644 index 0000000..768a155 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js @@ -0,0 +1,360 @@ +/** + * @fileoverview Rule to disallow use of unmodified expressions in loop conditions + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Traverser = require("../shared/traverser"), + astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_PATTERN = /(?:(?:Call|Class|Function|Member|New|Yield)Expression|Statement|Declaration)$/u; +const LOOP_PATTERN = /^(?:DoWhile|For|While)Statement$/u; // for-in/of statements don't have `test` property. +const GROUP_PATTERN = /^(?:BinaryExpression|ConditionalExpression)$/u; +const SKIP_PATTERN = /^(?:ArrowFunction|Class|Function)Expression$/u; +const DYNAMIC_PATTERN = /^(?:Call|Member|New|TaggedTemplate|Yield)Expression$/u; + +/** + * @typedef {Object} LoopConditionInfo + * @property {eslint-scope.Reference} reference - The reference. + * @property {ASTNode} group - BinaryExpression or ConditionalExpression nodes + * that the reference is belonging to. + * @property {Function} isInLoop - The predicate which checks a given reference + * is in this loop. + * @property {boolean} modified - The flag that the reference is modified in + * this loop. + */ + +/** + * Checks whether or not a given reference is a write reference. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is a write reference. + */ +function isWriteReference(reference) { + if (reference.init) { + const def = reference.resolved && reference.resolved.defs[0]; + + if (!def || def.type !== "Variable" || def.parent.kind !== "var") { + return false; + } + } + return reference.isWrite(); +} + +/** + * Checks whether or not a given loop condition info does not have the modified + * flag. + * @param {LoopConditionInfo} condition A loop condition info to check. + * @returns {boolean} `true` if the loop condition info is "unmodified". + */ +function isUnmodified(condition) { + return !condition.modified; +} + +/** + * Checks whether or not a given loop condition info does not have the modified + * flag and does not have the group this condition belongs to. + * @param {LoopConditionInfo} condition A loop condition info to check. + * @returns {boolean} `true` if the loop condition info is "unmodified". + */ +function isUnmodifiedAndNotBelongToGroup(condition) { + return !(condition.modified || condition.group); +} + +/** + * Checks whether or not a given reference is inside of a given node. + * @param {ASTNode} node A node to check. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the node. + */ +function isInRange(node, reference) { + const or = node.range; + const ir = reference.identifier.range; + + return or[0] <= ir[0] && ir[1] <= or[1]; +} + +/** + * Checks whether or not a given reference is inside of a loop node's condition. + * @param {ASTNode} node A node to check. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the loop node's + * condition. + */ +const isInLoop = { + WhileStatement: isInRange, + DoWhileStatement: isInRange, + ForStatement(node, reference) { + return ( + isInRange(node, reference) && + !(node.init && isInRange(node.init, reference)) + ); + } +}; + +/** + * Gets the function which encloses a given reference. + * This supports only FunctionDeclaration. + * @param {eslint-scope.Reference} reference A reference to get. + * @returns {ASTNode|null} The function node or null. + */ +function getEncloseFunctionDeclaration(reference) { + let node = reference.identifier; + + while (node) { + if (node.type === "FunctionDeclaration") { + return node.id ? node : null; + } + + node = node.parent; + } + + return null; +} + +/** + * Updates the "modified" flags of given loop conditions with given modifiers. + * @param {LoopConditionInfo[]} conditions The loop conditions to be updated. + * @param {eslint-scope.Reference[]} modifiers The references to update. + * @returns {void} + */ +function updateModifiedFlag(conditions, modifiers) { + + for (let i = 0; i < conditions.length; ++i) { + const condition = conditions[i]; + + for (let j = 0; !condition.modified && j < modifiers.length; ++j) { + const modifier = modifiers[j]; + let funcNode, funcVar; + + /* + * Besides checking for the condition being in the loop, we want to + * check the function that this modifier is belonging to is called + * in the loop. + * FIXME: This should probably be extracted to a function. + */ + const inLoop = condition.isInLoop(modifier) || Boolean( + (funcNode = getEncloseFunctionDeclaration(modifier)) && + (funcVar = astUtils.getVariableByName(modifier.from.upper, funcNode.id.name)) && + funcVar.references.some(condition.isInLoop) + ); + + condition.modified = inLoop; + } + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unmodified loop conditions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unmodified-loop-condition" + }, + + schema: [], + + messages: { + loopConditionNotModified: "'{{name}}' is not modified in this loop." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + let groupMap = null; + + /** + * Reports a given condition info. + * @param {LoopConditionInfo} condition A loop condition info to report. + * @returns {void} + */ + function report(condition) { + const node = condition.reference.identifier; + + context.report({ + node, + messageId: "loopConditionNotModified", + data: node + }); + } + + /** + * Registers given conditions to the group the condition belongs to. + * @param {LoopConditionInfo[]} conditions A loop condition info to + * register. + * @returns {void} + */ + function registerConditionsToGroup(conditions) { + for (let i = 0; i < conditions.length; ++i) { + const condition = conditions[i]; + + if (condition.group) { + let group = groupMap.get(condition.group); + + if (!group) { + group = []; + groupMap.set(condition.group, group); + } + group.push(condition); + } + } + } + + /** + * Reports references which are inside of unmodified groups. + * @param {LoopConditionInfo[]} conditions A loop condition info to report. + * @returns {void} + */ + function checkConditionsInGroup(conditions) { + if (conditions.every(isUnmodified)) { + conditions.forEach(report); + } + } + + /** + * Checks whether or not a given group node has any dynamic elements. + * @param {ASTNode} root A node to check. + * This node is one of BinaryExpression or ConditionalExpression. + * @returns {boolean} `true` if the node is dynamic. + */ + function hasDynamicExpressions(root) { + let retv = false; + + Traverser.traverse(root, { + visitorKeys: sourceCode.visitorKeys, + enter(node) { + if (DYNAMIC_PATTERN.test(node.type)) { + retv = true; + this.break(); + } else if (SKIP_PATTERN.test(node.type)) { + this.skip(); + } + } + }); + + return retv; + } + + /** + * Creates the loop condition information from a given reference. + * @param {eslint-scope.Reference} reference A reference to create. + * @returns {LoopConditionInfo|null} Created loop condition info, or null. + */ + function toLoopCondition(reference) { + if (reference.init) { + return null; + } + + let group = null; + let child = reference.identifier; + let node = child.parent; + + while (node) { + if (SENTINEL_PATTERN.test(node.type)) { + if (LOOP_PATTERN.test(node.type) && node.test === child) { + + // This reference is inside of a loop condition. + return { + reference, + group, + isInLoop: isInLoop[node.type].bind(null, node), + modified: false + }; + } + + // This reference is outside of a loop condition. + break; + } + + /* + * If it's inside of a group, OK if either operand is modified. + * So stores the group this reference belongs to. + */ + if (GROUP_PATTERN.test(node.type)) { + + // If this expression is dynamic, no need to check. + if (hasDynamicExpressions(node)) { + break; + } else { + group = node; + } + } + + child = node; + node = node.parent; + } + + return null; + } + + /** + * Finds unmodified references which are inside of a loop condition. + * Then reports the references which are outside of groups. + * @param {eslint-scope.Variable} variable A variable to report. + * @returns {void} + */ + function checkReferences(variable) { + + // Gets references that exist in loop conditions. + const conditions = variable + .references + .map(toLoopCondition) + .filter(Boolean); + + if (conditions.length === 0) { + return; + } + + // Registers the conditions to belonging groups. + registerConditionsToGroup(conditions); + + // Check the conditions are modified. + const modifiers = variable.references.filter(isWriteReference); + + if (modifiers.length > 0) { + updateModifiedFlag(conditions, modifiers); + } + + /* + * Reports the conditions which are not belonging to groups. + * Others will be reported after all variables are done. + */ + conditions + .filter(isUnmodifiedAndNotBelongToGroup) + .forEach(report); + } + + return { + "Program:exit"(node) { + const queue = [sourceCode.getScope(node)]; + + groupMap = new Map(); + + let scope; + + while ((scope = queue.pop())) { + queue.push(...scope.childScopes); + scope.variables.forEach(checkReferences); + } + + groupMap.forEach(checkConditionsInGroup); + groupMap = null; + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unneeded-ternary.js b/node_modules/eslint/lib/rules/no-unneeded-ternary.js new file mode 100644 index 0000000..ab1bdc5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unneeded-ternary.js @@ -0,0 +1,166 @@ +/** + * @fileoverview Rule to flag no-unneeded-ternary + * @author Gyandeep Singh + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +// Operators that always result in a boolean value +const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]); +const OPERATOR_INVERSES = { + "==": "!=", + "!=": "==", + "===": "!==", + "!==": "===" + + // Operators like < and >= are not true inverses, since both will return false with NaN. +}; +const OR_PRECEDENCE = astUtils.getPrecedence({ type: "LogicalExpression", operator: "||" }); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow ternary operators when simpler alternatives exist", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unneeded-ternary" + }, + + schema: [ + { + type: "object", + properties: { + defaultAssignment: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + fixable: "code", + + messages: { + unnecessaryConditionalExpression: "Unnecessary use of boolean literals in conditional expression.", + unnecessaryConditionalAssignment: "Unnecessary use of conditional expression for default assignment." + } + }, + + create(context) { + const options = context.options[0] || {}; + const defaultAssignment = options.defaultAssignment !== false; + const sourceCode = context.sourceCode; + + /** + * Test if the node is a boolean literal + * @param {ASTNode} node The node to report. + * @returns {boolean} True if the its a boolean literal + * @private + */ + function isBooleanLiteral(node) { + return node.type === "Literal" && typeof node.value === "boolean"; + } + + /** + * Creates an expression that represents the boolean inverse of the expression represented by the original node + * @param {ASTNode} node A node representing an expression + * @returns {string} A string representing an inverted expression + */ + function invertExpression(node) { + if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator + ); + const text = sourceCode.getText(); + + return text.slice(node.range[0], + operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + text.slice(operatorToken.range[1], node.range[1]); + } + + if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) { + return `!(${astUtils.getParenthesisedText(sourceCode, node)})`; + } + return `!${astUtils.getParenthesisedText(sourceCode, node)}`; + } + + /** + * Tests if a given node always evaluates to a boolean value + * @param {ASTNode} node An expression node + * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value + */ + function isBooleanExpression(node) { + return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) || + node.type === "UnaryExpression" && node.operator === "!"; + } + + /** + * Test if the node matches the pattern id ? id : expression + * @param {ASTNode} node The ConditionalExpression to check. + * @returns {boolean} True if the pattern is matched, and false otherwise + * @private + */ + function matchesDefaultAssignment(node) { + return node.test.type === "Identifier" && + node.consequent.type === "Identifier" && + node.test.name === node.consequent.name; + } + + return { + + ConditionalExpression(node) { + if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) { + context.report({ + node, + messageId: "unnecessaryConditionalExpression", + fix(fixer) { + if (node.consequent.value === node.alternate.value) { + + // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true` + return node.test.type === "Identifier" ? fixer.replaceText(node, node.consequent.value.toString()) : null; + } + if (node.alternate.value) { + + // Replace `foo() ? false : true` with `!(foo())` + return fixer.replaceText(node, invertExpression(node.test)); + } + + // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise. + + return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`); + } + }); + } else if (!defaultAssignment && matchesDefaultAssignment(node)) { + context.report({ + node, + messageId: "unnecessaryConditionalAssignment", + fix(fixer) { + const shouldParenthesizeAlternate = + ( + astUtils.getPrecedence(node.alternate) < OR_PRECEDENCE || + astUtils.isCoalesceExpression(node.alternate) + ) && + !astUtils.isParenthesised(sourceCode, node.alternate); + const alternateText = shouldParenthesizeAlternate + ? `(${sourceCode.getText(node.alternate)})` + : astUtils.getParenthesisedText(sourceCode, node.alternate); + const testText = astUtils.getParenthesisedText(sourceCode, node.test); + + return fixer.replaceText(node, `${testText} || ${alternateText}`); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unreachable-loop.js b/node_modules/eslint/lib/rules/no-unreachable-loop.js new file mode 100644 index 0000000..1df764e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unreachable-loop.js @@ -0,0 +1,150 @@ +/** + * @fileoverview Rule to disallow loops with a body that allows only one iteration + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const allLoopTypes = ["WhileStatement", "DoWhileStatement", "ForStatement", "ForInStatement", "ForOfStatement"]; + +/** + * Determines whether the given node is the first node in the code path to which a loop statement + * 'loops' for the next iteration. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a looping target. + */ +function isLoopingTarget(node) { + const parent = node.parent; + + if (parent) { + switch (parent.type) { + case "WhileStatement": + return node === parent.test; + case "DoWhileStatement": + return node === parent.body; + case "ForStatement": + return node === (parent.update || parent.test || parent.body); + case "ForInStatement": + case "ForOfStatement": + return node === parent.left; + + // no default + } + } + + return false; +} + +/** + * Creates an array with elements from the first given array that are not included in the second given array. + * @param {Array} arrA The array to compare from. + * @param {Array} arrB The array to compare against. + * @returns {Array} a new array that represents `arrA \ arrB`. + */ +function getDifference(arrA, arrB) { + return arrA.filter(a => !arrB.includes(a)); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow loops with a body that allows only one iteration", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unreachable-loop" + }, + + schema: [{ + type: "object", + properties: { + ignore: { + type: "array", + items: { + enum: allLoopTypes + }, + uniqueItems: true + } + }, + additionalProperties: false + }], + + messages: { + invalid: "Invalid loop. Its body allows only one iteration." + } + }, + + create(context) { + const ignoredLoopTypes = context.options[0] && context.options[0].ignore || [], + loopTypesToCheck = getDifference(allLoopTypes, ignoredLoopTypes), + loopSelector = loopTypesToCheck.join(","), + loopsByTargetSegments = new Map(), + loopsToReport = new Set(); + + let currentCodePath = null; + + return { + onCodePathStart(codePath) { + currentCodePath = codePath; + }, + + onCodePathEnd() { + currentCodePath = currentCodePath.upper; + }, + + [loopSelector](node) { + + /** + * Ignore unreachable loop statements to avoid unnecessary complexity in the implementation, or false positives otherwise. + * For unreachable segments, the code path analysis does not raise events required for this implementation. + */ + if (currentCodePath.currentSegments.some(segment => segment.reachable)) { + loopsToReport.add(node); + } + }, + + onCodePathSegmentStart(segment, node) { + if (isLoopingTarget(node)) { + const loop = node.parent; + + loopsByTargetSegments.set(segment, loop); + } + }, + + onCodePathSegmentLoop(_, toSegment, node) { + const loop = loopsByTargetSegments.get(toSegment); + + /** + * The second iteration is reachable, meaning that the loop is valid by the logic of this rule, + * only if there is at least one loop event with the appropriate target (which has been already + * determined in the `loopsByTargetSegments` map), raised from either: + * + * - the end of the loop's body (in which case `node === loop`) + * - a `continue` statement + * + * This condition skips loop events raised from `ForInStatement > .right` and `ForOfStatement > .right` nodes. + */ + if (node === loop || node.type === "ContinueStatement") { + + // Removes loop if it exists in the set. Otherwise, `Set#delete` has no effect and doesn't throw. + loopsToReport.delete(loop); + } + }, + + "Program:exit"() { + loopsToReport.forEach( + node => context.report({ node, messageId: "invalid" }) + ); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unreachable.js b/node_modules/eslint/lib/rules/no-unreachable.js new file mode 100644 index 0000000..6216a73 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unreachable.js @@ -0,0 +1,264 @@ +/** + * @fileoverview Checks for unreachable code due to return, throws, break, and continue. + * @author Joel Feenstra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * @typedef {Object} ConstructorInfo + * @property {ConstructorInfo | null} upper Info about the constructor that encloses this constructor. + * @property {boolean} hasSuperCall The flag about having `super()` expressions. + */ + +/** + * Checks whether or not a given variable declarator has the initializer. + * @param {ASTNode} node A VariableDeclarator node to check. + * @returns {boolean} `true` if the node has the initializer. + */ +function isInitialized(node) { + return Boolean(node.init); +} + +/** + * Checks whether or not a given code path segment is unreachable. + * @param {CodePathSegment} segment A CodePathSegment to check. + * @returns {boolean} `true` if the segment is unreachable. + */ +function isUnreachable(segment) { + return !segment.reachable; +} + +/** + * The class to distinguish consecutive unreachable statements. + */ +class ConsecutiveRange { + constructor(sourceCode) { + this.sourceCode = sourceCode; + this.startNode = null; + this.endNode = null; + } + + /** + * The location object of this range. + * @type {Object} + */ + get location() { + return { + start: this.startNode.loc.start, + end: this.endNode.loc.end + }; + } + + /** + * `true` if this range is empty. + * @type {boolean} + */ + get isEmpty() { + return !(this.startNode && this.endNode); + } + + /** + * Checks whether the given node is inside of this range. + * @param {ASTNode|Token} node The node to check. + * @returns {boolean} `true` if the node is inside of this range. + */ + contains(node) { + return ( + node.range[0] >= this.startNode.range[0] && + node.range[1] <= this.endNode.range[1] + ); + } + + /** + * Checks whether the given node is consecutive to this range. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is consecutive to this range. + */ + isConsecutive(node) { + return this.contains(this.sourceCode.getTokenBefore(node)); + } + + /** + * Merges the given node to this range. + * @param {ASTNode} node The node to merge. + * @returns {void} + */ + merge(node) { + this.endNode = node; + } + + /** + * Resets this range by the given node or null. + * @param {ASTNode|null} node The node to reset, or null. + * @returns {void} + */ + reset(node) { + this.startNode = this.endNode = node; + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unreachable code after `return`, `throw`, `continue`, and `break` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unreachable" + }, + + schema: [], + + messages: { + unreachableCode: "Unreachable code." + } + }, + + create(context) { + let currentCodePath = null; + + /** @type {ConstructorInfo | null} */ + let constructorInfo = null; + + /** @type {ConsecutiveRange} */ + const range = new ConsecutiveRange(context.sourceCode); + + /** + * Reports a given node if it's unreachable. + * @param {ASTNode} node A statement node to report. + * @returns {void} + */ + function reportIfUnreachable(node) { + let nextNode = null; + + if (node && (node.type === "PropertyDefinition" || currentCodePath.currentSegments.every(isUnreachable))) { + + // Store this statement to distinguish consecutive statements. + if (range.isEmpty) { + range.reset(node); + return; + } + + // Skip if this statement is inside of the current range. + if (range.contains(node)) { + return; + } + + // Merge if this statement is consecutive to the current range. + if (range.isConsecutive(node)) { + range.merge(node); + return; + } + + nextNode = node; + } + + /* + * Report the current range since this statement is reachable or is + * not consecutive to the current range. + */ + if (!range.isEmpty) { + context.report({ + messageId: "unreachableCode", + loc: range.location, + node: range.startNode + }); + } + + // Update the current range. + range.reset(nextNode); + } + + return { + + // Manages the current code path. + onCodePathStart(codePath) { + currentCodePath = codePath; + }, + + onCodePathEnd() { + currentCodePath = currentCodePath.upper; + }, + + // Registers for all statement nodes (excludes FunctionDeclaration). + BlockStatement: reportIfUnreachable, + BreakStatement: reportIfUnreachable, + ClassDeclaration: reportIfUnreachable, + ContinueStatement: reportIfUnreachable, + DebuggerStatement: reportIfUnreachable, + DoWhileStatement: reportIfUnreachable, + ExpressionStatement: reportIfUnreachable, + ForInStatement: reportIfUnreachable, + ForOfStatement: reportIfUnreachable, + ForStatement: reportIfUnreachable, + IfStatement: reportIfUnreachable, + ImportDeclaration: reportIfUnreachable, + LabeledStatement: reportIfUnreachable, + ReturnStatement: reportIfUnreachable, + SwitchStatement: reportIfUnreachable, + ThrowStatement: reportIfUnreachable, + TryStatement: reportIfUnreachable, + + VariableDeclaration(node) { + if (node.kind !== "var" || node.declarations.some(isInitialized)) { + reportIfUnreachable(node); + } + }, + + WhileStatement: reportIfUnreachable, + WithStatement: reportIfUnreachable, + ExportNamedDeclaration: reportIfUnreachable, + ExportDefaultDeclaration: reportIfUnreachable, + ExportAllDeclaration: reportIfUnreachable, + + "Program:exit"() { + reportIfUnreachable(); + }, + + /* + * Instance fields defined in a subclass are never created if the constructor of the subclass + * doesn't call `super()`, so their definitions are unreachable code. + */ + "MethodDefinition[kind='constructor']"() { + constructorInfo = { + upper: constructorInfo, + hasSuperCall: false + }; + }, + "MethodDefinition[kind='constructor']:exit"(node) { + const { hasSuperCall } = constructorInfo; + + constructorInfo = constructorInfo.upper; + + // skip typescript constructors without the body + if (!node.value.body) { + return; + } + + const classDefinition = node.parent.parent; + + if (classDefinition.superClass && !hasSuperCall) { + for (const element of classDefinition.body.body) { + if (element.type === "PropertyDefinition" && !element.static) { + reportIfUnreachable(element); + } + } + } + }, + "CallExpression > Super.callee"() { + if (constructorInfo) { + constructorInfo.hasSuperCall = true; + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-finally.js b/node_modules/eslint/lib/rules/no-unsafe-finally.js new file mode 100644 index 0000000..ebd2432 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-finally.js @@ -0,0 +1,111 @@ +/** + * @fileoverview Rule to flag unsafe statements in finally block + * @author Onur Temizkan + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_NODE_TYPE_RETURN_THROW = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/u; +const SENTINEL_NODE_TYPE_BREAK = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/u; +const SENTINEL_NODE_TYPE_CONTINUE = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/u; + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow control flow statements in `finally` blocks", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-finally" + }, + + schema: [], + + messages: { + unsafeUsage: "Unsafe usage of {{nodeType}}." + } + }, + create(context) { + + /** + * Checks if the node is the finalizer of a TryStatement + * @param {ASTNode} node node to check. + * @returns {boolean} - true if the node is the finalizer of a TryStatement + */ + function isFinallyBlock(node) { + return node.parent.type === "TryStatement" && node.parent.finalizer === node; + } + + /** + * Climbs up the tree if the node is not a sentinel node + * @param {ASTNode} node node to check. + * @param {string} label label of the break or continue statement + * @returns {boolean} - return whether the node is a finally block or a sentinel node + */ + function isInFinallyBlock(node, label) { + let labelInside = false; + let sentinelNodeType; + + if (node.type === "BreakStatement" && !node.label) { + sentinelNodeType = SENTINEL_NODE_TYPE_BREAK; + } else if (node.type === "ContinueStatement") { + sentinelNodeType = SENTINEL_NODE_TYPE_CONTINUE; + } else { + sentinelNodeType = SENTINEL_NODE_TYPE_RETURN_THROW; + } + + for ( + let currentNode = node; + currentNode && !sentinelNodeType.test(currentNode.type); + currentNode = currentNode.parent + ) { + if (currentNode.parent.label && label && (currentNode.parent.label.name === label.name)) { + labelInside = true; + } + if (isFinallyBlock(currentNode)) { + if (label && labelInside) { + return false; + } + return true; + } + } + return false; + } + + /** + * Checks whether the possibly-unsafe statement is inside a finally block. + * @param {ASTNode} node node to check. + * @returns {void} + */ + function check(node) { + if (isInFinallyBlock(node, node.label)) { + context.report({ + messageId: "unsafeUsage", + data: { + nodeType: node.type + }, + node, + line: node.loc.line, + column: node.loc.column + }); + } + } + + return { + ReturnStatement: check, + ThrowStatement: check, + BreakStatement: check, + ContinueStatement: check + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-negation.js b/node_modules/eslint/lib/rules/no-unsafe-negation.js new file mode 100644 index 0000000..cabd7e2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-negation.js @@ -0,0 +1,128 @@ +/** + * @fileoverview Rule to disallow negating the left operand of relational operators + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given operator is `in` or `instanceof` + * @param {string} op The operator type to check. + * @returns {boolean} `true` if the operator is `in` or `instanceof` + */ +function isInOrInstanceOfOperator(op) { + return op === "in" || op === "instanceof"; +} + +/** + * Checks whether the given operator is an ordering relational operator or not. + * @param {string} op The operator type to check. + * @returns {boolean} `true` if the operator is an ordering relational operator. + */ +function isOrderingRelationalOperator(op) { + return op === "<" || op === ">" || op === ">=" || op === "<="; +} + +/** + * Checks whether the given node is a logical negation expression or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a logical negation expression. + */ +function isNegation(node) { + return node.type === "UnaryExpression" && node.operator === "!"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow negating the left operand of relational operators", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-negation" + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + enforceForOrderingRelations: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + fixable: null, + + messages: { + unexpected: "Unexpected negating the left operand of '{{operator}}' operator.", + suggestNegatedExpression: "Negate '{{operator}}' expression instead of its left operand. This changes the current behavior.", + suggestParenthesisedNegation: "Wrap negation in '()' to make the intention explicit. This preserves the current behavior." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = context.options[0] || {}; + const enforceForOrderingRelations = options.enforceForOrderingRelations === true; + + return { + BinaryExpression(node) { + const operator = node.operator; + const orderingRelationRuleApplies = enforceForOrderingRelations && isOrderingRelationalOperator(operator); + + if ( + (isInOrInstanceOfOperator(operator) || orderingRelationRuleApplies) && + isNegation(node.left) && + !astUtils.isParenthesised(sourceCode, node.left) + ) { + context.report({ + node, + loc: node.left.loc, + messageId: "unexpected", + data: { operator }, + suggest: [ + { + messageId: "suggestNegatedExpression", + data: { operator }, + fix(fixer) { + const negationToken = sourceCode.getFirstToken(node.left); + const fixRange = [negationToken.range[1], node.range[1]]; + const text = sourceCode.text.slice(fixRange[0], fixRange[1]); + + return fixer.replaceTextRange(fixRange, `(${text})`); + } + }, + { + messageId: "suggestParenthesisedNegation", + fix(fixer) { + return fixer.replaceText(node.left, `(${sourceCode.getText(node.left)})`); + } + } + ] + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js b/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js new file mode 100644 index 0000000..fe2bead --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js @@ -0,0 +1,205 @@ +/** + * @fileoverview Rule to disallow unsafe optional chaining + * @author Yeon JuAn + */ + +"use strict"; + +const UNSAFE_ARITHMETIC_OPERATORS = new Set(["+", "-", "/", "*", "%", "**"]); +const UNSAFE_ASSIGNMENT_OPERATORS = new Set(["+=", "-=", "/=", "*=", "%=", "**="]); +const UNSAFE_RELATIONAL_OPERATORS = new Set(["in", "instanceof"]); + +/** + * Checks whether a node is a destructuring pattern or not + * @param {ASTNode} node node to check + * @returns {boolean} `true` if a node is a destructuring pattern, otherwise `false` + */ +function isDestructuringPattern(node) { + return node.type === "ObjectPattern" || node.type === "ArrayPattern"; +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow use of optional chaining in contexts where the `undefined` value is not allowed", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-optional-chaining" + }, + schema: [{ + type: "object", + properties: { + disallowArithmeticOperators: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + fixable: null, + messages: { + unsafeOptionalChain: "Unsafe usage of optional chaining. If it short-circuits with 'undefined' the evaluation will throw TypeError.", + unsafeArithmetic: "Unsafe arithmetic operation on optional chaining. It can result in NaN." + } + }, + + create(context) { + const options = context.options[0] || {}; + const disallowArithmeticOperators = (options.disallowArithmeticOperators) || false; + + /** + * Reports unsafe usage of optional chaining + * @param {ASTNode} node node to report + * @returns {void} + */ + function reportUnsafeUsage(node) { + context.report({ + messageId: "unsafeOptionalChain", + node + }); + } + + /** + * Reports unsafe arithmetic operation on optional chaining + * @param {ASTNode} node node to report + * @returns {void} + */ + function reportUnsafeArithmetic(node) { + context.report({ + messageId: "unsafeArithmetic", + node + }); + } + + /** + * Checks and reports if a node can short-circuit with `undefined` by optional chaining. + * @param {ASTNode} [node] node to check + * @param {Function} reportFunc report function + * @returns {void} + */ + function checkUndefinedShortCircuit(node, reportFunc) { + if (!node) { + return; + } + switch (node.type) { + case "LogicalExpression": + if (node.operator === "||" || node.operator === "??") { + checkUndefinedShortCircuit(node.right, reportFunc); + } else if (node.operator === "&&") { + checkUndefinedShortCircuit(node.left, reportFunc); + checkUndefinedShortCircuit(node.right, reportFunc); + } + break; + case "SequenceExpression": + checkUndefinedShortCircuit( + node.expressions[node.expressions.length - 1], + reportFunc + ); + break; + case "ConditionalExpression": + checkUndefinedShortCircuit(node.consequent, reportFunc); + checkUndefinedShortCircuit(node.alternate, reportFunc); + break; + case "AwaitExpression": + checkUndefinedShortCircuit(node.argument, reportFunc); + break; + case "ChainExpression": + reportFunc(node); + break; + default: + break; + } + } + + /** + * Checks unsafe usage of optional chaining + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkUnsafeUsage(node) { + checkUndefinedShortCircuit(node, reportUnsafeUsage); + } + + /** + * Checks unsafe arithmetic operations on optional chaining + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkUnsafeArithmetic(node) { + checkUndefinedShortCircuit(node, reportUnsafeArithmetic); + } + + return { + "AssignmentExpression, AssignmentPattern"(node) { + if (isDestructuringPattern(node.left)) { + checkUnsafeUsage(node.right); + } + }, + "ClassDeclaration, ClassExpression"(node) { + checkUnsafeUsage(node.superClass); + }, + CallExpression(node) { + if (!node.optional) { + checkUnsafeUsage(node.callee); + } + }, + NewExpression(node) { + checkUnsafeUsage(node.callee); + }, + VariableDeclarator(node) { + if (isDestructuringPattern(node.id)) { + checkUnsafeUsage(node.init); + } + }, + MemberExpression(node) { + if (!node.optional) { + checkUnsafeUsage(node.object); + } + }, + TaggedTemplateExpression(node) { + checkUnsafeUsage(node.tag); + }, + ForOfStatement(node) { + checkUnsafeUsage(node.right); + }, + SpreadElement(node) { + if (node.parent && node.parent.type !== "ObjectExpression") { + checkUnsafeUsage(node.argument); + } + }, + BinaryExpression(node) { + if (UNSAFE_RELATIONAL_OPERATORS.has(node.operator)) { + checkUnsafeUsage(node.right); + } + if ( + disallowArithmeticOperators && + UNSAFE_ARITHMETIC_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.right); + checkUnsafeArithmetic(node.left); + } + }, + WithStatement(node) { + checkUnsafeUsage(node.object); + }, + UnaryExpression(node) { + if ( + disallowArithmeticOperators && + UNSAFE_ARITHMETIC_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.argument); + } + }, + AssignmentExpression(node) { + if ( + disallowArithmeticOperators && + UNSAFE_ASSIGNMENT_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.right); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unused-expressions.js b/node_modules/eslint/lib/rules/no-unused-expressions.js new file mode 100644 index 0000000..46bb7ba --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-expressions.js @@ -0,0 +1,186 @@ +/** + * @fileoverview Flag expressions in statement position that do not side effect + * @author Michael Ficarra + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Returns `true`. + * @returns {boolean} `true`. + */ +function alwaysTrue() { + return true; +} + +/** + * Returns `false`. + * @returns {boolean} `false`. + */ +function alwaysFalse() { + return false; +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unused expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unused-expressions" + }, + + schema: [ + { + type: "object", + properties: { + allowShortCircuit: { + type: "boolean", + default: false + }, + allowTernary: { + type: "boolean", + default: false + }, + allowTaggedTemplates: { + type: "boolean", + default: false + }, + enforceForJSX: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + unusedExpression: "Expected an assignment or function call and instead saw an expression." + } + }, + + create(context) { + const config = context.options[0] || {}, + allowShortCircuit = config.allowShortCircuit || false, + allowTernary = config.allowTernary || false, + allowTaggedTemplates = config.allowTaggedTemplates || false, + enforceForJSX = config.enforceForJSX || false; + + /** + * Has AST suggesting a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return node.type === "ExpressionStatement" && + node.expression.type === "Literal" && typeof node.expression.value === "string"; + } + + /** + * Gets the leading sequence of members in a list that pass the predicate. + * @param {Function} predicate ([a] -> Boolean) the function used to make the determination + * @param {a[]} list the input list + * @returns {a[]} the leading sequence of members in the given list that pass the given predicate + */ + function takeWhile(predicate, list) { + for (let i = 0; i < list.length; ++i) { + if (!predicate(list[i])) { + return list.slice(0, i); + } + } + return list.slice(); + } + + /** + * Gets leading directives nodes in a Node body. + * @param {ASTNode} node a Program or BlockStatement node + * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body + */ + function directives(node) { + return takeWhile(looksLikeDirective, node.body); + } + + /** + * Detect if a Node is a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node is considered a directive in its current position + */ + function isDirective(node) { + + /** + * https://tc39.es/ecma262/#directive-prologue + * + * Only `FunctionBody`, `ScriptBody` and `ModuleBody` can have directive prologue. + * Class static blocks do not have directive prologue. + */ + return astUtils.isTopLevelExpressionStatement(node) && directives(node.parent).includes(node); + } + + /** + * The member functions return `true` if the type has no side-effects. + * Unknown nodes are handled as `false`, then this rule ignores those. + */ + const Checker = Object.assign(Object.create(null), { + isDisallowed(node) { + return (Checker[node.type] || alwaysFalse)(node); + }, + + ArrayExpression: alwaysTrue, + ArrowFunctionExpression: alwaysTrue, + BinaryExpression: alwaysTrue, + ChainExpression(node) { + return Checker.isDisallowed(node.expression); + }, + ClassExpression: alwaysTrue, + ConditionalExpression(node) { + if (allowTernary) { + return Checker.isDisallowed(node.consequent) || Checker.isDisallowed(node.alternate); + } + return true; + }, + FunctionExpression: alwaysTrue, + Identifier: alwaysTrue, + JSXElement() { + return enforceForJSX; + }, + JSXFragment() { + return enforceForJSX; + }, + Literal: alwaysTrue, + LogicalExpression(node) { + if (allowShortCircuit) { + return Checker.isDisallowed(node.right); + } + return true; + }, + MemberExpression: alwaysTrue, + MetaProperty: alwaysTrue, + ObjectExpression: alwaysTrue, + SequenceExpression: alwaysTrue, + TaggedTemplateExpression() { + return !allowTaggedTemplates; + }, + TemplateLiteral: alwaysTrue, + ThisExpression: alwaysTrue, + UnaryExpression(node) { + return node.operator !== "void" && node.operator !== "delete"; + } + }); + + return { + ExpressionStatement(node) { + if (Checker.isDisallowed(node.expression) && !isDirective(node)) { + context.report({ node, messageId: "unusedExpression" }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unused-labels.js b/node_modules/eslint/lib/rules/no-unused-labels.js new file mode 100644 index 0000000..be06b32 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-labels.js @@ -0,0 +1,143 @@ +/** + * @fileoverview Rule to disallow unused labels. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unused labels", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unused-labels" + }, + + schema: [], + + fixable: "code", + + messages: { + unused: "'{{name}}:' is defined but never used." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Adds a scope info to the stack. + * @param {ASTNode} node A node to add. This is a LabeledStatement. + * @returns {void} + */ + function enterLabeledScope(node) { + scopeInfo = { + label: node.label.name, + used: false, + upper: scopeInfo + }; + } + + /** + * Checks if a `LabeledStatement` node is fixable. + * For a node to be fixable, there must be no comments between the label and the body. + * Furthermore, is must be possible to remove the label without turning the body statement into a + * directive after other fixes are applied. + * @param {ASTNode} node The node to evaluate. + * @returns {boolean} Whether or not the node is fixable. + */ + function isFixable(node) { + + /* + * Only perform a fix if there are no comments between the label and the body. This will be the case + * when there is exactly one token/comment (the ":") between the label and the body. + */ + if (sourceCode.getTokenAfter(node.label, { includeComments: true }) !== + sourceCode.getTokenBefore(node.body, { includeComments: true })) { + return false; + } + + // Looking for the node's deepest ancestor which is not a `LabeledStatement`. + let ancestor = node.parent; + + while (ancestor.type === "LabeledStatement") { + ancestor = ancestor.parent; + } + + if (ancestor.type === "Program" || + (ancestor.type === "BlockStatement" && astUtils.isFunction(ancestor.parent))) { + const { body } = node; + + if (body.type === "ExpressionStatement" && + ((body.expression.type === "Literal" && typeof body.expression.value === "string") || + astUtils.isStaticTemplateLiteral(body.expression))) { + return false; // potential directive + } + } + return true; + } + + /** + * Removes the top of the stack. + * At the same time, this reports the label if it's never used. + * @param {ASTNode} node A node to report. This is a LabeledStatement. + * @returns {void} + */ + function exitLabeledScope(node) { + if (!scopeInfo.used) { + context.report({ + node: node.label, + messageId: "unused", + data: node.label, + fix: isFixable(node) ? fixer => fixer.removeRange([node.range[0], node.body.range[0]]) : null + }); + } + + scopeInfo = scopeInfo.upper; + } + + /** + * Marks the label of a given node as used. + * @param {ASTNode} node A node to mark. This is a BreakStatement or + * ContinueStatement. + * @returns {void} + */ + function markAsUsed(node) { + if (!node.label) { + return; + } + + const label = node.label.name; + let info = scopeInfo; + + while (info) { + if (info.label === label) { + info.used = true; + break; + } + info = info.upper; + } + } + + return { + LabeledStatement: enterLabeledScope, + "LabeledStatement:exit": exitLabeledScope, + BreakStatement: markAsUsed, + ContinueStatement: markAsUsed + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unused-private-class-members.js b/node_modules/eslint/lib/rules/no-unused-private-class-members.js new file mode 100644 index 0000000..037be7d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-private-class-members.js @@ -0,0 +1,195 @@ +/** + * @fileoverview Rule to flag declared but unused private class members + * @author Tim van der Lippe + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unused private class members", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unused-private-class-members" + }, + + schema: [], + + messages: { + unusedPrivateClassMember: "'{{classMemberName}}' is defined but never used." + } + }, + + create(context) { + const trackedClasses = []; + + /** + * Check whether the current node is in a write only assignment. + * @param {ASTNode} privateIdentifierNode Node referring to a private identifier + * @returns {boolean} Whether the node is in a write only assignment + * @private + */ + function isWriteOnlyAssignment(privateIdentifierNode) { + const parentStatement = privateIdentifierNode.parent.parent; + const isAssignmentExpression = parentStatement.type === "AssignmentExpression"; + + if (!isAssignmentExpression && + parentStatement.type !== "ForInStatement" && + parentStatement.type !== "ForOfStatement" && + parentStatement.type !== "AssignmentPattern") { + return false; + } + + // It is a write-only usage, since we still allow usages on the right for reads + if (parentStatement.left !== privateIdentifierNode.parent) { + return false; + } + + // For any other operator (such as '+=') we still consider it a read operation + if (isAssignmentExpression && parentStatement.operator !== "=") { + + /* + * However, if the read operation is "discarded" in an empty statement, then + * we consider it write only. + */ + return parentStatement.parent.type === "ExpressionStatement"; + } + + return true; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + // Collect all declared members up front and assume they are all unused + ClassBody(classBodyNode) { + const privateMembers = new Map(); + + trackedClasses.unshift(privateMembers); + for (const bodyMember of classBodyNode.body) { + if (bodyMember.type === "PropertyDefinition" || bodyMember.type === "MethodDefinition") { + if (bodyMember.key.type === "PrivateIdentifier") { + privateMembers.set(bodyMember.key.name, { + declaredNode: bodyMember, + isAccessor: bodyMember.type === "MethodDefinition" && + (bodyMember.kind === "set" || bodyMember.kind === "get") + }); + } + } + } + }, + + /* + * Process all usages of the private identifier and remove a member from + * `declaredAndUnusedPrivateMembers` if we deem it used. + */ + PrivateIdentifier(privateIdentifierNode) { + const classBody = trackedClasses.find(classProperties => classProperties.has(privateIdentifierNode.name)); + + // Can't happen, as it is a parser to have a missing class body, but let's code defensively here. + if (!classBody) { + return; + } + + // In case any other usage was already detected, we can short circuit the logic here. + const memberDefinition = classBody.get(privateIdentifierNode.name); + + if (memberDefinition.isUsed) { + return; + } + + // The definition of the class member itself + if (privateIdentifierNode.parent.type === "PropertyDefinition" || + privateIdentifierNode.parent.type === "MethodDefinition") { + return; + } + + /* + * Any usage of an accessor is considered a read, as the getter/setter can have + * side-effects in its definition. + */ + if (memberDefinition.isAccessor) { + memberDefinition.isUsed = true; + return; + } + + // Any assignments to this member, except for assignments that also read + if (isWriteOnlyAssignment(privateIdentifierNode)) { + return; + } + + const wrappingExpressionType = privateIdentifierNode.parent.parent.type; + const parentOfWrappingExpressionType = privateIdentifierNode.parent.parent.parent.type; + + // A statement which only increments (`this.#x++;`) + if (wrappingExpressionType === "UpdateExpression" && + parentOfWrappingExpressionType === "ExpressionStatement") { + return; + } + + /* + * ({ x: this.#usedInDestructuring } = bar); + * + * But should treat the following as a read: + * ({ [this.#x]: a } = foo); + */ + if (wrappingExpressionType === "Property" && + parentOfWrappingExpressionType === "ObjectPattern" && + privateIdentifierNode.parent.parent.value === privateIdentifierNode.parent) { + return; + } + + // [...this.#unusedInRestPattern] = bar; + if (wrappingExpressionType === "RestElement") { + return; + } + + // [this.#unusedInAssignmentPattern] = bar; + if (wrappingExpressionType === "ArrayPattern") { + return; + } + + /* + * We can't delete the memberDefinition, as we need to keep track of which member we are marking as used. + * In the case of nested classes, we only mark the first member we encounter as used. If you were to delete + * the member, then any subsequent usage could incorrectly mark the member of an encapsulating parent class + * as used, which is incorrect. + */ + memberDefinition.isUsed = true; + }, + + /* + * Post-process the class members and report any remaining members. + * Since private members can only be accessed in the current class context, + * we can safely assume that all usages are within the current class body. + */ + "ClassBody:exit"() { + const unusedPrivateMembers = trackedClasses.shift(); + + for (const [classMemberName, { declaredNode, isUsed }] of unusedPrivateMembers.entries()) { + if (isUsed) { + continue; + } + context.report({ + node: declaredNode, + loc: declaredNode.key.loc, + messageId: "unusedPrivateClassMember", + data: { + classMemberName: `#${classMemberName}` + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-unused-vars.js b/node_modules/eslint/lib/rules/no-unused-vars.js new file mode 100644 index 0000000..f29e678 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-vars.js @@ -0,0 +1,718 @@ +/** + * @fileoverview Rule to flag declared but unused variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * Bag of data used for formatting the `unusedVar` lint message. + * @typedef {Object} UnusedVarMessageData + * @property {string} varName The name of the unused var. + * @property {'defined'|'assigned a value'} action Description of the vars state. + * @property {string} additional Any additional info to be appended at the end. + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unused variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unused-vars" + }, + + schema: [ + { + oneOf: [ + { + enum: ["all", "local"] + }, + { + type: "object", + properties: { + vars: { + enum: ["all", "local"] + }, + varsIgnorePattern: { + type: "string" + }, + args: { + enum: ["all", "after-used", "none"] + }, + ignoreRestSiblings: { + type: "boolean" + }, + argsIgnorePattern: { + type: "string" + }, + caughtErrors: { + enum: ["all", "none"] + }, + caughtErrorsIgnorePattern: { + type: "string" + }, + destructuredArrayIgnorePattern: { + type: "string" + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + unusedVar: "'{{varName}}' is {{action}} but never used{{additional}}." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/u; + + const config = { + vars: "all", + args: "after-used", + ignoreRestSiblings: false, + caughtErrors: "none" + }; + + const firstOption = context.options[0]; + + if (firstOption) { + if (typeof firstOption === "string") { + config.vars = firstOption; + } else { + config.vars = firstOption.vars || config.vars; + config.args = firstOption.args || config.args; + config.ignoreRestSiblings = firstOption.ignoreRestSiblings || config.ignoreRestSiblings; + config.caughtErrors = firstOption.caughtErrors || config.caughtErrors; + + if (firstOption.varsIgnorePattern) { + config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern, "u"); + } + + if (firstOption.argsIgnorePattern) { + config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern, "u"); + } + + if (firstOption.caughtErrorsIgnorePattern) { + config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern, "u"); + } + + if (firstOption.destructuredArrayIgnorePattern) { + config.destructuredArrayIgnorePattern = new RegExp(firstOption.destructuredArrayIgnorePattern, "u"); + } + } + } + + /** + * Generates the message data about the variable being defined and unused, + * including the ignore pattern if configured. + * @param {Variable} unusedVar eslint-scope variable object. + * @returns {UnusedVarMessageData} The message data to be used with this unused variable. + */ + function getDefinedMessageData(unusedVar) { + const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type; + let type; + let pattern; + + if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) { + type = "args"; + pattern = config.caughtErrorsIgnorePattern.toString(); + } else if (defType === "Parameter" && config.argsIgnorePattern) { + type = "args"; + pattern = config.argsIgnorePattern.toString(); + } else if (defType !== "Parameter" && config.varsIgnorePattern) { + type = "vars"; + pattern = config.varsIgnorePattern.toString(); + } + + const additional = type ? `. Allowed unused ${type} must match ${pattern}` : ""; + + return { + varName: unusedVar.name, + action: "defined", + additional + }; + } + + /** + * Generate the warning message about the variable being + * assigned and unused, including the ignore pattern if configured. + * @param {Variable} unusedVar eslint-scope variable object. + * @returns {UnusedVarMessageData} The message data to be used with this unused variable. + */ + function getAssignedMessageData(unusedVar) { + const def = unusedVar.defs[0]; + let additional = ""; + + if (config.destructuredArrayIgnorePattern && def && def.name.parent.type === "ArrayPattern") { + additional = `. Allowed unused elements of array destructuring patterns must match ${config.destructuredArrayIgnorePattern.toString()}`; + } else if (config.varsIgnorePattern) { + additional = `. Allowed unused vars must match ${config.varsIgnorePattern.toString()}`; + } + + return { + varName: unusedVar.name, + action: "assigned a value", + additional + }; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const STATEMENT_TYPE = /(?:Statement|Declaration)$/u; + + /** + * Determines if a given variable is being exported from a module. + * @param {Variable} variable eslint-scope variable object. + * @returns {boolean} True if the variable is exported, false if not. + * @private + */ + function isExported(variable) { + + const definition = variable.defs[0]; + + if (definition) { + + let node = definition.node; + + if (node.type === "VariableDeclarator") { + node = node.parent; + } else if (definition.type === "Parameter") { + return false; + } + + return node.parent.type.indexOf("Export") === 0; + } + return false; + + } + + /** + * Checks whether a node is a sibling of the rest property or not. + * @param {ASTNode} node a node to check + * @returns {boolean} True if the node is a sibling of the rest property, otherwise false. + */ + function hasRestSibling(node) { + return node.type === "Property" && + node.parent.type === "ObjectPattern" && + REST_PROPERTY_TYPE.test(node.parent.properties[node.parent.properties.length - 1].type); + } + + /** + * Determines if a variable has a sibling rest property + * @param {Variable} variable eslint-scope variable object. + * @returns {boolean} True if the variable is exported, false if not. + * @private + */ + function hasRestSpreadSibling(variable) { + if (config.ignoreRestSiblings) { + const hasRestSiblingDefinition = variable.defs.some(def => hasRestSibling(def.name.parent)); + const hasRestSiblingReference = variable.references.some(ref => hasRestSibling(ref.identifier.parent)); + + return hasRestSiblingDefinition || hasRestSiblingReference; + } + + return false; + } + + /** + * Determines if a reference is a read operation. + * @param {Reference} ref An eslint-scope Reference + * @returns {boolean} whether the given reference represents a read operation + * @private + */ + function isReadRef(ref) { + return ref.isRead(); + } + + /** + * Determine if an identifier is referencing an enclosing function name. + * @param {Reference} ref The reference to check. + * @param {ASTNode[]} nodes The candidate function nodes. + * @returns {boolean} True if it's a self-reference, false if not. + * @private + */ + function isSelfReference(ref, nodes) { + let scope = ref.from; + + while (scope) { + if (nodes.includes(scope.block)) { + return true; + } + + scope = scope.upper; + } + + return false; + } + + /** + * Gets a list of function definitions for a specified variable. + * @param {Variable} variable eslint-scope variable object. + * @returns {ASTNode[]} Function nodes. + * @private + */ + function getFunctionDefinitions(variable) { + const functionDefinitions = []; + + variable.defs.forEach(def => { + const { type, node } = def; + + // FunctionDeclarations + if (type === "FunctionName") { + functionDefinitions.push(node); + } + + // FunctionExpressions + if (type === "Variable" && node.init && + (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) { + functionDefinitions.push(node.init); + } + }); + return functionDefinitions; + } + + /** + * Checks the position of given nodes. + * @param {ASTNode} inner A node which is expected as inside. + * @param {ASTNode} outer A node which is expected as outside. + * @returns {boolean} `true` if the `inner` node exists in the `outer` node. + * @private + */ + function isInside(inner, outer) { + return ( + inner.range[0] >= outer.range[0] && + inner.range[1] <= outer.range[1] + ); + } + + /** + * Checks whether a given node is unused expression or not. + * @param {ASTNode} node The node itself + * @returns {boolean} The node is an unused expression. + * @private + */ + function isUnusedExpression(node) { + const parent = node.parent; + + if (parent.type === "ExpressionStatement") { + return true; + } + + if (parent.type === "SequenceExpression") { + const isLastExpression = parent.expressions[parent.expressions.length - 1] === node; + + if (!isLastExpression) { + return true; + } + return isUnusedExpression(parent); + } + + return false; + } + + /** + * If a given reference is left-hand side of an assignment, this gets + * the right-hand side node of the assignment. + * + * In the following cases, this returns null. + * + * - The reference is not the LHS of an assignment expression. + * - The reference is inside of a loop. + * - The reference is inside of a function scope which is different from + * the declaration. + * @param {eslint-scope.Reference} ref A reference to check. + * @param {ASTNode} prevRhsNode The previous RHS node. + * @returns {ASTNode|null} The RHS node or null. + * @private + */ + function getRhsNode(ref, prevRhsNode) { + const id = ref.identifier; + const parent = id.parent; + const refScope = ref.from.variableScope; + const varScope = ref.resolved.scope.variableScope; + const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id); + + /* + * Inherits the previous node if this reference is in the node. + * This is for `a = a + a`-like code. + */ + if (prevRhsNode && isInside(id, prevRhsNode)) { + return prevRhsNode; + } + + if (parent.type === "AssignmentExpression" && + isUnusedExpression(parent) && + id === parent.left && + !canBeUsedLater + ) { + return parent.right; + } + return null; + } + + /** + * Checks whether a given function node is stored to somewhere or not. + * If the function node is stored, the function can be used later. + * @param {ASTNode} funcNode A function node to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} `true` if under the following conditions: + * - the funcNode is assigned to a variable. + * - the funcNode is bound as an argument of a function call. + * - the function is bound to a property and the object satisfies above conditions. + * @private + */ + function isStorableFunction(funcNode, rhsNode) { + let node = funcNode; + let parent = funcNode.parent; + + while (parent && isInside(parent, rhsNode)) { + switch (parent.type) { + case "SequenceExpression": + if (parent.expressions[parent.expressions.length - 1] !== node) { + return false; + } + break; + + case "CallExpression": + case "NewExpression": + return parent.callee !== node; + + case "AssignmentExpression": + case "TaggedTemplateExpression": + case "YieldExpression": + return true; + + default: + if (STATEMENT_TYPE.test(parent.type)) { + + /* + * If it encountered statements, this is a complex pattern. + * Since analyzing complex patterns is hard, this returns `true` to avoid false positive. + */ + return true; + } + } + + node = parent; + parent = parent.parent; + } + + return false; + } + + /** + * Checks whether a given Identifier node exists inside of a function node which can be used later. + * + * "can be used later" means: + * - the function is assigned to a variable. + * - the function is bound to a property and the object can be used later. + * - the function is bound as an argument of a function call. + * + * If a reference exists in a function which can be used later, the reference is read when the function is called. + * @param {ASTNode} id An Identifier node to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later. + * @private + */ + function isInsideOfStorableFunction(id, rhsNode) { + const funcNode = astUtils.getUpperFunction(id); + + return ( + funcNode && + isInside(funcNode, rhsNode) && + isStorableFunction(funcNode, rhsNode) + ); + } + + /** + * Checks whether a given reference is a read to update itself or not. + * @param {eslint-scope.Reference} ref A reference to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} The reference is a read to update itself. + * @private + */ + function isReadForItself(ref, rhsNode) { + const id = ref.identifier; + const parent = id.parent; + + return ref.isRead() && ( + + // self update. e.g. `a += 1`, `a++` + ( + ( + parent.type === "AssignmentExpression" && + parent.left === id && + isUnusedExpression(parent) && + !astUtils.isLogicalAssignmentOperator(parent.operator) + ) || + ( + parent.type === "UpdateExpression" && + isUnusedExpression(parent) + ) + ) || + + // in RHS of an assignment for itself. e.g. `a = a + 1` + ( + rhsNode && + isInside(id, rhsNode) && + !isInsideOfStorableFunction(id, rhsNode) + ) + ); + } + + /** + * Determine if an identifier is used either in for-in or for-of loops. + * @param {Reference} ref The reference to check. + * @returns {boolean} whether reference is used in the for-in loops + * @private + */ + function isForInOfRef(ref) { + let target = ref.identifier.parent; + + + // "for (var ...) { return; }" + if (target.type === "VariableDeclarator") { + target = target.parent.parent; + } + + if (target.type !== "ForInStatement" && target.type !== "ForOfStatement") { + return false; + } + + // "for (...) { return; }" + if (target.body.type === "BlockStatement") { + target = target.body.body[0]; + + // "for (...) return;" + } else { + target = target.body; + } + + // For empty loop body + if (!target) { + return false; + } + + return target.type === "ReturnStatement"; + } + + /** + * Determines if the variable is used. + * @param {Variable} variable The variable to check. + * @returns {boolean} True if the variable is used + * @private + */ + function isUsedVariable(variable) { + const functionNodes = getFunctionDefinitions(variable), + isFunctionDefinition = functionNodes.length > 0; + let rhsNode = null; + + return variable.references.some(ref => { + if (isForInOfRef(ref)) { + return true; + } + + const forItself = isReadForItself(ref, rhsNode); + + rhsNode = getRhsNode(ref, rhsNode); + + return ( + isReadRef(ref) && + !forItself && + !(isFunctionDefinition && isSelfReference(ref, functionNodes)) + ); + }); + } + + /** + * Checks whether the given variable is after the last used parameter. + * @param {eslint-scope.Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is defined after the last + * used parameter. + */ + function isAfterLastUsedArg(variable) { + const def = variable.defs[0]; + const params = sourceCode.getDeclaredVariables(def.node); + const posteriorParams = params.slice(params.indexOf(variable) + 1); + + // If any used parameters occur after this parameter, do not report. + return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed); + } + + /** + * Gets an array of variables without read references. + * @param {Scope} scope an eslint-scope Scope object. + * @param {Variable[]} unusedVars an array that saving result. + * @returns {Variable[]} unused variables of the scope and descendant scopes. + * @private + */ + function collectUnusedVariables(scope, unusedVars) { + const variables = scope.variables; + const childScopes = scope.childScopes; + let i, l; + + if (scope.type !== "global" || config.vars === "all") { + for (i = 0, l = variables.length; i < l; ++i) { + const variable = variables[i]; + + // skip a variable of class itself name in the class scope + if (scope.type === "class" && scope.block.id === variable.identifiers[0]) { + continue; + } + + // skip function expression names and variables marked with markVariableAsUsed() + if (scope.functionExpressionScope || variable.eslintUsed) { + continue; + } + + // skip implicit "arguments" variable + if (scope.type === "function" && variable.name === "arguments" && variable.identifiers.length === 0) { + continue; + } + + // explicit global variables don't have definitions. + const def = variable.defs[0]; + + if (def) { + const type = def.type; + const refUsedInArrayPatterns = variable.references.some(ref => ref.identifier.parent.type === "ArrayPattern"); + + // skip elements of array destructuring patterns + if ( + ( + def.name.parent.type === "ArrayPattern" || + refUsedInArrayPatterns + ) && + config.destructuredArrayIgnorePattern && + config.destructuredArrayIgnorePattern.test(def.name.name) + ) { + continue; + } + + // skip catch variables + if (type === "CatchClause") { + if (config.caughtErrors === "none") { + continue; + } + + // skip ignored parameters + if (config.caughtErrorsIgnorePattern && config.caughtErrorsIgnorePattern.test(def.name.name)) { + continue; + } + } + + if (type === "Parameter") { + + // skip any setter argument + if ((def.node.parent.type === "Property" || def.node.parent.type === "MethodDefinition") && def.node.parent.kind === "set") { + continue; + } + + // if "args" option is "none", skip any parameter + if (config.args === "none") { + continue; + } + + // skip ignored parameters + if (config.argsIgnorePattern && config.argsIgnorePattern.test(def.name.name)) { + continue; + } + + // if "args" option is "after-used", skip used variables + if (config.args === "after-used" && astUtils.isFunction(def.name.parent) && !isAfterLastUsedArg(variable)) { + continue; + } + } else { + + // skip ignored variables + if (config.varsIgnorePattern && config.varsIgnorePattern.test(def.name.name)) { + continue; + } + } + } + + if (!isUsedVariable(variable) && !isExported(variable) && !hasRestSpreadSibling(variable)) { + unusedVars.push(variable); + } + } + } + + for (i = 0, l = childScopes.length; i < l; ++i) { + collectUnusedVariables(childScopes[i], unusedVars); + } + + return unusedVars; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program:exit"(programNode) { + const unusedVars = collectUnusedVariables(sourceCode.getScope(programNode), []); + + for (let i = 0, l = unusedVars.length; i < l; ++i) { + const unusedVar = unusedVars[i]; + + // Report the first declaration. + if (unusedVar.defs.length > 0) { + + // report last write reference, https://github.com/eslint/eslint/issues/14324 + const writeReferences = unusedVar.references.filter(ref => ref.isWrite() && ref.from.variableScope === unusedVar.scope.variableScope); + + let referenceToReport; + + if (writeReferences.length > 0) { + referenceToReport = writeReferences[writeReferences.length - 1]; + } + + context.report({ + node: referenceToReport ? referenceToReport.identifier : unusedVar.identifiers[0], + messageId: "unusedVar", + data: unusedVar.references.some(ref => ref.isWrite()) + ? getAssignedMessageData(unusedVar) + : getDefinedMessageData(unusedVar) + }); + + // If there are no regular declaration, report the first `/*globals*/` comment directive. + } else if (unusedVar.eslintExplicitGlobalComments) { + const directiveComment = unusedVar.eslintExplicitGlobalComments[0]; + + context.report({ + node: programNode, + loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, directiveComment, unusedVar.name), + messageId: "unusedVar", + data: getDefinedMessageData(unusedVar) + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/no-use-before-define.js b/node_modules/eslint/lib/rules/no-use-before-define.js new file mode 100644 index 0000000..9d6b043 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-use-before-define.js @@ -0,0 +1,348 @@ +/** + * @fileoverview Rule to flag use of variables before they are defined + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u; +const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u; + +/** + * Parses a given value as options. + * @param {any} options A value to parse. + * @returns {Object} The parsed options. + */ +function parseOptions(options) { + let functions = true; + let classes = true; + let variables = true; + let allowNamedExports = false; + + if (typeof options === "string") { + functions = (options !== "nofunc"); + } else if (typeof options === "object" && options !== null) { + functions = options.functions !== false; + classes = options.classes !== false; + variables = options.variables !== false; + allowNamedExports = !!options.allowNamedExports; + } + + return { functions, classes, variables, allowNamedExports }; +} + +/** + * Checks whether or not a given location is inside of the range of a given node. + * @param {ASTNode} node An node to check. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of the range of the node. + */ +function isInRange(node, location) { + return node && node.range[0] <= location && location <= node.range[1]; +} + +/** + * Checks whether or not a given location is inside of the range of a class static initializer. + * Static initializers are static blocks and initializers of static fields. + * @param {ASTNode} node `ClassBody` node to check static initializers. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of a class static initializer. + */ +function isInClassStaticInitializerRange(node, location) { + return node.body.some(classMember => ( + ( + classMember.type === "StaticBlock" && + isInRange(classMember, location) + ) || + ( + classMember.type === "PropertyDefinition" && + classMember.static && + classMember.value && + isInRange(classMember.value, location) + ) + )); +} + +/** + * Checks whether a given scope is the scope of a class static initializer. + * Static initializers are static blocks and initializers of static fields. + * @param {eslint-scope.Scope} scope A scope to check. + * @returns {boolean} `true` if the scope is a class static initializer scope. + */ +function isClassStaticInitializerScope(scope) { + if (scope.type === "class-static-block") { + return true; + } + + if (scope.type === "class-field-initializer") { + + // `scope.block` is PropertyDefinition#value node + const propertyDefinition = scope.block.parent; + + return propertyDefinition.static; + } + + return false; +} + +/** + * Checks whether a given reference is evaluated in an execution context + * that isn't the one where the variable it refers to is defined. + * Execution contexts are: + * - top-level + * - functions + * - class field initializers (implicit functions) + * - class static blocks (implicit functions) + * Static class field initializers and class static blocks are automatically run during the class definition evaluation, + * and therefore we'll consider them as a part of the parent execution context. + * Example: + * + * const x = 1; + * + * x; // returns `false` + * () => x; // returns `true` + * + * class C { + * field = x; // returns `true` + * static field = x; // returns `false` + * + * method() { + * x; // returns `true` + * } + * + * static method() { + * x; // returns `true` + * } + * + * static { + * x; // returns `false` + * } + * } + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is from a separate execution context. + */ +function isFromSeparateExecutionContext(reference) { + const variable = reference.resolved; + let scope = reference.from; + + // Scope#variableScope represents execution context + while (variable.scope.variableScope !== scope.variableScope) { + if (isClassStaticInitializerScope(scope.variableScope)) { + scope = scope.variableScope.upper; + } else { + return true; + } + } + + return false; +} + +/** + * Checks whether or not a given reference is evaluated during the initialization of its variable. + * + * This returns `true` in the following cases: + * + * var a = a + * var [a = a] = list + * var {a = a} = obj + * for (var a in a) {} + * for (var a of a) {} + * var C = class { [C]; }; + * var C = class { static foo = C; }; + * var C = class { static { foo = C; } }; + * class C extends C {} + * class C extends (class { static foo = C; }) {} + * class C { [C]; } + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is evaluated during the initialization. + */ +function isEvaluatedDuringInitialization(reference) { + if (isFromSeparateExecutionContext(reference)) { + + /* + * Even if the reference appears in the initializer, it isn't evaluated during the initialization. + * For example, `const x = () => x;` is valid. + */ + return false; + } + + const location = reference.identifier.range[1]; + const definition = reference.resolved.defs[0]; + + if (definition.type === "ClassName") { + + // `ClassDeclaration` or `ClassExpression` + const classDefinition = definition.node; + + return ( + isInRange(classDefinition, location) && + + /* + * Class binding is initialized before running static initializers. + * For example, `class C { static foo = C; static { bar = C; } }` is valid. + */ + !isInClassStaticInitializerRange(classDefinition.body, location) + ); + } + + let node = definition.name.parent; + + while (node) { + if (node.type === "VariableDeclarator") { + if (isInRange(node.init, location)) { + return true; + } + if (FOR_IN_OF_TYPE.test(node.parent.parent.type) && + isInRange(node.parent.parent.right, location) + ) { + return true; + } + break; + } else if (node.type === "AssignmentPattern") { + if (isInRange(node.right, location)) { + return true; + } + } else if (SENTINEL_TYPE.test(node.type)) { + break; + } + + node = node.parent; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow the use of variables before they are defined", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-use-before-define" + }, + + schema: [ + { + oneOf: [ + { + enum: ["nofunc"] + }, + { + type: "object", + properties: { + functions: { type: "boolean" }, + classes: { type: "boolean" }, + variables: { type: "boolean" }, + allowNamedExports: { type: "boolean" } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + usedBeforeDefined: "'{{name}}' was used before it was defined." + } + }, + + create(context) { + const options = parseOptions(context.options[0]); + const sourceCode = context.sourceCode; + + /** + * Determines whether a given reference should be checked. + * + * Returns `false` if the reference is: + * - initialization's (e.g., `let a = 1`). + * - referring to an undefined variable (i.e., if it's an unresolved reference). + * - referring to a variable that is defined, but not in the given source code + * (e.g., global environment variable or `arguments` in functions). + * - allowed by options. + * @param {eslint-scope.Reference} reference The reference + * @returns {boolean} `true` if the reference should be checked + */ + function shouldCheck(reference) { + if (reference.init) { + return false; + } + + const { identifier } = reference; + + if ( + options.allowNamedExports && + identifier.parent.type === "ExportSpecifier" && + identifier.parent.local === identifier + ) { + return false; + } + + const variable = reference.resolved; + + if (!variable || variable.defs.length === 0) { + return false; + } + + const definitionType = variable.defs[0].type; + + if (!options.functions && definitionType === "FunctionName") { + return false; + } + + if ( + ( + !options.variables && definitionType === "Variable" || + !options.classes && definitionType === "ClassName" + ) && + + // don't skip checking the reference if it's in the same execution context, because of TDZ + isFromSeparateExecutionContext(reference) + ) { + return false; + } + + return true; + } + + /** + * Finds and validates all references in a given scope and its child scopes. + * @param {eslint-scope.Scope} scope The scope object. + * @returns {void} + */ + function checkReferencesInScope(scope) { + scope.references.filter(shouldCheck).forEach(reference => { + const variable = reference.resolved; + const definitionIdentifier = variable.defs[0].name; + + if ( + reference.identifier.range[1] < definitionIdentifier.range[1] || + isEvaluatedDuringInitialization(reference) + ) { + context.report({ + node: reference.identifier, + messageId: "usedBeforeDefined", + data: reference.identifier + }); + } + }); + + scope.childScopes.forEach(checkReferencesInScope); + } + + return { + Program(node) { + checkReferencesInScope(sourceCode.getScope(node)); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-backreference.js b/node_modules/eslint/lib/rules/no-useless-backreference.js new file mode 100644 index 0000000..7ca43c8 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-backreference.js @@ -0,0 +1,194 @@ +/** + * @fileoverview Rule to disallow useless backreferences in regular expressions + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { CALL, CONSTRUCT, ReferenceTracker, getStringIfConstant } = require("@eslint-community/eslint-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new RegExpParser(); + +/** + * Finds the path from the given `regexpp` AST node to the root node. + * @param {regexpp.Node} node Node. + * @returns {regexpp.Node[]} Array that starts with the given node and ends with the root node. + */ +function getPathToRoot(node) { + const path = []; + let current = node; + + do { + path.push(current); + current = current.parent; + } while (current); + + return path; +} + +/** + * Determines whether the given `regexpp` AST node is a lookaround node. + * @param {regexpp.Node} node Node. + * @returns {boolean} `true` if it is a lookaround node. + */ +function isLookaround(node) { + return node.type === "Assertion" && + (node.kind === "lookahead" || node.kind === "lookbehind"); +} + +/** + * Determines whether the given `regexpp` AST node is a negative lookaround node. + * @param {regexpp.Node} node Node. + * @returns {boolean} `true` if it is a negative lookaround node. + */ +function isNegativeLookaround(node) { + return isLookaround(node) && node.negate; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow useless backreferences in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-backreference" + }, + + schema: [], + + messages: { + nested: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' from within that group.", + forward: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which appears later in the pattern.", + backward: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which appears before in the same lookbehind.", + disjunctive: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which is in another alternative.", + intoNegativeLookaround: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which is in a negative lookaround." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Checks and reports useless backreferences in the given regular expression. + * @param {ASTNode} node Node that represents regular expression. A regex literal or RegExp constructor call. + * @param {string} pattern Regular expression pattern. + * @param {string} flags Regular expression flags. + * @returns {void} + */ + function checkRegex(node, pattern, flags) { + let regExpAST; + + try { + regExpAST = parser.parsePattern(pattern, 0, pattern.length, { unicode: flags.includes("u"), unicodeSets: flags.includes("v") }); + } catch { + + // Ignore regular expressions with syntax errors + return; + } + + visitRegExpAST(regExpAST, { + onBackreferenceEnter(bref) { + const group = bref.resolved, + brefPath = getPathToRoot(bref), + groupPath = getPathToRoot(group); + let messageId = null; + + if (brefPath.includes(group)) { + + // group is bref's ancestor => bref is nested ('nested reference') => group hasn't matched yet when bref starts to match. + messageId = "nested"; + } else { + + // Start from the root to find the lowest common ancestor. + let i = brefPath.length - 1, + j = groupPath.length - 1; + + do { + i--; + j--; + } while (brefPath[i] === groupPath[j]); + + const indexOfLowestCommonAncestor = j + 1, + groupCut = groupPath.slice(0, indexOfLowestCommonAncestor), + commonPath = groupPath.slice(indexOfLowestCommonAncestor), + lowestCommonLookaround = commonPath.find(isLookaround), + isMatchingBackward = lowestCommonLookaround && lowestCommonLookaround.kind === "lookbehind"; + + if (!isMatchingBackward && bref.end <= group.start) { + + // bref is left, group is right ('forward reference') => group hasn't matched yet when bref starts to match. + messageId = "forward"; + } else if (isMatchingBackward && group.end <= bref.start) { + + // the opposite of the previous when the regex is matching backward in a lookbehind context. + messageId = "backward"; + } else if (groupCut[groupCut.length - 1].type === "Alternative") { + + // group's and bref's ancestor nodes below the lowest common ancestor are sibling alternatives => they're disjunctive. + messageId = "disjunctive"; + } else if (groupCut.some(isNegativeLookaround)) { + + // group is in a negative lookaround which isn't bref's ancestor => group has already failed when bref starts to match. + messageId = "intoNegativeLookaround"; + } + } + + if (messageId) { + context.report({ + node, + messageId, + data: { + bref: bref.raw, + group: group.raw + } + }); + } + } + }); + } + + return { + "Literal[regex]"(node) { + const { pattern, flags } = node.regex; + + checkRegex(node, pattern, flags); + }, + Program(node) { + const scope = sourceCode.getScope(node), + tracker = new ReferenceTracker(scope), + traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true + } + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences(traceMap)) { + const [patternNode, flagsNode] = refNode.arguments, + pattern = getStringIfConstant(patternNode, scope), + flags = getStringIfConstant(flagsNode, scope); + + if (typeof pattern === "string") { + checkRegex(refNode, pattern, flags || ""); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-call.js b/node_modules/eslint/lib/rules/no-useless-call.js new file mode 100644 index 0000000..dea2b47 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-call.js @@ -0,0 +1,90 @@ +/** + * @fileoverview A rule to disallow unnecessary `.call()` and `.apply()`. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is a `.call()`/`.apply()`. + * @param {ASTNode} node A CallExpression node to check. + * @returns {boolean} Whether or not the node is a `.call()`/`.apply()`. + */ +function isCallOrNonVariadicApply(node) { + const callee = astUtils.skipChainExpression(node.callee); + + return ( + callee.type === "MemberExpression" && + callee.property.type === "Identifier" && + callee.computed === false && + ( + (callee.property.name === "call" && node.arguments.length >= 1) || + (callee.property.name === "apply" && node.arguments.length === 2 && node.arguments[1].type === "ArrayExpression") + ) + ); +} + + +/** + * Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`. + * @param {ASTNode|null} expectedThis The node that is the owner of the applied function. + * @param {ASTNode} thisArg The node that is given to the first argument of the `.call()`/`.apply()`. + * @param {SourceCode} sourceCode The ESLint source code object. + * @returns {boolean} Whether or not `thisArg` is not changed by `.call()`/`.apply()`. + */ +function isValidThisArg(expectedThis, thisArg, sourceCode) { + if (!expectedThis) { + return astUtils.isNullOrUndefined(thisArg); + } + return astUtils.equalTokens(expectedThis, thisArg, sourceCode); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary calls to `.call()` and `.apply()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-call" + }, + + schema: [], + + messages: { + unnecessaryCall: "Unnecessary '.{{name}}()'." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + if (!isCallOrNonVariadicApply(node)) { + return; + } + + const callee = astUtils.skipChainExpression(node.callee); + const applied = astUtils.skipChainExpression(callee.object); + const expectedThis = (applied.type === "MemberExpression") ? applied.object : null; + const thisArg = node.arguments[0]; + + if (isValidThisArg(expectedThis, thisArg, sourceCode)) { + context.report({ node, messageId: "unnecessaryCall", data: { name: callee.property.name } }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-catch.js b/node_modules/eslint/lib/rules/no-useless-catch.js new file mode 100644 index 0000000..e02013d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-catch.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Reports useless `catch` clauses that just rethrow their error. + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary `catch` clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-catch" + }, + + schema: [], + + messages: { + unnecessaryCatchClause: "Unnecessary catch clause.", + unnecessaryCatch: "Unnecessary try/catch wrapper." + } + }, + + create(context) { + return { + CatchClause(node) { + if ( + node.param && + node.param.type === "Identifier" && + node.body.body.length && + node.body.body[0].type === "ThrowStatement" && + node.body.body[0].argument.type === "Identifier" && + node.body.body[0].argument.name === node.param.name + ) { + if (node.parent.finalizer) { + context.report({ + node, + messageId: "unnecessaryCatchClause" + }); + } else { + context.report({ + node: node.parent, + messageId: "unnecessaryCatch" + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-computed-key.js b/node_modules/eslint/lib/rules/no-useless-computed-key.js new file mode 100644 index 0000000..f2d9f33 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-computed-key.js @@ -0,0 +1,168 @@ +/** + * @fileoverview Rule to disallow unnecessary computed property keys in object literals + * @author Burak Yigit Kaya + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the computed key syntax is unnecessarily used for the given node. + * In particular, it determines whether removing the square brackets and using the content between them + * directly as the key (e.g. ['foo'] -> 'foo') would produce valid syntax and preserve the same behavior. + * Valid non-computed keys are only: identifiers, number literals and string literals. + * Only literals can preserve the same behavior, with a few exceptions for specific node types: + * Property + * - { ["__proto__"]: foo } defines a property named "__proto__" + * { "__proto__": foo } defines object's prototype + * PropertyDefinition + * - class C { ["constructor"]; } defines an instance field named "constructor" + * class C { "constructor"; } produces a parsing error + * - class C { static ["constructor"]; } defines a static field named "constructor" + * class C { static "constructor"; } produces a parsing error + * - class C { static ["prototype"]; } produces a runtime error (doesn't break the whole script) + * class C { static "prototype"; } produces a parsing error (breaks the whole script) + * MethodDefinition + * - class C { ["constructor"]() {} } defines a prototype method named "constructor" + * class C { "constructor"() {} } defines the constructor + * - class C { static ["prototype"]() {} } produces a runtime error (doesn't break the whole script) + * class C { static "prototype"() {} } produces a parsing error (breaks the whole script) + * @param {ASTNode} node The node to check. It can be `Property`, `PropertyDefinition` or `MethodDefinition`. + * @throws {Error} (Unreachable.) + * @returns {void} `true` if the node has useless computed key. + */ +function hasUselessComputedKey(node) { + if (!node.computed) { + return false; + } + + const { key } = node; + + if (key.type !== "Literal") { + return false; + } + + const { value } = key; + + if (typeof value !== "number" && typeof value !== "string") { + return false; + } + + switch (node.type) { + case "Property": + return value !== "__proto__"; + + case "PropertyDefinition": + if (node.static) { + return value !== "constructor" && value !== "prototype"; + } + + return value !== "constructor"; + + case "MethodDefinition": + if (node.static) { + return value !== "prototype"; + } + + return value !== "constructor"; + + /* c8 ignore next */ + default: + throw new Error(`Unexpected node type: ${node.type}`); + } + +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary computed property keys in objects and classes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-computed-key" + }, + + schema: [{ + type: "object", + properties: { + enforceForClassMembers: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + fixable: "code", + + messages: { + unnecessarilyComputedProperty: "Unnecessarily computed property [{{property}}] found." + } + }, + create(context) { + const sourceCode = context.sourceCode; + const enforceForClassMembers = context.options[0] && context.options[0].enforceForClassMembers; + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function check(node) { + if (hasUselessComputedKey(node)) { + const { key } = node; + + context.report({ + node, + messageId: "unnecessarilyComputedProperty", + data: { property: sourceCode.getText(key) }, + fix(fixer) { + const leftSquareBracket = sourceCode.getTokenBefore(key, astUtils.isOpeningBracketToken); + const rightSquareBracket = sourceCode.getTokenAfter(key, astUtils.isClosingBracketToken); + + // If there are comments between the brackets and the property name, don't do a fix. + if (sourceCode.commentsExistBetween(leftSquareBracket, rightSquareBracket)) { + return null; + } + + const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket); + + // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} }) + const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] && + !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key)); + + const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw; + + return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey); + } + }); + } + } + + /** + * A no-op function to act as placeholder for checking a node when the `enforceForClassMembers` option is `false`. + * @returns {void} + * @private + */ + function noop() {} + + return { + Property: check, + MethodDefinition: enforceForClassMembers ? check : noop, + PropertyDefinition: enforceForClassMembers ? check : noop + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-concat.js b/node_modules/eslint/lib/rules/no-useless-concat.js new file mode 100644 index 0000000..c566c62 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-concat.js @@ -0,0 +1,115 @@ +/** + * @fileoverview disallow unnecessary concatenation of template strings + * @author Henry Zhu + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a concatenation. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a concatenation. + */ +function isConcatenation(node) { + return node.type === "BinaryExpression" && node.operator === "+"; +} + +/** + * Checks if the given token is a `+` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `+` token. + */ +function isConcatOperatorToken(token) { + return token.value === "+" && token.type === "Punctuator"; +} + +/** + * Get's the right most node on the left side of a BinaryExpression with + operator. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {ASTNode} node + */ +function getLeft(node) { + let left = node.left; + + while (isConcatenation(left)) { + left = left.right; + } + return left; +} + +/** + * Get's the left most node on the right side of a BinaryExpression with + operator. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {ASTNode} node + */ +function getRight(node) { + let right = node.right; + + while (isConcatenation(right)) { + right = right.left; + } + return right; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary concatenation of literals or template literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-concat" + }, + + schema: [], + + messages: { + unexpectedConcat: "Unexpected string concatenation of literals." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + BinaryExpression(node) { + + // check if not concatenation + if (node.operator !== "+") { + return; + } + + // account for the `foo + "a" + "b"` case + const left = getLeft(node); + const right = getRight(node); + + if (astUtils.isStringLiteral(left) && + astUtils.isStringLiteral(right) && + astUtils.isTokenOnSameLine(left, right) + ) { + const operatorToken = sourceCode.getFirstTokenBetween(left, right, isConcatOperatorToken); + + context.report({ + node, + loc: operatorToken.loc, + messageId: "unexpectedConcat" + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-constructor.js b/node_modules/eslint/lib/rules/no-useless-constructor.js new file mode 100644 index 0000000..2b9c18e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-constructor.js @@ -0,0 +1,189 @@ +/** + * @fileoverview Rule to flag the use of redundant constructors in classes. + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether a given array of statements is a single call of `super`. + * @param {ASTNode[]} body An array of statements to check. + * @returns {boolean} `true` if the body is a single call of `super`. + */ +function isSingleSuperCall(body) { + return ( + body.length === 1 && + body[0].type === "ExpressionStatement" && + body[0].expression.type === "CallExpression" && + body[0].expression.callee.type === "Super" + ); +} + +/** + * Checks whether a given node is a pattern which doesn't have any side effects. + * Default parameters and Destructuring parameters can have side effects. + * @param {ASTNode} node A pattern node. + * @returns {boolean} `true` if the node doesn't have any side effects. + */ +function isSimple(node) { + return node.type === "Identifier" || node.type === "RestElement"; +} + +/** + * Checks whether a given array of expressions is `...arguments` or not. + * `super(...arguments)` passes all arguments through. + * @param {ASTNode[]} superArgs An array of expressions to check. + * @returns {boolean} `true` if the superArgs is `...arguments`. + */ +function isSpreadArguments(superArgs) { + return ( + superArgs.length === 1 && + superArgs[0].type === "SpreadElement" && + superArgs[0].argument.type === "Identifier" && + superArgs[0].argument.name === "arguments" + ); +} + +/** + * Checks whether given 2 nodes are identifiers which have the same name or not. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes are identifiers which have the same + * name. + */ +function isValidIdentifierPair(ctorParam, superArg) { + return ( + ctorParam.type === "Identifier" && + superArg.type === "Identifier" && + ctorParam.name === superArg.name + ); +} + +/** + * Checks whether given 2 nodes are a rest/spread pair which has the same values. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes are a rest/spread pair which has the + * same values. + */ +function isValidRestSpreadPair(ctorParam, superArg) { + return ( + ctorParam.type === "RestElement" && + superArg.type === "SpreadElement" && + isValidIdentifierPair(ctorParam.argument, superArg.argument) + ); +} + +/** + * Checks whether given 2 nodes have the same value or not. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes have the same value or not. + */ +function isValidPair(ctorParam, superArg) { + return ( + isValidIdentifierPair(ctorParam, superArg) || + isValidRestSpreadPair(ctorParam, superArg) + ); +} + +/** + * Checks whether the parameters of a constructor and the arguments of `super()` + * have the same values or not. + * @param {ASTNode} ctorParams The parameters of a constructor to check. + * @param {ASTNode} superArgs The arguments of `super()` to check. + * @returns {boolean} `true` if those have the same values. + */ +function isPassingThrough(ctorParams, superArgs) { + if (ctorParams.length !== superArgs.length) { + return false; + } + + for (let i = 0; i < ctorParams.length; ++i) { + if (!isValidPair(ctorParams[i], superArgs[i])) { + return false; + } + } + + return true; +} + +/** + * Checks whether the constructor body is a redundant super call. + * @param {Array} body constructor body content. + * @param {Array} ctorParams The params to check against super call. + * @returns {boolean} true if the constructor body is redundant + */ +function isRedundantSuperCall(body, ctorParams) { + return ( + isSingleSuperCall(body) && + ctorParams.every(isSimple) && + ( + isSpreadArguments(body[0].expression.arguments) || + isPassingThrough(ctorParams, body[0].expression.arguments) + ) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary constructors", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-constructor" + }, + + schema: [], + + messages: { + noUselessConstructor: "Useless constructor." + } + }, + + create(context) { + + /** + * Checks whether a node is a redundant constructor + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkForConstructor(node) { + if (node.kind !== "constructor") { + return; + } + + /* + * Prevent crashing on parsers which do not require class constructor + * to have a body, e.g. typescript and flow + */ + if (!node.value.body) { + return; + } + + const body = node.value.body.body; + const ctorParams = node.value.params; + const superClass = node.parent.parent.superClass; + + if (superClass ? isRedundantSuperCall(body, ctorParams) : (body.length === 0)) { + context.report({ + node, + messageId: "noUselessConstructor" + }); + } + } + + return { + MethodDefinition: checkForConstructor + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-escape.js b/node_modules/eslint/lib/rules/no-useless-escape.js new file mode 100644 index 0000000..0e0f6f0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-escape.js @@ -0,0 +1,333 @@ +/** + * @fileoverview Look for useless escapes in strings and regexes + * @author Onur Temizkan + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +/** + * @typedef {import('@eslint-community/regexpp').AST.CharacterClass} CharacterClass + * @typedef {import('@eslint-community/regexpp').AST.ExpressionCharacterClass} ExpressionCharacterClass + */ +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Returns the union of two sets. + * @param {Set} setA The first set + * @param {Set} setB The second set + * @returns {Set} The union of the two sets + */ +function union(setA, setB) { + return new Set(function *() { + yield* setA; + yield* setB; + }()); +} + +const VALID_STRING_ESCAPES = union(new Set("\\nrvtbfux"), astUtils.LINEBREAKS); +const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnpPrsStvwWxu0123456789]"); +const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()Bk")); + +/* + * Set of characters that require escaping in character classes in `unicodeSets` mode. + * ( ) [ ] { } / - \ | are ClassSetSyntaxCharacter + */ +const REGEX_CLASSSET_CHARACTER_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("q/[{}|()-")); + +/* + * A single character set of ClassSetReservedDoublePunctuator. + * && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ are ClassSetReservedDoublePunctuator + */ +const REGEX_CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR = new Set("!#$%&*+,.:;<=>?@^`~"); + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary escape characters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-escape" + }, + + hasSuggestions: true, + + messages: { + unnecessaryEscape: "Unnecessary escape character: \\{{character}}.", + removeEscape: "Remove the `\\`. This maintains the current functionality.", + removeEscapeDoNotKeepSemantics: "Remove the `\\` if it was inserted by mistake.", + escapeBackslash: "Replace the `\\` with `\\\\` to include the actual backslash character." + }, + + schema: [] + }, + + create(context) { + const sourceCode = context.sourceCode; + const parser = new RegExpParser(); + + /** + * Reports a node + * @param {ASTNode} node The node to report + * @param {number} startOffset The backslash's offset from the start of the node + * @param {string} character The uselessly escaped character (not including the backslash) + * @param {boolean} [disableEscapeBackslashSuggest] `true` if escapeBackslash suggestion should be turned off. + * @returns {void} + */ + function report(node, startOffset, character, disableEscapeBackslashSuggest) { + const rangeStart = node.range[0] + startOffset; + const range = [rangeStart, rangeStart + 1]; + const start = sourceCode.getLocFromIndex(rangeStart); + + context.report({ + node, + loc: { + start, + end: { line: start.line, column: start.column + 1 } + }, + messageId: "unnecessaryEscape", + data: { character }, + suggest: [ + { + + // Removing unnecessary `\` characters in a directive is not guaranteed to maintain functionality. + messageId: astUtils.isDirective(node.parent) + ? "removeEscapeDoNotKeepSemantics" : "removeEscape", + fix(fixer) { + return fixer.removeRange(range); + } + }, + ...disableEscapeBackslashSuggest + ? [] + : [ + { + messageId: "escapeBackslash", + fix(fixer) { + return fixer.insertTextBeforeRange(range, "\\"); + } + } + ] + ] + }); + } + + /** + * Checks if the escape character in given string slice is unnecessary. + * @private + * @param {ASTNode} node node to validate. + * @param {string} match string slice to validate. + * @returns {void} + */ + function validateString(node, match) { + const isTemplateElement = node.type === "TemplateElement"; + const escapedChar = match[0][1]; + let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar); + let isQuoteEscape; + + if (isTemplateElement) { + isQuoteEscape = escapedChar === "`"; + + if (escapedChar === "$") { + + // Warn if `\$` is not followed by `{` + isUnnecessaryEscape = match.input[match.index + 2] !== "{"; + } else if (escapedChar === "{") { + + /* + * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping + * is necessary and the rule should not warn. If preceded by `/$`, the rule + * will warn for the `/$` instead, as it is the first unnecessarily escaped character. + */ + isUnnecessaryEscape = match.input[match.index - 1] !== "$"; + } + } else { + isQuoteEscape = escapedChar === node.raw[0]; + } + + if (isUnnecessaryEscape && !isQuoteEscape) { + report(node, match.index, match[0].slice(1)); + } + } + + /** + * Checks if the escape character in given regexp is unnecessary. + * @private + * @param {ASTNode} node node to validate. + * @returns {void} + */ + function validateRegExp(node) { + const { pattern, flags } = node.regex; + let patternNode; + const unicode = flags.includes("u"); + const unicodeSets = flags.includes("v"); + + try { + patternNode = parser.parsePattern(pattern, 0, pattern.length, { unicode, unicodeSets }); + } catch { + + // Ignore regular expressions with syntax errors + return; + } + + /** @type {(CharacterClass | ExpressionCharacterClass)[]} */ + const characterClassStack = []; + + visitRegExpAST(patternNode, { + onCharacterClassEnter: characterClassNode => characterClassStack.unshift(characterClassNode), + onCharacterClassLeave: () => characterClassStack.shift(), + onExpressionCharacterClassEnter: characterClassNode => characterClassStack.unshift(characterClassNode), + onExpressionCharacterClassLeave: () => characterClassStack.shift(), + onCharacterEnter(characterNode) { + if (!characterNode.raw.startsWith("\\")) { + + // It's not an escaped character. + return; + } + + const escapedChar = characterNode.raw.slice(1); + + if (escapedChar !== String.fromCodePoint(characterNode.value)) { + + // It's a valid escape. + return; + } + let allowedEscapes; + + if (characterClassStack.length) { + allowedEscapes = unicodeSets ? REGEX_CLASSSET_CHARACTER_ESCAPES : REGEX_GENERAL_ESCAPES; + } else { + allowedEscapes = REGEX_NON_CHARCLASS_ESCAPES; + } + if (allowedEscapes.has(escapedChar)) { + return; + } + + const reportedIndex = characterNode.start + 1; + let disableEscapeBackslashSuggest = false; + + if (characterClassStack.length) { + const characterClassNode = characterClassStack[0]; + + if (escapedChar === "^") { + + /* + * The '^' character is also a special case; it must always be escaped outside of character classes, but + * it only needs to be escaped in character classes if it's at the beginning of the character class. To + * account for this, consider it to be a valid escape character outside of character classes, and filter + * out '^' characters that appear at the start of a character class. + */ + if (characterClassNode.start + 1 === characterNode.start) { + + return; + } + } + if (!unicodeSets) { + if (escapedChar === "-") { + + /* + * The '-' character is a special case, because it's only valid to escape it if it's in a character + * class, and is not at either edge of the character class. To account for this, don't consider '-' + * characters to be valid in general, and filter out '-' characters that appear in the middle of a + * character class. + */ + if (characterClassNode.start + 1 !== characterNode.start && characterNode.end !== characterClassNode.end - 1) { + + return; + } + } + } else { // unicodeSets mode + if (REGEX_CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR.has(escapedChar)) { + + // Escaping is valid if it is a ClassSetReservedDoublePunctuator. + if (pattern[characterNode.end] === escapedChar) { + return; + } + if (pattern[characterNode.start - 1] === escapedChar) { + if (escapedChar !== "^") { + return; + } + + // If the previous character is a `negate` caret(`^`), escape to caret is unnecessary. + + if (!characterClassNode.negate) { + return; + } + const negateCaretIndex = characterClassNode.start + 1; + + if (negateCaretIndex < characterNode.start - 1) { + return; + } + } + } + + if (characterNode.parent.type === "ClassIntersection" || characterNode.parent.type === "ClassSubtraction") { + disableEscapeBackslashSuggest = true; + } + } + } + + report( + node, + reportedIndex, + escapedChar, + disableEscapeBackslashSuggest + ); + } + }); + } + + /** + * Checks if a node has an escape. + * @param {ASTNode} node node to check. + * @returns {void} + */ + function check(node) { + const isTemplateElement = node.type === "TemplateElement"; + + if ( + isTemplateElement && + node.parent && + node.parent.parent && + node.parent.parent.type === "TaggedTemplateExpression" && + node.parent === node.parent.parent.quasi + ) { + + // Don't report tagged template literals, because the backslash character is accessible to the tag function. + return; + } + + if (typeof node.value === "string" || isTemplateElement) { + + /* + * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/. + * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25. + */ + if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") { + return; + } + + const value = isTemplateElement ? sourceCode.getText(node) : node.raw; + const pattern = /\\[^\d]/gu; + let match; + + while ((match = pattern.exec(value))) { + validateString(node, match); + } + } else if (node.regex) { + validateRegExp(node); + } + + } + + return { + Literal: check, + TemplateElement: check + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-rename.js b/node_modules/eslint/lib/rules/no-useless-rename.js new file mode 100644 index 0000000..0c818fb --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-rename.js @@ -0,0 +1,172 @@ +/** + * @fileoverview Disallow renaming import, export, and destructured assignments to the same name. + * @author Kai Cataldo + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow renaming import, export, and destructured assignments to the same name", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-rename" + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + ignoreDestructuring: { type: "boolean", default: false }, + ignoreImport: { type: "boolean", default: false }, + ignoreExport: { type: "boolean", default: false } + }, + additionalProperties: false + } + ], + + messages: { + unnecessarilyRenamed: "{{type}} {{name}} unnecessarily renamed." + } + }, + + create(context) { + const sourceCode = context.sourceCode, + options = context.options[0] || {}, + ignoreDestructuring = options.ignoreDestructuring === true, + ignoreImport = options.ignoreImport === true, + ignoreExport = options.ignoreExport === true; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports error for unnecessarily renamed assignments + * @param {ASTNode} node node to report + * @param {ASTNode} initial node with initial name value + * @param {string} type the type of the offending node + * @returns {void} + */ + function reportError(node, initial, type) { + const name = initial.type === "Identifier" ? initial.name : initial.value; + + return context.report({ + node, + messageId: "unnecessarilyRenamed", + data: { + name, + type + }, + fix(fixer) { + const replacementNode = node.type === "Property" ? node.value : node.local; + + if (sourceCode.getCommentsInside(node).length > sourceCode.getCommentsInside(replacementNode).length) { + return null; + } + + // Don't autofix code such as `({foo: (foo) = a} = obj);`, parens are not allowed in shorthand properties. + if ( + replacementNode.type === "AssignmentPattern" && + astUtils.isParenthesised(sourceCode, replacementNode.left) + ) { + return null; + } + + return fixer.replaceText(node, sourceCode.getText(replacementNode)); + } + }); + } + + /** + * Checks whether a destructured assignment is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkDestructured(node) { + if (ignoreDestructuring) { + return; + } + + for (const property of node.properties) { + + /** + * Properties using shorthand syntax and rest elements can not be renamed. + * If the property is computed, we have no idea if a rename is useless or not. + */ + if (property.type !== "Property" || property.shorthand || property.computed) { + continue; + } + + const key = (property.key.type === "Identifier" && property.key.name) || (property.key.type === "Literal" && property.key.value); + const renamedKey = property.value.type === "AssignmentPattern" ? property.value.left.name : property.value.name; + + if (key === renamedKey) { + reportError(property, property.key, "Destructuring assignment"); + } + } + } + + /** + * Checks whether an import is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkImport(node) { + if (ignoreImport) { + return; + } + + if ( + node.imported.range[0] !== node.local.range[0] && + astUtils.getModuleExportName(node.imported) === node.local.name + ) { + reportError(node, node.imported, "Import"); + } + } + + /** + * Checks whether an export is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkExport(node) { + if (ignoreExport) { + return; + } + + if ( + node.local.range[0] !== node.exported.range[0] && + astUtils.getModuleExportName(node.local) === astUtils.getModuleExportName(node.exported) + ) { + reportError(node, node.local, "Export"); + } + + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ObjectPattern: checkDestructured, + ImportSpecifier: checkImport, + ExportSpecifier: checkExport + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-useless-return.js b/node_modules/eslint/lib/rules/no-useless-return.js new file mode 100644 index 0000000..f895231 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-return.js @@ -0,0 +1,333 @@ +/** + * @fileoverview Disallow redundant return statements + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + FixTracker = require("./utils/fix-tracker"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Removes the given element from the array. + * @param {Array} array The source array to remove. + * @param {any} element The target item to remove. + * @returns {void} + */ +function remove(array, element) { + const index = array.indexOf(element); + + if (index !== -1) { + array.splice(index, 1); + } +} + +/** + * Checks whether it can remove the given return statement or not. + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if the node is removable. + */ +function isRemovable(node) { + return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type); +} + +/** + * Checks whether the given return statement is in a `finally` block or not. + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if the node is in a `finally` block. + */ +function isInFinally(node) { + for ( + let currentNode = node; + currentNode && currentNode.parent && !astUtils.isFunction(currentNode); + currentNode = currentNode.parent + ) { + if (currentNode.parent.type === "TryStatement" && currentNode.parent.finalizer === currentNode) { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow redundant return statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-return" + }, + + fixable: "code", + schema: [], + + messages: { + unnecessaryReturn: "Unnecessary return statement." + } + }, + + create(context) { + const segmentInfoMap = new WeakMap(); + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Checks whether the given segment is terminated by a return statement or not. + * @param {CodePathSegment} segment The segment to check. + * @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. + */ + function isReturned(segment) { + const info = segmentInfoMap.get(segment); + + return !info || info.returned; + } + + /** + * Collects useless return statements from the given previous segments. + * + * A previous segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * @param {ASTNode[]} uselessReturns The collected return statements. + * @param {CodePathSegment[]} prevSegments The previous segments to traverse. + * @param {WeakSet} [providedTraversedSegments] A set of segments that have already been traversed in this call + * @returns {ASTNode[]} `uselessReturns`. + */ + function getUselessReturns(uselessReturns, prevSegments, providedTraversedSegments) { + const traversedSegments = providedTraversedSegments || new WeakSet(); + + for (const segment of prevSegments) { + if (!segment.reachable) { + if (!traversedSegments.has(segment)) { + traversedSegments.add(segment); + getUselessReturns( + uselessReturns, + segment.allPrevSegments.filter(isReturned), + traversedSegments + ); + } + continue; + } + + uselessReturns.push(...segmentInfoMap.get(segment).uselessReturns); + } + + return uselessReturns; + } + + /** + * Removes the return statements on the given segment from the useless return + * statement list. + * + * This segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * @param {CodePathSegment} segment The segment to get return statements. + * @param {Set} usedUnreachableSegments A set of segments that have already been traversed in this call. + * @returns {void} + */ + function markReturnStatementsOnSegmentAsUsed(segment, usedUnreachableSegments) { + if (!segment.reachable) { + usedUnreachableSegments.add(segment); + segment.allPrevSegments + .filter(isReturned) + .filter(prevSegment => !usedUnreachableSegments.has(prevSegment)) + .forEach(prevSegment => markReturnStatementsOnSegmentAsUsed(prevSegment, usedUnreachableSegments)); + return; + } + + const info = segmentInfoMap.get(segment); + + info.uselessReturns = info.uselessReturns.filter(node => { + if (scopeInfo.traversedTryBlockStatements && scopeInfo.traversedTryBlockStatements.length > 0) { + const returnInitialRange = node.range[0]; + const returnFinalRange = node.range[1]; + + const areBlocksInRange = scopeInfo.traversedTryBlockStatements.some(tryBlockStatement => { + const blockInitialRange = tryBlockStatement.range[0]; + const blockFinalRange = tryBlockStatement.range[1]; + + return ( + returnInitialRange >= blockInitialRange && + returnFinalRange <= blockFinalRange + ); + }); + + if (areBlocksInRange) { + return true; + } + } + + remove(scopeInfo.uselessReturns, node); + return false; + }); + } + + /** + * Removes the return statements on the current segments from the useless + * return statement list. + * + * This function will be called at every statement except FunctionDeclaration, + * BlockStatement, and BreakStatement. + * + * - FunctionDeclarations are always executed whether it's returned or not. + * - BlockStatements do nothing. + * - BreakStatements go the next merely. + * @returns {void} + */ + function markReturnStatementsOnCurrentSegmentsAsUsed() { + scopeInfo + .codePath + .currentSegments + .forEach(segment => markReturnStatementsOnSegmentAsUsed(segment, new Set())); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + + // Makes and pushes a new scope information. + onCodePathStart(codePath) { + scopeInfo = { + upper: scopeInfo, + uselessReturns: [], + traversedTryBlockStatements: [], + codePath + }; + }, + + // Reports useless return statements if exist. + onCodePathEnd() { + for (const node of scopeInfo.uselessReturns) { + context.report({ + node, + loc: node.loc, + messageId: "unnecessaryReturn", + fix(fixer) { + if (isRemovable(node) && !sourceCode.getCommentsInside(node).length) { + + /* + * Extend the replacement range to include the + * entire function to avoid conflicting with + * no-else-return. + * https://github.com/eslint/eslint/issues/8026 + */ + return new FixTracker(fixer, sourceCode) + .retainEnclosingFunction(node) + .remove(node); + } + return null; + } + }); + } + + scopeInfo = scopeInfo.upper; + }, + + /* + * Initializes segments. + * NOTE: This event is notified for only reachable segments. + */ + onCodePathSegmentStart(segment) { + const info = { + uselessReturns: getUselessReturns([], segment.allPrevSegments), + returned: false + }; + + // Stores the info. + segmentInfoMap.set(segment, info); + }, + + // Adds ReturnStatement node to check whether it's useless or not. + ReturnStatement(node) { + if (node.argument) { + markReturnStatementsOnCurrentSegmentsAsUsed(); + } + if ( + node.argument || + astUtils.isInLoop(node) || + isInFinally(node) || + + // Ignore `return` statements in unreachable places (https://github.com/eslint/eslint/issues/11647). + !scopeInfo.codePath.currentSegments.some(s => s.reachable) + ) { + return; + } + + for (const segment of scopeInfo.codePath.currentSegments) { + const info = segmentInfoMap.get(segment); + + if (info) { + info.uselessReturns.push(node); + info.returned = true; + } + } + scopeInfo.uselessReturns.push(node); + }, + + "TryStatement > BlockStatement.block:exit"(node) { + scopeInfo.traversedTryBlockStatements.push(node); + }, + + "TryStatement:exit"() { + scopeInfo.traversedTryBlockStatements.pop(); + }, + + /* + * Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. + * Removes return statements of the current segments from the useless return statement list. + */ + ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportDefaultDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-var.js b/node_modules/eslint/lib/rules/no-var.js new file mode 100644 index 0000000..d45a91a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-var.js @@ -0,0 +1,334 @@ +/** + * @fileoverview Rule to check for the usage of var. + * @author Jamund Ferguson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Check whether a given variable is a global variable or not. + * @param {eslint-scope.Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is a global variable. + */ +function isGlobal(variable) { + return Boolean(variable.scope) && variable.scope.type === "global"; +} + +/** + * Finds the nearest function scope or global scope walking up the scope + * hierarchy. + * @param {eslint-scope.Scope} scope The scope to traverse. + * @returns {eslint-scope.Scope} a function scope or global scope containing the given + * scope. + */ +function getEnclosingFunctionScope(scope) { + let currentScope = scope; + + while (currentScope.type !== "function" && currentScope.type !== "global") { + currentScope = currentScope.upper; + } + return currentScope; +} + +/** + * Checks whether the given variable has any references from a more specific + * function expression (i.e. a closure). + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is used from a closure. + */ +function isReferencedInClosure(variable) { + const enclosingFunctionScope = getEnclosingFunctionScope(variable.scope); + + return variable.references.some(reference => + getEnclosingFunctionScope(reference.from) !== enclosingFunctionScope); +} + +/** + * Checks whether the given node is the assignee of a loop. + * @param {ASTNode} node A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration is assigned as part of loop + * iteration. + */ +function isLoopAssignee(node) { + return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") && + node === node.parent.left; +} + +/** + * Checks whether the given variable declaration is immediately initialized. + * @param {ASTNode} node A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration has an initializer. + */ +function isDeclarationInitialized(node) { + return node.declarations.every(declarator => declarator.init !== null); +} + +const SCOPE_NODE_TYPE = /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/u; + +/** + * Gets the scope node which directly contains a given node. + * @param {ASTNode} node A node to get. This is a `VariableDeclaration` or + * an `Identifier`. + * @returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`, + * `SwitchStatement`, `ForStatement`, `ForInStatement`, and + * `ForOfStatement`. + */ +function getScopeNode(node) { + for (let currentNode = node; currentNode; currentNode = currentNode.parent) { + if (SCOPE_NODE_TYPE.test(currentNode.type)) { + return currentNode; + } + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks whether a given variable is redeclared or not. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is redeclared. + */ +function isRedeclared(variable) { + return variable.defs.length >= 2; +} + +/** + * Checks whether a given variable is used from outside of the specified scope. + * @param {ASTNode} scopeNode A scope node to check. + * @returns {Function} The predicate function which checks whether a given + * variable is used from outside of the specified scope. + */ +function isUsedFromOutsideOf(scopeNode) { + + /** + * Checks whether a given reference is inside of the specified scope or not. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the specified + * scope. + */ + function isOutsideOfScope(reference) { + const scope = scopeNode.range; + const id = reference.identifier.range; + + return id[0] < scope[0] || id[1] > scope[1]; + } + + return function(variable) { + return variable.references.some(isOutsideOfScope); + }; +} + +/** + * Creates the predicate function which checks whether a variable has their references in TDZ. + * + * The predicate function would return `true`: + * + * - if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};) + * - if a reference is in the expression of their default value. E.g. (var {a = a} = {};) + * - if a reference is in the expression of their initializer. E.g. (var a = a;) + * @param {ASTNode} node The initializer node of VariableDeclarator. + * @returns {Function} The predicate function. + * @private + */ +function hasReferenceInTDZ(node) { + const initStart = node.range[0]; + const initEnd = node.range[1]; + + return variable => { + const id = variable.defs[0].name; + const idStart = id.range[0]; + const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null); + const defaultStart = defaultValue && defaultValue.range[0]; + const defaultEnd = defaultValue && defaultValue.range[1]; + + return variable.references.some(reference => { + const start = reference.identifier.range[0]; + const end = reference.identifier.range[1]; + + return !reference.init && ( + start < idStart || + (defaultValue !== null && start >= defaultStart && end <= defaultEnd) || + (!astUtils.isFunction(node) && start >= initStart && end <= initEnd) + ); + }); + }; +} + +/** + * Checks whether a given variable has name that is allowed for 'var' declarations, + * but disallowed for `let` declarations. + * @param {eslint-scope.Variable} variable The variable to check. + * @returns {boolean} `true` if the variable has a disallowed name. + */ +function hasNameDisallowedForLetDeclarations(variable) { + return variable.name === "let"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `let` or `const` instead of `var`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-var" + }, + + schema: [], + fixable: "code", + + messages: { + unexpectedVar: "Unexpected var, use let or const instead." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks whether the variables which are defined by the given declarator node have their references in TDZ. + * @param {ASTNode} declarator The VariableDeclarator node to check. + * @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ. + */ + function hasSelfReferenceInTDZ(declarator) { + if (!declarator.init) { + return false; + } + const variables = sourceCode.getDeclaredVariables(declarator); + + return variables.some(hasReferenceInTDZ(declarator.init)); + } + + /** + * Checks whether it can fix a given variable declaration or not. + * It cannot fix if the following cases: + * + * - A variable is a global variable. + * - A variable is declared on a SwitchCase node. + * - A variable is redeclared. + * - A variable is used from outside the scope. + * - A variable is used from a closure within a loop. + * - A variable might be used before it is assigned within a loop. + * - A variable might be used in TDZ. + * - A variable is declared in statement position (e.g. a single-line `IfStatement`) + * - A variable has name that is disallowed for `let` declarations. + * + * ## A variable is declared on a SwitchCase node. + * + * If this rule modifies 'var' declarations on a SwitchCase node, it + * would generate the warnings of 'no-case-declarations' rule. And the + * 'eslint:recommended' preset includes 'no-case-declarations' rule, so + * this rule doesn't modify those declarations. + * + * ## A variable is redeclared. + * + * The language spec disallows redeclarations of `let` declarations. + * Those variables would cause syntax errors. + * + * ## A variable is used from outside the scope. + * + * The language spec disallows accesses from outside of the scope for + * `let` declarations. Those variables would cause reference errors. + * + * ## A variable is used from a closure within a loop. + * + * A `var` declaration within a loop shares the same variable instance + * across all loop iterations, while a `let` declaration creates a new + * instance for each iteration. This means if a variable in a loop is + * referenced by any closure, changing it from `var` to `let` would + * change the behavior in a way that is generally unsafe. + * + * ## A variable might be used before it is assigned within a loop. + * + * Within a loop, a `let` declaration without an initializer will be + * initialized to null, while a `var` declaration will retain its value + * from the previous iteration, so it is only safe to change `var` to + * `let` if we can statically determine that the variable is always + * assigned a value before its first access in the loop body. To keep + * the implementation simple, we only convert `var` to `let` within + * loops when the variable is a loop assignee or the declaration has an + * initializer. + * @param {ASTNode} node A variable declaration node to check. + * @returns {boolean} `true` if it can fix the node. + */ + function canFix(node) { + const variables = sourceCode.getDeclaredVariables(node); + const scopeNode = getScopeNode(node); + + if (node.parent.type === "SwitchCase" || + node.declarations.some(hasSelfReferenceInTDZ) || + variables.some(isGlobal) || + variables.some(isRedeclared) || + variables.some(isUsedFromOutsideOf(scopeNode)) || + variables.some(hasNameDisallowedForLetDeclarations) + ) { + return false; + } + + if (astUtils.isInLoop(node)) { + if (variables.some(isReferencedInClosure)) { + return false; + } + if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) { + return false; + } + } + + if ( + !isLoopAssignee(node) && + !(node.parent.type === "ForStatement" && node.parent.init === node) && + !astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type) + ) { + + // If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed. + return false; + } + + return true; + } + + /** + * Reports a given variable declaration node. + * @param {ASTNode} node A variable declaration node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "unexpectedVar", + + fix(fixer) { + const varToken = sourceCode.getFirstToken(node, { filter: t => t.value === "var" }); + + return canFix(node) + ? fixer.replaceText(varToken, "let") + : null; + } + }); + } + + return { + "VariableDeclaration:exit"(node) { + if (node.kind === "var") { + report(node); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-void.js b/node_modules/eslint/lib/rules/no-void.js new file mode 100644 index 0000000..9546d7a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-void.js @@ -0,0 +1,64 @@ +/** + * @fileoverview Rule to disallow use of void operator. + * @author Mike Sidorov + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `void` operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-void" + }, + + messages: { + noVoid: "Expected 'undefined' and instead saw 'void'." + }, + + schema: [ + { + type: "object", + properties: { + allowAsStatement: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ] + }, + + create(context) { + const allowAsStatement = + context.options[0] && context.options[0].allowAsStatement; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + 'UnaryExpression[operator="void"]'(node) { + if ( + allowAsStatement && + node.parent && + node.parent.type === "ExpressionStatement" + ) { + return; + } + context.report({ + node, + messageId: "noVoid" + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-warning-comments.js b/node_modules/eslint/lib/rules/no-warning-comments.js new file mode 100644 index 0000000..c415bee --- /dev/null +++ b/node_modules/eslint/lib/rules/no-warning-comments.js @@ -0,0 +1,201 @@ +/** + * @fileoverview Rule that warns about used warning comments + * @author Alexander Schmidt + */ + +"use strict"; + +const escapeRegExp = require("escape-string-regexp"); +const astUtils = require("./utils/ast-utils"); + +const CHAR_LIMIT = 40; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified warning terms in comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-warning-comments" + }, + + schema: [ + { + type: "object", + properties: { + terms: { + type: "array", + items: { + type: "string" + } + }, + location: { + enum: ["start", "anywhere"] + }, + decoration: { + type: "array", + items: { + type: "string", + pattern: "^\\S$" + }, + minItems: 1, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedComment: "Unexpected '{{matchedTerm}}' comment: '{{comment}}'." + } + }, + + create(context) { + const sourceCode = context.sourceCode, + configuration = context.options[0] || {}, + warningTerms = configuration.terms || ["todo", "fixme", "xxx"], + location = configuration.location || "start", + decoration = [...configuration.decoration || []].join(""), + selfConfigRegEx = /\bno-warning-comments\b/u; + + /** + * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified + * location ("start" or "anywhere"). If the term starts or ends with non word characters, then the match will not + * require word boundaries on that side. + * @param {string} term A term to convert to a RegExp + * @returns {RegExp} The term converted to a RegExp + */ + function convertToRegExp(term) { + const escaped = escapeRegExp(term); + const escapedDecoration = escapeRegExp(decoration); + + /* + * When matching at the start, ignore leading whitespace, and + * there's no need to worry about word boundaries. + * + * These expressions for the prefix and suffix are designed as follows: + * ^ handles any terms at the beginning of a comment. + * e.g. terms ["TODO"] matches `//TODO something` + * $ handles any terms at the end of a comment + * e.g. terms ["TODO"] matches `// something TODO` + * \b handles terms preceded/followed by word boundary + * e.g. terms: ["!FIX", "FIX!"] matches `// FIX!something` or `// something!FIX` + * terms: ["FIX"] matches `// FIX!` or `// !FIX`, but not `// fixed or affix` + * + * For location start: + * [\s]* handles optional leading spaces + * e.g. terms ["TODO"] matches `// TODO something` + * [\s\*]* (where "\*" is the escaped string of decoration) + * handles optional leading spaces or decoration characters (for "start" location only) + * e.g. terms ["TODO"] matches `/**** TODO something ... ` + */ + const wordBoundary = "\\b"; + + let prefix = ""; + + if (location === "start") { + prefix = `^[\\s${escapedDecoration}]*`; + } else if (/^\w/u.test(term)) { + prefix = wordBoundary; + } + + const suffix = /\w$/u.test(term) ? wordBoundary : ""; + const flags = "iu"; // Case-insensitive with Unicode case folding. + + /* + * For location "start", the typical regex is: + * /^[\s]*ESCAPED_TERM\b/iu. + * Or if decoration characters are specified (e.g. "*"), then any of + * those characters may appear in any order at the start: + * /^[\s\*]*ESCAPED_TERM\b/iu. + * + * For location "anywhere" the typical regex is + * /\bESCAPED_TERM\b/iu + * + * If it starts or ends with non-word character, the prefix and suffix are empty, respectively. + */ + return new RegExp(`${prefix}${escaped}${suffix}`, flags); + } + + const warningRegExps = warningTerms.map(convertToRegExp); + + /** + * Checks the specified comment for matches of the configured warning terms and returns the matches. + * @param {string} comment The comment which is checked. + * @returns {Array} All matched warning terms for this comment. + */ + function commentContainsWarningTerm(comment) { + const matches = []; + + warningRegExps.forEach((regex, index) => { + if (regex.test(comment)) { + matches.push(warningTerms[index]); + } + }); + + return matches; + } + + /** + * Checks the specified node for matching warning comments and reports them. + * @param {ASTNode} node The AST node being checked. + * @returns {void} undefined. + */ + function checkComment(node) { + const comment = node.value; + + if ( + astUtils.isDirectiveComment(node) && + selfConfigRegEx.test(comment) + ) { + return; + } + + const matches = commentContainsWarningTerm(comment); + + matches.forEach(matchedTerm => { + let commentToDisplay = ""; + let truncated = false; + + for (const c of comment.trim().split(/\s+/u)) { + const tmp = commentToDisplay ? `${commentToDisplay} ${c}` : c; + + if (tmp.length <= CHAR_LIMIT) { + commentToDisplay = tmp; + } else { + truncated = true; + break; + } + } + + context.report({ + node, + messageId: "unexpectedComment", + data: { + matchedTerm, + comment: `${commentToDisplay}${ + truncated ? "..." : "" + }` + } + }); + }); + } + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type !== "Shebang") + .forEach(checkComment); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-whitespace-before-property.js b/node_modules/eslint/lib/rules/no-whitespace-before-property.js new file mode 100644 index 0000000..1153314 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-whitespace-before-property.js @@ -0,0 +1,113 @@ +/** + * @fileoverview Rule to disallow whitespace before properties + * @author Kai Cataldo + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Disallow whitespace before properties", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-whitespace-before-property" + }, + + fixable: "whitespace", + schema: [], + + messages: { + unexpectedWhitespace: "Unexpected whitespace before property {{propName}}." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports whitespace before property token + * @param {ASTNode} node the node to report in the event of an error + * @param {Token} leftToken the left token + * @param {Token} rightToken the right token + * @returns {void} + * @private + */ + function reportError(node, leftToken, rightToken) { + context.report({ + node, + messageId: "unexpectedWhitespace", + data: { + propName: sourceCode.getText(node.property) + }, + fix(fixer) { + let replacementText = ""; + + if (!node.computed && !node.optional && astUtils.isDecimalInteger(node.object)) { + + /* + * If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError. + * Don't fix this case. + */ + return null; + } + + // Don't fix if comments exist. + if (sourceCode.commentsExistBetween(leftToken, rightToken)) { + return null; + } + + if (node.optional) { + replacementText = "?."; + } else if (!node.computed) { + replacementText = "."; + } + + return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], replacementText); + } + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + MemberExpression(node) { + let rightToken; + let leftToken; + + if (!astUtils.isTokenOnSameLine(node.object, node.property)) { + return; + } + + if (node.computed) { + rightToken = sourceCode.getTokenBefore(node.property, astUtils.isOpeningBracketToken); + leftToken = sourceCode.getTokenBefore(rightToken, node.optional ? 1 : 0); + } else { + rightToken = sourceCode.getFirstToken(node.property); + leftToken = sourceCode.getTokenBefore(rightToken, 1); + } + + if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken)) { + reportError(node, leftToken, rightToken); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/no-with.js b/node_modules/eslint/lib/rules/no-with.js new file mode 100644 index 0000000..0fb2c45 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-with.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Rule to flag use of with statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `with` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-with" + }, + + schema: [], + + messages: { + unexpectedWith: "Unexpected use of 'with' statement." + } + }, + + create(context) { + + return { + WithStatement(node) { + context.report({ node, messageId: "unexpectedWith" }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/nonblock-statement-body-position.js b/node_modules/eslint/lib/rules/nonblock-statement-body-position.js new file mode 100644 index 0000000..1ea2770 --- /dev/null +++ b/node_modules/eslint/lib/rules/nonblock-statement-body-position.js @@ -0,0 +1,124 @@ +/** + * @fileoverview enforce the location of single-line statements + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const POSITION_SCHEMA = { enum: ["beside", "below", "any"] }; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce the location of single-line statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/nonblock-statement-body-position" + }, + + fixable: "whitespace", + + schema: [ + POSITION_SCHEMA, + { + properties: { + overrides: { + properties: { + if: POSITION_SCHEMA, + else: POSITION_SCHEMA, + while: POSITION_SCHEMA, + do: POSITION_SCHEMA, + for: POSITION_SCHEMA + }, + additionalProperties: false + } + }, + additionalProperties: false + } + ], + + messages: { + expectNoLinebreak: "Expected no linebreak before this statement.", + expectLinebreak: "Expected a linebreak before this statement." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Gets the applicable preference for a particular keyword + * @param {string} keywordName The name of a keyword, e.g. 'if' + * @returns {string} The applicable option for the keyword, e.g. 'beside' + */ + function getOption(keywordName) { + return context.options[1] && context.options[1].overrides && context.options[1].overrides[keywordName] || + context.options[0] || + "beside"; + } + + /** + * Validates the location of a single-line statement + * @param {ASTNode} node The single-line statement + * @param {string} keywordName The applicable keyword name for the single-line statement + * @returns {void} + */ + function validateStatement(node, keywordName) { + const option = getOption(keywordName); + + if (node.type === "BlockStatement" || option === "any") { + return; + } + + const tokenBefore = sourceCode.getTokenBefore(node); + + if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") { + context.report({ + node, + messageId: "expectLinebreak", + fix: fixer => fixer.insertTextBefore(node, "\n") + }); + } else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") { + context.report({ + node, + messageId: "expectNoLinebreak", + fix(fixer) { + if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) { + return null; + } + return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " "); + } + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + IfStatement(node) { + validateStatement(node.consequent, "if"); + + // Check the `else` node, but don't check 'else if' statements. + if (node.alternate && node.alternate.type !== "IfStatement") { + validateStatement(node.alternate, "else"); + } + }, + WhileStatement: node => validateStatement(node.body, "while"), + DoWhileStatement: node => validateStatement(node.body, "do"), + ForStatement: node => validateStatement(node.body, "for"), + ForInStatement: node => validateStatement(node.body, "for"), + ForOfStatement: node => validateStatement(node.body, "for") + }; + } +}; diff --git a/node_modules/eslint/lib/rules/object-curly-newline.js b/node_modules/eslint/lib/rules/object-curly-newline.js new file mode 100644 index 0000000..caf1982 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-curly-newline.js @@ -0,0 +1,321 @@ +/** + * @fileoverview Rule to require or disallow line breaks inside braces. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Schema objects. +const OPTION_VALUE = { + oneOf: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + multiline: { + type: "boolean" + }, + minProperties: { + type: "integer", + minimum: 0 + }, + consistent: { + type: "boolean" + } + }, + additionalProperties: false, + minProperties: 1 + } + ] +}; + +/** + * Normalizes a given option value. + * @param {string|Object|undefined} value An option value to parse. + * @returns {{multiline: boolean, minProperties: number, consistent: boolean}} Normalized option object. + */ +function normalizeOptionValue(value) { + let multiline = false; + let minProperties = Number.POSITIVE_INFINITY; + let consistent = false; + + if (value) { + if (value === "always") { + minProperties = 0; + } else if (value === "never") { + minProperties = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(value.multiline); + minProperties = value.minProperties || Number.POSITIVE_INFINITY; + consistent = Boolean(value.consistent); + } + } else { + consistent = true; + } + + return { multiline, minProperties, consistent }; +} + +/** + * Checks if a value is an object. + * @param {any} value The value to check + * @returns {boolean} `true` if the value is an object, otherwise `false` + */ +function isObject(value) { + return typeof value === "object" && value !== null; +} + +/** + * Checks if an option is a node-specific option + * @param {any} option The option to check + * @returns {boolean} `true` if the option is node-specific, otherwise `false` + */ +function isNodeSpecificOption(option) { + return isObject(option) || typeof option === "string"; +} + +/** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ + * ObjectExpression: {multiline: boolean, minProperties: number, consistent: boolean}, + * ObjectPattern: {multiline: boolean, minProperties: number, consistent: boolean}, + * ImportDeclaration: {multiline: boolean, minProperties: number, consistent: boolean}, + * ExportNamedDeclaration : {multiline: boolean, minProperties: number, consistent: boolean} + * }} Normalized option object. + */ +function normalizeOptions(options) { + if (isObject(options) && Object.values(options).some(isNodeSpecificOption)) { + return { + ObjectExpression: normalizeOptionValue(options.ObjectExpression), + ObjectPattern: normalizeOptionValue(options.ObjectPattern), + ImportDeclaration: normalizeOptionValue(options.ImportDeclaration), + ExportNamedDeclaration: normalizeOptionValue(options.ExportDeclaration) + }; + } + + const value = normalizeOptionValue(options); + + return { ObjectExpression: value, ObjectPattern: value, ImportDeclaration: value, ExportNamedDeclaration: value }; +} + +/** + * Determines if ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration + * node needs to be checked for missing line breaks + * @param {ASTNode} node Node under inspection + * @param {Object} options option specific to node type + * @param {Token} first First object property + * @param {Token} last Last object property + * @returns {boolean} `true` if node needs to be checked for missing line breaks + */ +function areLineBreaksRequired(node, options, first, last) { + let objectProperties; + + if (node.type === "ObjectExpression" || node.type === "ObjectPattern") { + objectProperties = node.properties; + } else { + + // is ImportDeclaration or ExportNamedDeclaration + objectProperties = node.specifiers + .filter(s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier"); + } + + return objectProperties.length >= options.minProperties || + ( + options.multiline && + objectProperties.length > 0 && + first.loc.start.line !== last.loc.end.line + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent line breaks after opening and before closing braces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-curly-newline" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + OPTION_VALUE, + { + type: "object", + properties: { + ObjectExpression: OPTION_VALUE, + ObjectPattern: OPTION_VALUE, + ImportDeclaration: OPTION_VALUE, + ExportDeclaration: OPTION_VALUE + }, + additionalProperties: false, + minProperties: 1 + } + ] + } + ], + + messages: { + unexpectedLinebreakBeforeClosingBrace: "Unexpected line break before this closing brace.", + unexpectedLinebreakAfterOpeningBrace: "Unexpected line break after this opening brace.", + expectedLinebreakBeforeClosingBrace: "Expected a line break before this closing brace.", + expectedLinebreakAfterOpeningBrace: "Expected a line break after this opening brace." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const normalizedOptions = normalizeOptions(context.options[0]); + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration node. + * @returns {void} + */ + function check(node) { + const options = normalizedOptions[node.type]; + + if ( + (node.type === "ImportDeclaration" && + !node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) || + (node.type === "ExportNamedDeclaration" && + !node.specifiers.some(specifier => specifier.type === "ExportSpecifier")) + ) { + return; + } + + const openBrace = sourceCode.getFirstToken(node, token => token.value === "{"); + + let closeBrace; + + if (node.typeAnnotation) { + closeBrace = sourceCode.getTokenBefore(node.typeAnnotation); + } else { + closeBrace = sourceCode.getLastToken(node, token => token.value === "}"); + } + + let first = sourceCode.getTokenAfter(openBrace, { includeComments: true }); + let last = sourceCode.getTokenBefore(closeBrace, { includeComments: true }); + + const needsLineBreaks = areLineBreaksRequired(node, options, first, last); + + const hasCommentsFirstToken = astUtils.isCommentToken(first); + const hasCommentsLastToken = astUtils.isCommentToken(last); + + /* + * Use tokens or comments to check multiline or not. + * But use only tokens to check whether line breaks are needed. + * This allows: + * var obj = { // eslint-disable-line foo + * a: 1 + * } + */ + first = sourceCode.getTokenAfter(openBrace); + last = sourceCode.getTokenBefore(closeBrace); + + if (needsLineBreaks) { + if (astUtils.isTokenOnSameLine(openBrace, first)) { + context.report({ + messageId: "expectedLinebreakAfterOpeningBrace", + node, + loc: openBrace.loc, + fix(fixer) { + if (hasCommentsFirstToken) { + return null; + } + + return fixer.insertTextAfter(openBrace, "\n"); + } + }); + } + if (astUtils.isTokenOnSameLine(last, closeBrace)) { + context.report({ + messageId: "expectedLinebreakBeforeClosingBrace", + node, + loc: closeBrace.loc, + fix(fixer) { + if (hasCommentsLastToken) { + return null; + } + + return fixer.insertTextBefore(closeBrace, "\n"); + } + }); + } + } else { + const consistent = options.consistent; + const hasLineBreakBetweenOpenBraceAndFirst = !astUtils.isTokenOnSameLine(openBrace, first); + const hasLineBreakBetweenCloseBraceAndLast = !astUtils.isTokenOnSameLine(last, closeBrace); + + if ( + (!consistent && hasLineBreakBetweenOpenBraceAndFirst) || + (consistent && hasLineBreakBetweenOpenBraceAndFirst && !hasLineBreakBetweenCloseBraceAndLast) + ) { + context.report({ + messageId: "unexpectedLinebreakAfterOpeningBrace", + node, + loc: openBrace.loc, + fix(fixer) { + if (hasCommentsFirstToken) { + return null; + } + + return fixer.removeRange([ + openBrace.range[1], + first.range[0] + ]); + } + }); + } + if ( + (!consistent && hasLineBreakBetweenCloseBraceAndLast) || + (consistent && !hasLineBreakBetweenOpenBraceAndFirst && hasLineBreakBetweenCloseBraceAndLast) + ) { + context.report({ + messageId: "unexpectedLinebreakBeforeClosingBrace", + node, + loc: closeBrace.loc, + fix(fixer) { + if (hasCommentsLastToken) { + return null; + } + + return fixer.removeRange([ + last.range[1], + closeBrace.range[0] + ]); + } + }); + } + } + } + + return { + ObjectExpression: check, + ObjectPattern: check, + ImportDeclaration: check, + ExportNamedDeclaration: check + }; + } +}; diff --git a/node_modules/eslint/lib/rules/object-curly-spacing.js b/node_modules/eslint/lib/rules/object-curly-spacing.js new file mode 100644 index 0000000..41ca428 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-curly-spacing.js @@ -0,0 +1,308 @@ +/** + * @fileoverview Disallows or enforces spaces inside of object literals. + * @author Jamund Ferguson + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing inside braces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-curly-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + arraysInObjects: { + type: "boolean" + }, + objectsInObjects: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + + messages: { + requireSpaceBefore: "A space is required before '{{token}}'.", + requireSpaceAfter: "A space is required after '{{token}}'.", + unexpectedSpaceBefore: "There should be no space before '{{token}}'.", + unexpectedSpaceAfter: "There should be no space after '{{token}}'." + } + }, + + create(context) { + const spaced = context.options[0] === "always", + sourceCode = context.sourceCode; + + /** + * Determines whether an option is set, relative to the spacing option. + * If spaced is "always", then check whether option is set to false. + * If spaced is "never", then check whether option is set to true. + * @param {Object} option The option to exclude. + * @returns {boolean} Whether or not the property is excluded. + */ + function isOptionSet(option) { + return context.options[1] ? context.options[1][option] === !spaced : false; + } + + const options = { + spaced, + arraysInObjectsException: isOptionSet("arraysInObjects"), + objectsInObjectsException: isOptionSet("objectsInObjects") + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningSpace(node, token) { + const nextToken = context.sourceCode.getTokenAfter(token, { includeComments: true }); + + context.report({ + node, + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + token: token.value + }, + fix(fixer) { + return fixer.removeRange([token.range[1], nextToken.range[0]]); + } + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingSpace(node, token) { + const previousToken = context.sourceCode.getTokenBefore(token, { includeComments: true }); + + context.report({ + node, + loc: { start: previousToken.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + token: token.value + }, + fix(fixer) { + return fixer.removeRange([previousToken.range[1], token.range[0]]); + } + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "requireSpaceAfter", + data: { + token: token.value + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + } + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "requireSpaceBefore", + data: { + token: token.value + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + } + }); + } + + /** + * Determines if spacing in curly braces is valid. + * @param {ASTNode} node The AST node to check. + * @param {Token} first The first token to check (should be the opening brace) + * @param {Token} second The second token to check (should be first after the opening brace) + * @param {Token} penultimate The penultimate token to check (should be last before closing brace) + * @param {Token} last The last token to check (should be closing brace) + * @returns {void} + */ + function validateBraceSpacing(node, first, second, penultimate, last) { + if (astUtils.isTokenOnSameLine(first, second)) { + const firstSpaced = sourceCode.isSpaceBetweenTokens(first, second); + + if (options.spaced && !firstSpaced) { + reportRequiredBeginningSpace(node, first); + } + if (!options.spaced && firstSpaced && second.type !== "Line") { + reportNoBeginningSpace(node, first); + } + } + + if (astUtils.isTokenOnSameLine(penultimate, last)) { + const shouldCheckPenultimate = ( + options.arraysInObjectsException && astUtils.isClosingBracketToken(penultimate) || + options.objectsInObjectsException && astUtils.isClosingBraceToken(penultimate) + ); + const penultimateType = shouldCheckPenultimate && sourceCode.getNodeByRangeIndex(penultimate.range[0]).type; + + const closingCurlyBraceMustBeSpaced = ( + options.arraysInObjectsException && penultimateType === "ArrayExpression" || + options.objectsInObjectsException && (penultimateType === "ObjectExpression" || penultimateType === "ObjectPattern") + ) ? !options.spaced : options.spaced; + + const lastSpaced = sourceCode.isSpaceBetweenTokens(penultimate, last); + + if (closingCurlyBraceMustBeSpaced && !lastSpaced) { + reportRequiredEndingSpace(node, last); + } + if (!closingCurlyBraceMustBeSpaced && lastSpaced) { + reportNoEndingSpace(node, last); + } + } + } + + /** + * Gets '}' token of an object node. + * + * Because the last token of object patterns might be a type annotation, + * this traverses tokens preceded by the last property, then returns the + * first '}' token. + * @param {ASTNode} node The node to get. This node is an + * ObjectExpression or an ObjectPattern. And this node has one or + * more properties. + * @returns {Token} '}' token. + */ + function getClosingBraceOfObject(node) { + const lastProperty = node.properties[node.properties.length - 1]; + + return sourceCode.getTokenAfter(lastProperty, astUtils.isClosingBraceToken); + } + + /** + * Reports a given object node if spacing in curly braces is invalid. + * @param {ASTNode} node An ObjectExpression or ObjectPattern node to check. + * @returns {void} + */ + function checkForObject(node) { + if (node.properties.length === 0) { + return; + } + + const first = sourceCode.getFirstToken(node), + last = getClosingBraceOfObject(node), + second = sourceCode.getTokenAfter(first, { includeComments: true }), + penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + /** + * Reports a given import node if spacing in curly braces is invalid. + * @param {ASTNode} node An ImportDeclaration node to check. + * @returns {void} + */ + function checkForImport(node) { + if (node.specifiers.length === 0) { + return; + } + + let firstSpecifier = node.specifiers[0]; + const lastSpecifier = node.specifiers[node.specifiers.length - 1]; + + if (lastSpecifier.type !== "ImportSpecifier") { + return; + } + if (firstSpecifier.type !== "ImportSpecifier") { + firstSpecifier = node.specifiers[1]; + } + + const first = sourceCode.getTokenBefore(firstSpecifier), + last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken), + second = sourceCode.getTokenAfter(first, { includeComments: true }), + penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + /** + * Reports a given export node if spacing in curly braces is invalid. + * @param {ASTNode} node An ExportNamedDeclaration node to check. + * @returns {void} + */ + function checkForExport(node) { + if (node.specifiers.length === 0) { + return; + } + + const firstSpecifier = node.specifiers[0], + lastSpecifier = node.specifiers[node.specifiers.length - 1], + first = sourceCode.getTokenBefore(firstSpecifier), + last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken), + second = sourceCode.getTokenAfter(first, { includeComments: true }), + penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + // var {x} = y; + ObjectPattern: checkForObject, + + // var y = {x: 'y'} + ObjectExpression: checkForObject, + + // import {y} from 'x'; + ImportDeclaration: checkForImport, + + // export {name} from 'yo'; + ExportNamedDeclaration: checkForExport + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/object-property-newline.js b/node_modules/eslint/lib/rules/object-property-newline.js new file mode 100644 index 0000000..deca9b5 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-property-newline.js @@ -0,0 +1,99 @@ +/** + * @fileoverview Rule to enforce placing object properties on separate lines. + * @author Vitor Balocco + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce placing object properties on separate lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-property-newline" + }, + + schema: [ + { + type: "object", + properties: { + allowAllPropertiesOnSameLine: { + type: "boolean", + default: false + }, + allowMultiplePropertiesPerLine: { // Deprecated + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + fixable: "whitespace", + + messages: { + propertiesOnNewlineAll: "Object properties must go on a new line if they aren't all on the same line.", + propertiesOnNewline: "Object properties must go on a new line." + } + }, + + create(context) { + const allowSameLine = context.options[0] && ( + (context.options[0].allowAllPropertiesOnSameLine || context.options[0].allowMultiplePropertiesPerLine /* Deprecated */) + ); + const messageId = allowSameLine + ? "propertiesOnNewlineAll" + : "propertiesOnNewline"; + + const sourceCode = context.sourceCode; + + return { + ObjectExpression(node) { + if (allowSameLine) { + if (node.properties.length > 1) { + const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.properties[0]); + const lastTokenOfLastProperty = sourceCode.getLastToken(node.properties[node.properties.length - 1]); + + if (firstTokenOfFirstProperty.loc.end.line === lastTokenOfLastProperty.loc.start.line) { + + // All keys and values are on the same line + return; + } + } + } + + for (let i = 1; i < node.properties.length; i++) { + const lastTokenOfPreviousProperty = sourceCode.getLastToken(node.properties[i - 1]); + const firstTokenOfCurrentProperty = sourceCode.getFirstToken(node.properties[i]); + + if (lastTokenOfPreviousProperty.loc.end.line === firstTokenOfCurrentProperty.loc.start.line) { + context.report({ + node, + loc: firstTokenOfCurrentProperty.loc, + messageId, + fix(fixer) { + const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty); + const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]]; + + // Don't perform a fix if there are any comments between the comma and the next property. + if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) { + return null; + } + + return fixer.replaceTextRange(rangeAfterComma, "\n"); + } + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/object-shorthand.js b/node_modules/eslint/lib/rules/object-shorthand.js new file mode 100644 index 0000000..e4cb3a4 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-shorthand.js @@ -0,0 +1,520 @@ +/** + * @fileoverview Rule to enforce concise object methods and properties. + * @author Jamund Ferguson + */ + +"use strict"; + +const OPTIONS = { + always: "always", + never: "never", + methods: "methods", + properties: "properties", + consistent: "consistent", + consistentAsNeeded: "consistent-as-needed" +}; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require or disallow method and property shorthand syntax for object literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-shorthand" + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always", "methods", "properties", "never", "consistent", "consistent-as-needed"] + } + ], + minItems: 0, + maxItems: 1 + }, + { + type: "array", + items: [ + { + enum: ["always", "methods", "properties"] + }, + { + type: "object", + properties: { + avoidQuotes: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + }, + { + type: "array", + items: [ + { + enum: ["always", "methods"] + }, + { + type: "object", + properties: { + ignoreConstructors: { + type: "boolean" + }, + methodsIgnorePattern: { + type: "string" + }, + avoidQuotes: { + type: "boolean" + }, + avoidExplicitReturnArrows: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + } + ] + }, + + messages: { + expectedAllPropertiesShorthanded: "Expected shorthand for all properties.", + expectedLiteralMethodLongform: "Expected longform method syntax for string literal keys.", + expectedPropertyShorthand: "Expected property shorthand.", + expectedPropertyLongform: "Expected longform property syntax.", + expectedMethodShorthand: "Expected method shorthand.", + expectedMethodLongform: "Expected longform method syntax.", + unexpectedMix: "Unexpected mix of shorthand and non-shorthand properties." + } + }, + + create(context) { + const APPLY = context.options[0] || OPTIONS.always; + const APPLY_TO_METHODS = APPLY === OPTIONS.methods || APPLY === OPTIONS.always; + const APPLY_TO_PROPS = APPLY === OPTIONS.properties || APPLY === OPTIONS.always; + const APPLY_NEVER = APPLY === OPTIONS.never; + const APPLY_CONSISTENT = APPLY === OPTIONS.consistent; + const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded; + + const PARAMS = context.options[1] || {}; + const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors; + const METHODS_IGNORE_PATTERN = PARAMS.methodsIgnorePattern + ? new RegExp(PARAMS.methodsIgnorePattern, "u") + : null; + const AVOID_QUOTES = PARAMS.avoidQuotes; + const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const CTOR_PREFIX_REGEX = /[^_$0-9]/u; + + /** + * Determines if the first character of the name is a capital letter. + * @param {string} name The name of the node to evaluate. + * @returns {boolean} True if the first character of the property name is a capital letter, false if not. + * @private + */ + function isConstructor(name) { + const match = CTOR_PREFIX_REGEX.exec(name); + + // Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8' + if (!match) { + return false; + } + + const firstChar = name.charAt(match.index); + + return firstChar === firstChar.toUpperCase(); + } + + /** + * Determines if the property can have a shorthand form. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the property can have a shorthand form + * @private + */ + function canHaveShorthand(property) { + return (property.kind !== "set" && property.kind !== "get" && property.type !== "SpreadElement" && property.type !== "SpreadProperty" && property.type !== "ExperimentalSpreadProperty"); + } + + /** + * Checks whether a node is a string literal. + * @param {ASTNode} node Any AST node. + * @returns {boolean} `true` if it is a string literal. + */ + function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; + } + + /** + * Determines if the property is a shorthand or not. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the property is considered shorthand, false if not. + * @private + */ + function isShorthand(property) { + + // property.method is true when `{a(){}}`. + return (property.shorthand || property.method); + } + + /** + * Determines if the property's key and method or value are named equally. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the key and value are named equally, false if not. + * @private + */ + function isRedundant(property) { + const value = property.value; + + if (value.type === "FunctionExpression") { + return !value.id; // Only anonymous should be shorthand method. + } + if (value.type === "Identifier") { + return astUtils.getStaticPropertyName(property) === value.name; + } + + return false; + } + + /** + * Ensures that an object's properties are consistently shorthand, or not shorthand at all. + * @param {ASTNode} node Property AST node + * @param {boolean} checkRedundancy Whether to check longform redundancy + * @returns {void} + */ + function checkConsistency(node, checkRedundancy) { + + // We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand. + const properties = node.properties.filter(canHaveShorthand); + + // Do we still have properties left after filtering the getters and setters? + if (properties.length > 0) { + const shorthandProperties = properties.filter(isShorthand); + + /* + * If we do not have an equal number of longform properties as + * shorthand properties, we are using the annotations inconsistently + */ + if (shorthandProperties.length !== properties.length) { + + // We have at least 1 shorthand property + if (shorthandProperties.length > 0) { + context.report({ node, messageId: "unexpectedMix" }); + } else if (checkRedundancy) { + + /* + * If all properties of the object contain a method or value with a name matching it's key, + * all the keys are redundant. + */ + const canAlwaysUseShorthand = properties.every(isRedundant); + + if (canAlwaysUseShorthand) { + context.report({ node, messageId: "expectedAllPropertiesShorthanded" }); + } + } + } + } + } + + /** + * Fixes a FunctionExpression node by making it into a shorthand property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionShorthand(fixer, node) { + const firstKeyToken = node.computed + ? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken) + : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed + ? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken) + : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); + let keyPrefix = ""; + + // key: /* */ () => {} + if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) { + return null; + } + + if (node.value.async) { + keyPrefix += "async "; + } + if (node.value.generator) { + keyPrefix += "*"; + } + + const fixRange = [firstKeyToken.range[0], node.range[1]]; + const methodPrefix = keyPrefix + keyText; + + if (node.value.type === "FunctionExpression") { + const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function"); + const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken; + + return fixer.replaceTextRange( + fixRange, + methodPrefix + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1]) + ); + } + + const arrowToken = sourceCode.getTokenBefore(node.value.body, astUtils.isArrowToken); + const fnBody = sourceCode.text.slice(arrowToken.range[1], node.value.range[1]); + + let shouldAddParensAroundParameters = false; + let tokenBeforeParams; + + if (node.value.params.length === 0) { + tokenBeforeParams = sourceCode.getFirstToken(node.value, astUtils.isOpeningParenToken); + } else { + tokenBeforeParams = sourceCode.getTokenBefore(node.value.params[0]); + } + + if (node.value.params.length === 1) { + const hasParen = astUtils.isOpeningParenToken(tokenBeforeParams); + const isTokenOutsideNode = tokenBeforeParams.range[0] < node.range[0]; + + shouldAddParensAroundParameters = !hasParen || isTokenOutsideNode; + } + + const sliceStart = shouldAddParensAroundParameters + ? node.value.params[0].range[0] + : tokenBeforeParams.range[0]; + const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1]; + + const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd); + const newParamText = shouldAddParensAroundParameters ? `(${oldParamText})` : oldParamText; + + return fixer.replaceTextRange( + fixRange, + methodPrefix + newParamText + fnBody + ); + + } + + /** + * Fixes a FunctionExpression node by making it into a longform property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionLongform(fixer, node) { + const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); + let functionHeader = "function"; + + if (node.value.async) { + functionHeader = `async ${functionHeader}`; + } + if (node.value.generator) { + functionHeader = `${functionHeader}*`; + } + + return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], `${keyText}: ${functionHeader}`); + } + + /* + * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`), + * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is + * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical + * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered, + * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited. + * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them + * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule, + * because converting it into a method would change the value of one of the lexical identifiers. + */ + const lexicalScopeStack = []; + const arrowsWithLexicalIdentifiers = new WeakSet(); + const argumentsIdentifiers = new WeakSet(); + + /** + * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack. + * Also, this marks all `arguments` identifiers so that they can be detected later. + * @param {ASTNode} node The node representing the function. + * @returns {void} + */ + function enterFunction(node) { + lexicalScopeStack.unshift(new Set()); + sourceCode.getScope(node).variables.filter(variable => variable.name === "arguments").forEach(variable => { + variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier)); + }); + } + + /** + * Exits a function. This pops the current set of arrow functions off the lexical scope stack. + * @returns {void} + */ + function exitFunction() { + lexicalScopeStack.shift(); + } + + /** + * Marks the current function as having a lexical keyword. This implies that all arrow functions + * in the current lexical scope contain a reference to this lexical keyword. + * @returns {void} + */ + function reportLexicalIdentifier() { + lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction)); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: enterFunction, + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + "Program:exit": exitFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + + ArrowFunctionExpression(node) { + lexicalScopeStack[0].add(node); + }, + "ArrowFunctionExpression:exit"(node) { + lexicalScopeStack[0].delete(node); + }, + + ThisExpression: reportLexicalIdentifier, + Super: reportLexicalIdentifier, + MetaProperty(node) { + if (node.meta.name === "new" && node.property.name === "target") { + reportLexicalIdentifier(); + } + }, + Identifier(node) { + if (argumentsIdentifiers.has(node)) { + reportLexicalIdentifier(); + } + }, + + ObjectExpression(node) { + if (APPLY_CONSISTENT) { + checkConsistency(node, false); + } else if (APPLY_CONSISTENT_AS_NEEDED) { + checkConsistency(node, true); + } + }, + + "Property:exit"(node) { + const isConciseProperty = node.method || node.shorthand; + + // Ignore destructuring assignment + if (node.parent.type === "ObjectPattern") { + return; + } + + // getters and setters are ignored + if (node.kind === "get" || node.kind === "set") { + return; + } + + // only computed methods can fail the following checks + if (node.computed && node.value.type !== "FunctionExpression" && node.value.type !== "ArrowFunctionExpression") { + return; + } + + //-------------------------------------------------------------- + // Checks for property/method shorthand. + if (isConciseProperty) { + if (node.method && (APPLY_NEVER || AVOID_QUOTES && isStringLiteral(node.key))) { + const messageId = APPLY_NEVER ? "expectedMethodLongform" : "expectedLiteralMethodLongform"; + + // { x() {} } should be written as { x: function() {} } + context.report({ + node, + messageId, + fix: fixer => makeFunctionLongform(fixer, node) + }); + } else if (APPLY_NEVER) { + + // { x } should be written as { x: x } + context.report({ + node, + messageId: "expectedPropertyLongform", + fix: fixer => fixer.insertTextAfter(node.key, `: ${node.key.name}`) + }); + } + } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) { + if (IGNORE_CONSTRUCTORS && node.key.type === "Identifier" && isConstructor(node.key.name)) { + return; + } + + if (METHODS_IGNORE_PATTERN) { + const propertyName = astUtils.getStaticPropertyName(node); + + if (propertyName !== null && METHODS_IGNORE_PATTERN.test(propertyName)) { + return; + } + } + + if (AVOID_QUOTES && isStringLiteral(node.key)) { + return; + } + + // {[x]: function(){}} should be written as {[x]() {}} + if (node.value.type === "FunctionExpression" || + node.value.type === "ArrowFunctionExpression" && + node.value.body.type === "BlockStatement" && + AVOID_EXPLICIT_RETURN_ARROWS && + !arrowsWithLexicalIdentifiers.has(node.value) + ) { + context.report({ + node, + messageId: "expectedMethodShorthand", + fix: fixer => makeFunctionShorthand(fixer, node) + }); + } + } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) { + + // {x: x} should be written as {x} + context.report({ + node, + messageId: "expectedPropertyShorthand", + fix(fixer) { + return fixer.replaceText(node, node.value.name); + } + }); + } else if (node.value.type === "Identifier" && node.key.type === "Literal" && node.key.value === node.value.name && APPLY_TO_PROPS) { + if (AVOID_QUOTES) { + return; + } + + // {"x": x} should be written as {x} + context.report({ + node, + messageId: "expectedPropertyShorthand", + fix(fixer) { + return fixer.replaceText(node, node.value.name); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/one-var-declaration-per-line.js b/node_modules/eslint/lib/rules/one-var-declaration-per-line.js new file mode 100644 index 0000000..b1e045b --- /dev/null +++ b/node_modules/eslint/lib/rules/one-var-declaration-per-line.js @@ -0,0 +1,92 @@ +/** + * @fileoverview Rule to check multiple var declarations per line + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require or disallow newlines around variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/one-var-declaration-per-line" + }, + + schema: [ + { + enum: ["always", "initializations"] + } + ], + + fixable: "whitespace", + + messages: { + expectVarOnNewline: "Expected variable declaration to be on a new line." + } + }, + + create(context) { + + const always = context.options[0] === "always"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + + /** + * Determine if provided keyword is a variant of for specifiers + * @private + * @param {string} keyword keyword to test + * @returns {boolean} True if `keyword` is a variant of for specifier + */ + function isForTypeSpecifier(keyword) { + return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement"; + } + + /** + * Checks newlines around variable declarations. + * @private + * @param {ASTNode} node `VariableDeclaration` node to test + * @returns {void} + */ + function checkForNewLine(node) { + if (isForTypeSpecifier(node.parent.type)) { + return; + } + + const declarations = node.declarations; + let prev; + + declarations.forEach(current => { + if (prev && prev.loc.end.line === current.loc.start.line) { + if (always || prev.init || current.init) { + context.report({ + node, + messageId: "expectVarOnNewline", + loc: current.loc, + fix: fixer => fixer.insertTextBefore(current, "\n") + }); + } + } + prev = current; + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForNewLine + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/one-var.js b/node_modules/eslint/lib/rules/one-var.js new file mode 100644 index 0000000..abb1525 --- /dev/null +++ b/node_modules/eslint/lib/rules/one-var.js @@ -0,0 +1,567 @@ +/** + * @fileoverview A rule to control the use of single variable declarations. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is in a statement list. + * @param {ASTNode} node node to check + * @returns {boolean} `true` if the given node is in a statement list + */ +function isInStatementList(node) { + return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce variables to be declared either together or separately in functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/one-var" + }, + + fixable: "code", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never", "consecutive"] + }, + { + type: "object", + properties: { + separateRequires: { + type: "boolean" + }, + var: { + enum: ["always", "never", "consecutive"] + }, + let: { + enum: ["always", "never", "consecutive"] + }, + const: { + enum: ["always", "never", "consecutive"] + } + }, + additionalProperties: false + }, + { + type: "object", + properties: { + initialized: { + enum: ["always", "never", "consecutive"] + }, + uninitialized: { + enum: ["always", "never", "consecutive"] + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + combineUninitialized: "Combine this with the previous '{{type}}' statement with uninitialized variables.", + combineInitialized: "Combine this with the previous '{{type}}' statement with initialized variables.", + splitUninitialized: "Split uninitialized '{{type}}' declarations into multiple statements.", + splitInitialized: "Split initialized '{{type}}' declarations into multiple statements.", + splitRequires: "Split requires to be separated into a single block.", + combine: "Combine this with the previous '{{type}}' statement.", + split: "Split '{{type}}' declarations into multiple statements." + } + }, + + create(context) { + const MODE_ALWAYS = "always"; + const MODE_NEVER = "never"; + const MODE_CONSECUTIVE = "consecutive"; + const mode = context.options[0] || MODE_ALWAYS; + + const options = {}; + + if (typeof mode === "string") { // simple options configuration with just a string + options.var = { uninitialized: mode, initialized: mode }; + options.let = { uninitialized: mode, initialized: mode }; + options.const = { uninitialized: mode, initialized: mode }; + } else if (typeof mode === "object") { // options configuration is an object + options.separateRequires = !!mode.separateRequires; + options.var = { uninitialized: mode.var, initialized: mode.var }; + options.let = { uninitialized: mode.let, initialized: mode.let }; + options.const = { uninitialized: mode.const, initialized: mode.const }; + if (Object.prototype.hasOwnProperty.call(mode, "uninitialized")) { + options.var.uninitialized = mode.uninitialized; + options.let.uninitialized = mode.uninitialized; + options.const.uninitialized = mode.uninitialized; + } + if (Object.prototype.hasOwnProperty.call(mode, "initialized")) { + options.var.initialized = mode.initialized; + options.let.initialized = mode.initialized; + options.const.initialized = mode.initialized; + } + } + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = []; + const blockStack = []; + + /** + * Increments the blockStack counter. + * @returns {void} + * @private + */ + function startBlock() { + blockStack.push({ + let: { initialized: false, uninitialized: false }, + const: { initialized: false, uninitialized: false } + }); + } + + /** + * Increments the functionStack counter. + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push({ initialized: false, uninitialized: false }); + startBlock(); + } + + /** + * Decrements the blockStack counter. + * @returns {void} + * @private + */ + function endBlock() { + blockStack.pop(); + } + + /** + * Decrements the functionStack counter. + * @returns {void} + * @private + */ + function endFunction() { + functionStack.pop(); + endBlock(); + } + + /** + * Check if a variable declaration is a require. + * @param {ASTNode} decl variable declaration Node + * @returns {bool} if decl is a require, return true; else return false. + * @private + */ + function isRequire(decl) { + return decl.init && decl.init.type === "CallExpression" && decl.init.callee.name === "require"; + } + + /** + * Records whether initialized/uninitialized/required variables are defined in current scope. + * @param {string} statementType node.kind, one of: "var", "let", or "const" + * @param {ASTNode[]} declarations List of declarations + * @param {Object} currentScope The scope being investigated + * @returns {void} + * @private + */ + function recordTypes(statementType, declarations, currentScope) { + for (let i = 0; i < declarations.length; i++) { + if (declarations[i].init === null) { + if (options[statementType] && options[statementType].uninitialized === MODE_ALWAYS) { + currentScope.uninitialized = true; + } + } else { + if (options[statementType] && options[statementType].initialized === MODE_ALWAYS) { + if (options.separateRequires && isRequire(declarations[i])) { + currentScope.required = true; + } else { + currentScope.initialized = true; + } + } + } + } + } + + /** + * Determines the current scope (function or block) + * @param {string} statementType node.kind, one of: "var", "let", or "const" + * @returns {Object} The scope associated with statementType + */ + function getCurrentScope(statementType) { + let currentScope; + + if (statementType === "var") { + currentScope = functionStack[functionStack.length - 1]; + } else if (statementType === "let") { + currentScope = blockStack[blockStack.length - 1].let; + } else if (statementType === "const") { + currentScope = blockStack[blockStack.length - 1].const; + } + return currentScope; + } + + /** + * Counts the number of initialized and uninitialized declarations in a list of declarations + * @param {ASTNode[]} declarations List of declarations + * @returns {Object} Counts of 'uninitialized' and 'initialized' declarations + * @private + */ + function countDeclarations(declarations) { + const counts = { uninitialized: 0, initialized: 0 }; + + for (let i = 0; i < declarations.length; i++) { + if (declarations[i].init === null) { + counts.uninitialized++; + } else { + counts.initialized++; + } + } + return counts; + } + + /** + * Determines if there is more than one var statement in the current scope. + * @param {string} statementType node.kind, one of: "var", "let", or "const" + * @param {ASTNode[]} declarations List of declarations + * @returns {boolean} Returns true if it is the first var declaration, false if not. + * @private + */ + function hasOnlyOneStatement(statementType, declarations) { + + const declarationCounts = countDeclarations(declarations); + const currentOptions = options[statementType] || {}; + const currentScope = getCurrentScope(statementType); + const hasRequires = declarations.some(isRequire); + + if (currentOptions.uninitialized === MODE_ALWAYS && currentOptions.initialized === MODE_ALWAYS) { + if (currentScope.uninitialized || currentScope.initialized) { + if (!hasRequires) { + return false; + } + } + } + + if (declarationCounts.uninitialized > 0) { + if (currentOptions.uninitialized === MODE_ALWAYS && currentScope.uninitialized) { + return false; + } + } + if (declarationCounts.initialized > 0) { + if (currentOptions.initialized === MODE_ALWAYS && currentScope.initialized) { + if (!hasRequires) { + return false; + } + } + } + if (currentScope.required && hasRequires) { + return false; + } + recordTypes(statementType, declarations, currentScope); + return true; + } + + /** + * Fixer to join VariableDeclaration's into a single declaration + * @param {VariableDeclarator[]} declarations The `VariableDeclaration` to join + * @returns {Function} The fixer function + */ + function joinDeclarations(declarations) { + const declaration = declarations[0]; + const body = Array.isArray(declaration.parent.parent.body) ? declaration.parent.parent.body : []; + const currentIndex = body.findIndex(node => node.range[0] === declaration.parent.range[0]); + const previousNode = body[currentIndex - 1]; + + return fixer => { + const type = sourceCode.getTokenBefore(declaration); + const prevSemi = sourceCode.getTokenBefore(type); + const res = []; + + if (previousNode && previousNode.kind === sourceCode.getText(type)) { + if (prevSemi.value === ";") { + res.push(fixer.replaceText(prevSemi, ",")); + } else { + res.push(fixer.insertTextAfter(prevSemi, ",")); + } + res.push(fixer.replaceText(type, "")); + } + + return res; + }; + } + + /** + * Fixer to split a VariableDeclaration into individual declarations + * @param {VariableDeclaration} declaration The `VariableDeclaration` to split + * @returns {Function|null} The fixer function + */ + function splitDeclarations(declaration) { + const { parent } = declaration; + + // don't autofix code such as: if (foo) var x, y; + if (!isInStatementList(parent.type === "ExportNamedDeclaration" ? parent : declaration)) { + return null; + } + + return fixer => declaration.declarations.map(declarator => { + const tokenAfterDeclarator = sourceCode.getTokenAfter(declarator); + + if (tokenAfterDeclarator === null) { + return null; + } + + const afterComma = sourceCode.getTokenAfter(tokenAfterDeclarator, { includeComments: true }); + + if (tokenAfterDeclarator.value !== ",") { + return null; + } + + const exportPlacement = declaration.parent.type === "ExportNamedDeclaration" ? "export " : ""; + + /* + * `var x,y` + * tokenAfterDeclarator ^^ afterComma + */ + if (afterComma.range[0] === tokenAfterDeclarator.range[1]) { + return fixer.replaceText(tokenAfterDeclarator, `; ${exportPlacement}${declaration.kind} `); + } + + /* + * `var x, + * tokenAfterDeclarator ^ + * y` + * ^ afterComma + */ + if ( + afterComma.loc.start.line > tokenAfterDeclarator.loc.end.line || + afterComma.type === "Line" || + afterComma.type === "Block" + ) { + let lastComment = afterComma; + + while (lastComment.type === "Line" || lastComment.type === "Block") { + lastComment = sourceCode.getTokenAfter(lastComment, { includeComments: true }); + } + + return fixer.replaceTextRange( + [tokenAfterDeclarator.range[0], lastComment.range[0]], + `;${sourceCode.text.slice(tokenAfterDeclarator.range[1], lastComment.range[0])}${exportPlacement}${declaration.kind} ` + ); + } + + return fixer.replaceText(tokenAfterDeclarator, `; ${exportPlacement}${declaration.kind}`); + }).filter(x => x); + } + + /** + * Checks a given VariableDeclaration node for errors. + * @param {ASTNode} node The VariableDeclaration node to check + * @returns {void} + * @private + */ + function checkVariableDeclaration(node) { + const parent = node.parent; + const type = node.kind; + + if (!options[type]) { + return; + } + + const declarations = node.declarations; + const declarationCounts = countDeclarations(declarations); + const mixedRequires = declarations.some(isRequire) && !declarations.every(isRequire); + + if (options[type].initialized === MODE_ALWAYS) { + if (options.separateRequires && mixedRequires) { + context.report({ + node, + messageId: "splitRequires" + }); + } + } + + // consecutive + const nodeIndex = (parent.body && parent.body.length > 0 && parent.body.indexOf(node)) || 0; + + if (nodeIndex > 0) { + const previousNode = parent.body[nodeIndex - 1]; + const isPreviousNodeDeclaration = previousNode.type === "VariableDeclaration"; + const declarationsWithPrevious = declarations.concat(previousNode.declarations || []); + + if ( + isPreviousNodeDeclaration && + previousNode.kind === type && + !(declarationsWithPrevious.some(isRequire) && !declarationsWithPrevious.every(isRequire)) + ) { + const previousDeclCounts = countDeclarations(previousNode.declarations); + + if (options[type].initialized === MODE_CONSECUTIVE && options[type].uninitialized === MODE_CONSECUTIVE) { + context.report({ + node, + messageId: "combine", + data: { + type + }, + fix: joinDeclarations(declarations) + }); + } else if (options[type].initialized === MODE_CONSECUTIVE && declarationCounts.initialized > 0 && previousDeclCounts.initialized > 0) { + context.report({ + node, + messageId: "combineInitialized", + data: { + type + }, + fix: joinDeclarations(declarations) + }); + } else if (options[type].uninitialized === MODE_CONSECUTIVE && + declarationCounts.uninitialized > 0 && + previousDeclCounts.uninitialized > 0) { + context.report({ + node, + messageId: "combineUninitialized", + data: { + type + }, + fix: joinDeclarations(declarations) + }); + } + } + } + + // always + if (!hasOnlyOneStatement(type, declarations)) { + if (options[type].initialized === MODE_ALWAYS && options[type].uninitialized === MODE_ALWAYS) { + context.report({ + node, + messageId: "combine", + data: { + type + }, + fix: joinDeclarations(declarations) + }); + } else { + if (options[type].initialized === MODE_ALWAYS && declarationCounts.initialized > 0) { + context.report({ + node, + messageId: "combineInitialized", + data: { + type + }, + fix: joinDeclarations(declarations) + }); + } + if (options[type].uninitialized === MODE_ALWAYS && declarationCounts.uninitialized > 0) { + if (node.parent.left === node && (node.parent.type === "ForInStatement" || node.parent.type === "ForOfStatement")) { + return; + } + context.report({ + node, + messageId: "combineUninitialized", + data: { + type + }, + fix: joinDeclarations(declarations) + }); + } + } + } + + // never + if (parent.type !== "ForStatement" || parent.init !== node) { + const totalDeclarations = declarationCounts.uninitialized + declarationCounts.initialized; + + if (totalDeclarations > 1) { + if (options[type].initialized === MODE_NEVER && options[type].uninitialized === MODE_NEVER) { + + // both initialized and uninitialized + context.report({ + node, + messageId: "split", + data: { + type + }, + fix: splitDeclarations(node) + }); + } else if (options[type].initialized === MODE_NEVER && declarationCounts.initialized > 0) { + + // initialized + context.report({ + node, + messageId: "splitInitialized", + data: { + type + }, + fix: splitDeclarations(node) + }); + } else if (options[type].uninitialized === MODE_NEVER && declarationCounts.uninitialized > 0) { + + // uninitialized + context.report({ + node, + messageId: "splitUninitialized", + data: { + type + }, + fix: splitDeclarations(node) + }); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: startFunction, + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, // StaticBlock creates a new scope for `var` variables + + BlockStatement: startBlock, + ForStatement: startBlock, + ForInStatement: startBlock, + ForOfStatement: startBlock, + SwitchStatement: startBlock, + VariableDeclaration: checkVariableDeclaration, + "ForStatement:exit": endBlock, + "ForOfStatement:exit": endBlock, + "ForInStatement:exit": endBlock, + "SwitchStatement:exit": endBlock, + "BlockStatement:exit": endBlock, + + "Program:exit": endFunction, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/operator-assignment.js b/node_modules/eslint/lib/rules/operator-assignment.js new file mode 100644 index 0000000..f71d73b --- /dev/null +++ b/node_modules/eslint/lib/rules/operator-assignment.js @@ -0,0 +1,209 @@ +/** + * @fileoverview Rule to replace assignment expressions with operator assignment + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether an operator is commutative and has an operator assignment + * shorthand form. + * @param {string} operator Operator to check. + * @returns {boolean} True if the operator is commutative and has a + * shorthand form. + */ +function isCommutativeOperatorWithShorthand(operator) { + return ["*", "&", "^", "|"].includes(operator); +} + +/** + * Checks whether an operator is not commutative and has an operator assignment + * shorthand form. + * @param {string} operator Operator to check. + * @returns {boolean} True if the operator is not commutative and has + * a shorthand form. + */ +function isNonCommutativeOperatorWithShorthand(operator) { + return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].includes(operator); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) + * toString calls regardless of whether assignment shorthand is used) + * @param {ASTNode} node The node on the left side of the expression + * @returns {boolean} `true` if the node can be fixed + */ +function canBeFixed(node) { + return ( + node.type === "Identifier" || + ( + node.type === "MemberExpression" && + (node.object.type === "Identifier" || node.object.type === "ThisExpression") && + (!node.computed || node.property.type === "Literal") + ) + ); +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require or disallow assignment operator shorthand where possible", + recommended: false, + url: "https://eslint.org/docs/latest/rules/operator-assignment" + }, + + schema: [ + { + enum: ["always", "never"] + } + ], + + fixable: "code", + messages: { + replaced: "Assignment (=) can be replaced with operator assignment ({{operator}}).", + unexpected: "Unexpected operator assignment ({{operator}}) shorthand." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Returns the operator token of an AssignmentExpression or BinaryExpression + * @param {ASTNode} node An AssignmentExpression or BinaryExpression node + * @returns {Token} The operator token in the node + */ + function getOperatorToken(node) { + return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); + } + + /** + * Ensures that an assignment uses the shorthand form where possible. + * @param {ASTNode} node An AssignmentExpression node. + * @returns {void} + */ + function verify(node) { + if (node.operator !== "=" || node.right.type !== "BinaryExpression") { + return; + } + + const left = node.left; + const expr = node.right; + const operator = expr.operator; + + if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) { + const replacementOperator = `${operator}=`; + + if (astUtils.isSameReference(left, expr.left, true)) { + context.report({ + node, + messageId: "replaced", + data: { operator: replacementOperator }, + fix(fixer) { + if (canBeFixed(left) && canBeFixed(expr.left)) { + const equalsToken = getOperatorToken(node); + const operatorToken = getOperatorToken(expr); + const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]); + const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]); + + // Check for comments that would be removed. + if (sourceCode.commentsExistBetween(equalsToken, operatorToken)) { + return null; + } + + return fixer.replaceText(node, `${leftText}${replacementOperator}${rightText}`); + } + return null; + } + }); + } else if (astUtils.isSameReference(left, expr.right, true) && isCommutativeOperatorWithShorthand(operator)) { + + /* + * This case can't be fixed safely. + * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would + * change the execution order of the valueOf() functions. + */ + context.report({ + node, + messageId: "replaced", + data: { operator: replacementOperator } + }); + } + } + } + + /** + * Warns if an assignment expression uses operator assignment shorthand. + * @param {ASTNode} node An AssignmentExpression node. + * @returns {void} + */ + function prohibit(node) { + if (node.operator !== "=" && !astUtils.isLogicalAssignmentOperator(node.operator)) { + context.report({ + node, + messageId: "unexpected", + data: { operator: node.operator }, + fix(fixer) { + if (canBeFixed(node.left)) { + const firstToken = sourceCode.getFirstToken(node); + const operatorToken = getOperatorToken(node); + const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]); + const newOperator = node.operator.slice(0, -1); + let rightText; + + // Check for comments that would be duplicated. + if (sourceCode.commentsExistBetween(firstToken, operatorToken)) { + return null; + } + + // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side. + if ( + astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) && + !astUtils.isParenthesised(sourceCode, node.right) + ) { + rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; + } else { + const tokenAfterOperator = sourceCode.getTokenAfter(operatorToken, { includeComments: true }); + let rightTextPrefix = ""; + + if ( + operatorToken.range[1] === tokenAfterOperator.range[0] && + !astUtils.canTokensBeAdjacent({ type: "Punctuator", value: newOperator }, tokenAfterOperator) + ) { + rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar + } + + rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`; + } + + return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`); + } + return null; + } + }); + } + } + + return { + AssignmentExpression: context.options[0] !== "never" ? verify : prohibit + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/operator-linebreak.js b/node_modules/eslint/lib/rules/operator-linebreak.js new file mode 100644 index 0000000..2b609f6 --- /dev/null +++ b/node_modules/eslint/lib/rules/operator-linebreak.js @@ -0,0 +1,250 @@ +/** + * @fileoverview Operator linebreak - enforces operator linebreak style of two types: after and before + * @author Benoît Zugmeyer + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent linebreak style for operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/operator-linebreak" + }, + + schema: [ + { + enum: ["after", "before", "none", null] + }, + { + type: "object", + properties: { + overrides: { + type: "object", + additionalProperties: { + enum: ["after", "before", "none", "ignore"] + } + } + }, + additionalProperties: false + } + ], + + fixable: "code", + + messages: { + operatorAtBeginning: "'{{operator}}' should be placed at the beginning of the line.", + operatorAtEnd: "'{{operator}}' should be placed at the end of the line.", + badLinebreak: "Bad line breaking before and after '{{operator}}'.", + noLinebreak: "There should be no line break before or after '{{operator}}'." + } + }, + + create(context) { + + const usedDefaultGlobal = !context.options[0]; + const globalStyle = context.options[0] || "after"; + const options = context.options[1] || {}; + const styleOverrides = options.overrides ? Object.assign({}, options.overrides) : {}; + + if (usedDefaultGlobal && !styleOverrides["?"]) { + styleOverrides["?"] = "before"; + } + + if (usedDefaultGlobal && !styleOverrides[":"]) { + styleOverrides[":"] = "before"; + } + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Gets a fixer function to fix rule issues + * @param {Token} operatorToken The operator token of an expression + * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none' + * @returns {Function} A fixer function + */ + function getFixer(operatorToken, desiredStyle) { + return fixer => { + const tokenBefore = sourceCode.getTokenBefore(operatorToken); + const tokenAfter = sourceCode.getTokenAfter(operatorToken); + const textBefore = sourceCode.text.slice(tokenBefore.range[1], operatorToken.range[0]); + const textAfter = sourceCode.text.slice(operatorToken.range[1], tokenAfter.range[0]); + const hasLinebreakBefore = !astUtils.isTokenOnSameLine(tokenBefore, operatorToken); + const hasLinebreakAfter = !astUtils.isTokenOnSameLine(operatorToken, tokenAfter); + let newTextBefore, newTextAfter; + + if (hasLinebreakBefore !== hasLinebreakAfter && desiredStyle !== "none") { + + // If there is a comment before and after the operator, don't do a fix. + if (sourceCode.getTokenBefore(operatorToken, { includeComments: true }) !== tokenBefore && + sourceCode.getTokenAfter(operatorToken, { includeComments: true }) !== tokenAfter) { + + return null; + } + + /* + * If there is only one linebreak and it's on the wrong side of the operator, swap the text before and after the operator. + * foo && + * bar + * would get fixed to + * foo + * && bar + */ + newTextBefore = textAfter; + newTextAfter = textBefore; + } else { + const LINEBREAK_REGEX = astUtils.createGlobalLinebreakMatcher(); + + // Otherwise, if no linebreak is desired and no comments interfere, replace the linebreaks with empty strings. + newTextBefore = desiredStyle === "before" || textBefore.trim() ? textBefore : textBefore.replace(LINEBREAK_REGEX, ""); + newTextAfter = desiredStyle === "after" || textAfter.trim() ? textAfter : textAfter.replace(LINEBREAK_REGEX, ""); + + // If there was no change (due to interfering comments), don't output a fix. + if (newTextBefore === textBefore && newTextAfter === textAfter) { + return null; + } + } + + if (newTextAfter === "" && tokenAfter.type === "Punctuator" && "+-".includes(operatorToken.value) && tokenAfter.value === operatorToken.value) { + + // To avoid accidentally creating a ++ or -- operator, insert a space if the operator is a +/- and the following token is a unary +/-. + newTextAfter += " "; + } + + return fixer.replaceTextRange([tokenBefore.range[1], tokenAfter.range[0]], newTextBefore + operatorToken.value + newTextAfter); + }; + } + + /** + * Checks the operator placement + * @param {ASTNode} node The node to check + * @param {ASTNode} rightSide The node that comes after the operator in `node` + * @param {string} operator The operator + * @private + * @returns {void} + */ + function validateNode(node, rightSide, operator) { + + /* + * Find the operator token by searching from the right side, because between the left side and the operator + * there could be additional tokens from type annotations. Search specifically for the token which + * value equals the operator, in order to skip possible opening parentheses before the right side node. + */ + const operatorToken = sourceCode.getTokenBefore(rightSide, token => token.value === operator); + const leftToken = sourceCode.getTokenBefore(operatorToken); + const rightToken = sourceCode.getTokenAfter(operatorToken); + const operatorStyleOverride = styleOverrides[operator]; + const style = operatorStyleOverride || globalStyle; + const fix = getFixer(operatorToken, style); + + // if single line + if (astUtils.isTokenOnSameLine(leftToken, operatorToken) && + astUtils.isTokenOnSameLine(operatorToken, rightToken)) { + + // do nothing. + + } else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) && + !astUtils.isTokenOnSameLine(operatorToken, rightToken)) { + + // lone operator + context.report({ + node, + loc: operatorToken.loc, + messageId: "badLinebreak", + data: { + operator + }, + fix + }); + + } else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) { + + context.report({ + node, + loc: operatorToken.loc, + messageId: "operatorAtBeginning", + data: { + operator + }, + fix + }); + + } else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) { + + context.report({ + node, + loc: operatorToken.loc, + messageId: "operatorAtEnd", + data: { + operator + }, + fix + }); + + } else if (style === "none") { + + context.report({ + node, + loc: operatorToken.loc, + messageId: "noLinebreak", + data: { + operator + }, + fix + }); + + } + } + + /** + * Validates a binary expression using `validateNode` + * @param {BinaryExpression|LogicalExpression|AssignmentExpression} node node to be validated + * @returns {void} + */ + function validateBinaryExpression(node) { + validateNode(node, node.right, node.operator); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + BinaryExpression: validateBinaryExpression, + LogicalExpression: validateBinaryExpression, + AssignmentExpression: validateBinaryExpression, + VariableDeclarator(node) { + if (node.init) { + validateNode(node, node.init, "="); + } + }, + PropertyDefinition(node) { + if (node.value) { + validateNode(node, node.value, "="); + } + }, + ConditionalExpression(node) { + validateNode(node, node.consequent, "?"); + validateNode(node, node.alternate, ":"); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/padded-blocks.js b/node_modules/eslint/lib/rules/padded-blocks.js new file mode 100644 index 0000000..c6d1372 --- /dev/null +++ b/node_modules/eslint/lib/rules/padded-blocks.js @@ -0,0 +1,307 @@ +/** + * @fileoverview A rule to ensure blank lines within blocks. + * @author Mathias Schreck + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow padding within blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/padded-blocks" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + blocks: { + enum: ["always", "never"] + }, + switches: { + enum: ["always", "never"] + }, + classes: { + enum: ["always", "never"] + } + }, + additionalProperties: false, + minProperties: 1 + } + ] + }, + { + type: "object", + properties: { + allowSingleLineBlocks: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + + messages: { + alwaysPadBlock: "Block must be padded by blank lines.", + neverPadBlock: "Block must not be padded by blank lines." + } + }, + + create(context) { + const options = {}; + const typeOptions = context.options[0] || "always"; + const exceptOptions = context.options[1] || {}; + + if (typeof typeOptions === "string") { + const shouldHavePadding = typeOptions === "always"; + + options.blocks = shouldHavePadding; + options.switches = shouldHavePadding; + options.classes = shouldHavePadding; + } else { + if (Object.prototype.hasOwnProperty.call(typeOptions, "blocks")) { + options.blocks = typeOptions.blocks === "always"; + } + if (Object.prototype.hasOwnProperty.call(typeOptions, "switches")) { + options.switches = typeOptions.switches === "always"; + } + if (Object.prototype.hasOwnProperty.call(typeOptions, "classes")) { + options.classes = typeOptions.classes === "always"; + } + } + + if (Object.prototype.hasOwnProperty.call(exceptOptions, "allowSingleLineBlocks")) { + options.allowSingleLineBlocks = exceptOptions.allowSingleLineBlocks === true; + } + + const sourceCode = context.sourceCode; + + /** + * Gets the open brace token from a given node. + * @param {ASTNode} node A BlockStatement or SwitchStatement node from which to get the open brace. + * @returns {Token} The token of the open brace. + */ + function getOpenBrace(node) { + if (node.type === "SwitchStatement") { + return sourceCode.getTokenBefore(node.cases[0]); + } + + if (node.type === "StaticBlock") { + return sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token + } + + // `BlockStatement` or `ClassBody` + return sourceCode.getFirstToken(node); + } + + /** + * Checks if the given parameter is a comment node + * @param {ASTNode|Token} node An AST node or token + * @returns {boolean} True if node is a comment + */ + function isComment(node) { + return node.type === "Line" || node.type === "Block"; + } + + /** + * Checks if there is padding between two tokens + * @param {Token} first The first token + * @param {Token} second The second token + * @returns {boolean} True if there is at least a line between the tokens + */ + function isPaddingBetweenTokens(first, second) { + return second.loc.start.line - first.loc.end.line >= 2; + } + + + /** + * Checks if the given token has a blank line after it. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is followed by a blank line. + */ + function getFirstBlockToken(token) { + let prev, + first = token; + + do { + prev = first; + first = sourceCode.getTokenAfter(first, { includeComments: true }); + } while (isComment(first) && first.loc.start.line === prev.loc.end.line); + + return first; + } + + /** + * Checks if the given token is preceded by a blank line. + * @param {Token} token The token to check + * @returns {boolean} Whether or not the token is preceded by a blank line + */ + function getLastBlockToken(token) { + let last = token, + next; + + do { + next = last; + last = sourceCode.getTokenBefore(last, { includeComments: true }); + } while (isComment(last) && last.loc.end.line === next.loc.start.line); + + return last; + } + + /** + * Checks if a node should be padded, according to the rule config. + * @param {ASTNode} node The AST node to check. + * @throws {Error} (Unreachable) + * @returns {boolean} True if the node should be padded, false otherwise. + */ + function requirePaddingFor(node) { + switch (node.type) { + case "BlockStatement": + case "StaticBlock": + return options.blocks; + case "SwitchStatement": + return options.switches; + case "ClassBody": + return options.classes; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + } + + /** + * Checks the given BlockStatement node to be padded if the block is not empty. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPadding(node) { + const openBrace = getOpenBrace(node), + firstBlockToken = getFirstBlockToken(openBrace), + tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true }), + closeBrace = sourceCode.getLastToken(node), + lastBlockToken = getLastBlockToken(closeBrace), + tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true }), + blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken), + blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast); + + if (options.allowSingleLineBlocks && astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast)) { + return; + } + + if (requirePaddingFor(node)) { + + if (!blockHasTopPadding) { + context.report({ + node, + loc: { + start: tokenBeforeFirst.loc.start, + end: firstBlockToken.loc.start + }, + fix(fixer) { + return fixer.insertTextAfter(tokenBeforeFirst, "\n"); + }, + messageId: "alwaysPadBlock" + }); + } + if (!blockHasBottomPadding) { + context.report({ + node, + loc: { + end: tokenAfterLast.loc.start, + start: lastBlockToken.loc.end + }, + fix(fixer) { + return fixer.insertTextBefore(tokenAfterLast, "\n"); + }, + messageId: "alwaysPadBlock" + }); + } + } else { + if (blockHasTopPadding) { + + context.report({ + node, + loc: { + start: tokenBeforeFirst.loc.start, + end: firstBlockToken.loc.start + }, + fix(fixer) { + return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], "\n"); + }, + messageId: "neverPadBlock" + }); + } + + if (blockHasBottomPadding) { + + context.report({ + node, + loc: { + end: tokenAfterLast.loc.start, + start: lastBlockToken.loc.end + }, + messageId: "neverPadBlock", + fix(fixer) { + return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], "\n"); + } + }); + } + } + } + + const rule = {}; + + if (Object.prototype.hasOwnProperty.call(options, "switches")) { + rule.SwitchStatement = function(node) { + if (node.cases.length === 0) { + return; + } + checkPadding(node); + }; + } + + if (Object.prototype.hasOwnProperty.call(options, "blocks")) { + rule.BlockStatement = function(node) { + if (node.body.length === 0) { + return; + } + checkPadding(node); + }; + rule.StaticBlock = rule.BlockStatement; + } + + if (Object.prototype.hasOwnProperty.call(options, "classes")) { + rule.ClassBody = function(node) { + if (node.body.length === 0) { + return; + } + checkPadding(node); + }; + } + + return rule; + } +}; diff --git a/node_modules/eslint/lib/rules/padding-line-between-statements.js b/node_modules/eslint/lib/rules/padding-line-between-statements.js new file mode 100644 index 0000000..95e0873 --- /dev/null +++ b/node_modules/eslint/lib/rules/padding-line-between-statements.js @@ -0,0 +1,587 @@ +/** + * @fileoverview Rule to require or disallow newlines between statements + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const LT = `[${Array.from(astUtils.LINEBREAKS).join("")}]`; +const PADDING_LINE_SEQUENCE = new RegExp( + String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$`, + "u" +); +const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/u; +const CJS_IMPORT = /^require\(/u; + +/** + * Creates tester which check if a node starts with specific keyword. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newKeywordTester(keyword) { + return { + test: (node, sourceCode) => + sourceCode.getFirstToken(node).value === keyword + }; +} + +/** + * Creates tester which check if a node starts with specific keyword and spans a single line. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newSinglelineKeywordTester(keyword) { + return { + test: (node, sourceCode) => + node.loc.start.line === node.loc.end.line && + sourceCode.getFirstToken(node).value === keyword + }; +} + +/** + * Creates tester which check if a node starts with specific keyword and spans multiple lines. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newMultilineKeywordTester(keyword) { + return { + test: (node, sourceCode) => + node.loc.start.line !== node.loc.end.line && + sourceCode.getFirstToken(node).value === keyword + }; +} + +/** + * Creates tester which check if a node is specific type. + * @param {string} type The node type to test. + * @returns {Object} the created tester. + * @private + */ +function newNodeTypeTester(type) { + return { + test: node => + node.type === type + }; +} + +/** + * Checks the given node is an expression statement of IIFE. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is an expression statement of IIFE. + * @private + */ +function isIIFEStatement(node) { + if (node.type === "ExpressionStatement") { + let call = astUtils.skipChainExpression(node.expression); + + if (call.type === "UnaryExpression") { + call = astUtils.skipChainExpression(call.argument); + } + return call.type === "CallExpression" && astUtils.isFunction(call.callee); + } + return false; +} + +/** + * Checks whether the given node is a block-like statement. + * This checks the last token of the node is the closing brace of a block. + * @param {SourceCode} sourceCode The source code to get tokens. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a block-like statement. + * @private + */ +function isBlockLikeStatement(sourceCode, node) { + + // do-while with a block is a block-like statement. + if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") { + return true; + } + + /* + * IIFE is a block-like statement specially from + * JSCS#disallowPaddingNewLinesAfterBlocks. + */ + if (isIIFEStatement(node)) { + return true; + } + + // Checks the last token is a closing brace of blocks. + const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); + const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken) + ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) + : null; + + return Boolean(belongingNode) && ( + belongingNode.type === "BlockStatement" || + belongingNode.type === "SwitchStatement" + ); +} + +/** + * Gets the actual last token. + * + * If a semicolon is semicolon-less style's semicolon, this ignores it. + * For example: + * + * foo() + * ;[1, 2, 3].forEach(bar) + * @param {SourceCode} sourceCode The source code to get tokens. + * @param {ASTNode} node The node to get. + * @returns {Token} The actual last token. + * @private + */ +function getActualLastToken(sourceCode, node) { + const semiToken = sourceCode.getLastToken(node); + const prevToken = sourceCode.getTokenBefore(semiToken); + const nextToken = sourceCode.getTokenAfter(semiToken); + const isSemicolonLessStyle = Boolean( + prevToken && + nextToken && + prevToken.range[0] >= node.range[0] && + astUtils.isSemicolonToken(semiToken) && + semiToken.loc.start.line !== prevToken.loc.end.line && + semiToken.loc.end.line === nextToken.loc.start.line + ); + + return isSemicolonLessStyle ? prevToken : semiToken; +} + +/** + * This returns the concatenation of the first 2 captured strings. + * @param {string} _ Unused. Whole matched string. + * @param {string} trailingSpaces The trailing spaces of the first line. + * @param {string} indentSpaces The indentation spaces of the last line. + * @returns {string} The concatenation of trailingSpaces and indentSpaces. + * @private + */ +function replacerToRemovePaddingLines(_, trailingSpaces, indentSpaces) { + return trailingSpaces + indentSpaces; +} + +/** + * Check and report statements for `any` configuration. + * It does nothing. + * @returns {void} + * @private + */ +function verifyForAny() { +} + +/** + * Check and report statements for `never` configuration. + * This autofix removes blank lines between the given 2 statements. + * However, if comments exist between 2 blank lines, it does not remove those + * blank lines automatically. + * @param {RuleContext} context The rule context to report. + * @param {ASTNode} _ Unused. The previous node to check. + * @param {ASTNode} nextNode The next node to check. + * @param {Array} paddingLines The array of token pairs that blank + * lines exist between the pair. + * @returns {void} + * @private + */ +function verifyForNever(context, _, nextNode, paddingLines) { + if (paddingLines.length === 0) { + return; + } + + context.report({ + node: nextNode, + messageId: "unexpectedBlankLine", + fix(fixer) { + if (paddingLines.length >= 2) { + return null; + } + + const prevToken = paddingLines[0][0]; + const nextToken = paddingLines[0][1]; + const start = prevToken.range[1]; + const end = nextToken.range[0]; + const text = context.sourceCode.text + .slice(start, end) + .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines); + + return fixer.replaceTextRange([start, end], text); + } + }); +} + +/** + * Check and report statements for `always` configuration. + * This autofix inserts a blank line between the given 2 statements. + * If the `prevNode` has trailing comments, it inserts a blank line after the + * trailing comments. + * @param {RuleContext} context The rule context to report. + * @param {ASTNode} prevNode The previous node to check. + * @param {ASTNode} nextNode The next node to check. + * @param {Array} paddingLines The array of token pairs that blank + * lines exist between the pair. + * @returns {void} + * @private + */ +function verifyForAlways(context, prevNode, nextNode, paddingLines) { + if (paddingLines.length > 0) { + return; + } + + context.report({ + node: nextNode, + messageId: "expectedBlankLine", + fix(fixer) { + const sourceCode = context.sourceCode; + let prevToken = getActualLastToken(sourceCode, prevNode); + const nextToken = sourceCode.getFirstTokenBetween( + prevToken, + nextNode, + { + includeComments: true, + + /** + * Skip the trailing comments of the previous node. + * This inserts a blank line after the last trailing comment. + * + * For example: + * + * foo(); // trailing comment. + * // comment. + * bar(); + * + * Get fixed to: + * + * foo(); // trailing comment. + * + * // comment. + * bar(); + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is not a trailing comment. + * @private + */ + filter(token) { + if (astUtils.isTokenOnSameLine(prevToken, token)) { + prevToken = token; + return false; + } + return true; + } + } + ) || nextNode; + const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken) + ? "\n\n" + : "\n"; + + return fixer.insertTextAfter(prevToken, insertText); + } + }); +} + +/** + * Types of blank lines. + * `any`, `never`, and `always` are defined. + * Those have `verify` method to check and report statements. + * @private + */ +const PaddingTypes = { + any: { verify: verifyForAny }, + never: { verify: verifyForNever }, + always: { verify: verifyForAlways } +}; + +/** + * Types of statements. + * Those have `test` method to check it matches to the given statement. + * @private + */ +const StatementTypes = { + "*": { test: () => true }, + "block-like": { + test: (node, sourceCode) => isBlockLikeStatement(sourceCode, node) + }, + "cjs-export": { + test: (node, sourceCode) => + node.type === "ExpressionStatement" && + node.expression.type === "AssignmentExpression" && + CJS_EXPORT.test(sourceCode.getText(node.expression.left)) + }, + "cjs-import": { + test: (node, sourceCode) => + node.type === "VariableDeclaration" && + node.declarations.length > 0 && + Boolean(node.declarations[0].init) && + CJS_IMPORT.test(sourceCode.getText(node.declarations[0].init)) + }, + directive: { + test: astUtils.isDirective + }, + expression: { + test: node => node.type === "ExpressionStatement" && !astUtils.isDirective(node) + }, + iife: { + test: isIIFEStatement + }, + "multiline-block-like": { + test: (node, sourceCode) => + node.loc.start.line !== node.loc.end.line && + isBlockLikeStatement(sourceCode, node) + }, + "multiline-expression": { + test: node => + node.loc.start.line !== node.loc.end.line && + node.type === "ExpressionStatement" && + !astUtils.isDirective(node) + }, + + "multiline-const": newMultilineKeywordTester("const"), + "multiline-let": newMultilineKeywordTester("let"), + "multiline-var": newMultilineKeywordTester("var"), + "singleline-const": newSinglelineKeywordTester("const"), + "singleline-let": newSinglelineKeywordTester("let"), + "singleline-var": newSinglelineKeywordTester("var"), + + block: newNodeTypeTester("BlockStatement"), + empty: newNodeTypeTester("EmptyStatement"), + function: newNodeTypeTester("FunctionDeclaration"), + + break: newKeywordTester("break"), + case: newKeywordTester("case"), + class: newKeywordTester("class"), + const: newKeywordTester("const"), + continue: newKeywordTester("continue"), + debugger: newKeywordTester("debugger"), + default: newKeywordTester("default"), + do: newKeywordTester("do"), + export: newKeywordTester("export"), + for: newKeywordTester("for"), + if: newKeywordTester("if"), + import: newKeywordTester("import"), + let: newKeywordTester("let"), + return: newKeywordTester("return"), + switch: newKeywordTester("switch"), + throw: newKeywordTester("throw"), + try: newKeywordTester("try"), + var: newKeywordTester("var"), + while: newKeywordTester("while"), + with: newKeywordTester("with") +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow padding lines between statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/padding-line-between-statements" + }, + + fixable: "whitespace", + + schema: { + definitions: { + paddingType: { + enum: Object.keys(PaddingTypes) + }, + statementType: { + anyOf: [ + { enum: Object.keys(StatementTypes) }, + { + type: "array", + items: { enum: Object.keys(StatementTypes) }, + minItems: 1, + uniqueItems: true + } + ] + } + }, + type: "array", + items: { + type: "object", + properties: { + blankLine: { $ref: "#/definitions/paddingType" }, + prev: { $ref: "#/definitions/statementType" }, + next: { $ref: "#/definitions/statementType" } + }, + additionalProperties: false, + required: ["blankLine", "prev", "next"] + } + }, + + messages: { + unexpectedBlankLine: "Unexpected blank line before this statement.", + expectedBlankLine: "Expected blank line before this statement." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const configureList = context.options || []; + let scopeInfo = null; + + /** + * Processes to enter to new scope. + * This manages the current previous statement. + * @returns {void} + * @private + */ + function enterScope() { + scopeInfo = { + upper: scopeInfo, + prevNode: null + }; + } + + /** + * Processes to exit from the current scope. + * @returns {void} + * @private + */ + function exitScope() { + scopeInfo = scopeInfo.upper; + } + + /** + * Checks whether the given node matches the given type. + * @param {ASTNode} node The statement node to check. + * @param {string|string[]} type The statement type to check. + * @returns {boolean} `true` if the statement node matched the type. + * @private + */ + function match(node, type) { + let innerStatementNode = node; + + while (innerStatementNode.type === "LabeledStatement") { + innerStatementNode = innerStatementNode.body; + } + if (Array.isArray(type)) { + return type.some(match.bind(null, innerStatementNode)); + } + return StatementTypes[type].test(innerStatementNode, sourceCode); + } + + /** + * Finds the last matched configure from configureList. + * @param {ASTNode} prevNode The previous statement to match. + * @param {ASTNode} nextNode The current statement to match. + * @returns {Object} The tester of the last matched configure. + * @private + */ + function getPaddingType(prevNode, nextNode) { + for (let i = configureList.length - 1; i >= 0; --i) { + const configure = configureList[i]; + const matched = + match(prevNode, configure.prev) && + match(nextNode, configure.next); + + if (matched) { + return PaddingTypes[configure.blankLine]; + } + } + return PaddingTypes.any; + } + + /** + * Gets padding line sequences between the given 2 statements. + * Comments are separators of the padding line sequences. + * @param {ASTNode} prevNode The previous statement to count. + * @param {ASTNode} nextNode The current statement to count. + * @returns {Array} The array of token pairs. + * @private + */ + function getPaddingLineSequences(prevNode, nextNode) { + const pairs = []; + let prevToken = getActualLastToken(sourceCode, prevNode); + + if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) { + do { + const token = sourceCode.getTokenAfter( + prevToken, + { includeComments: true } + ); + + if (token.loc.start.line - prevToken.loc.end.line >= 2) { + pairs.push([prevToken, token]); + } + prevToken = token; + + } while (prevToken.range[0] < nextNode.range[0]); + } + + return pairs; + } + + /** + * Verify padding lines between the given node and the previous node. + * @param {ASTNode} node The node to verify. + * @returns {void} + * @private + */ + function verify(node) { + const parentType = node.parent.type; + const validParent = + astUtils.STATEMENT_LIST_PARENTS.has(parentType) || + parentType === "SwitchStatement"; + + if (!validParent) { + return; + } + + // Save this node as the current previous statement. + const prevNode = scopeInfo.prevNode; + + // Verify. + if (prevNode) { + const type = getPaddingType(prevNode, node); + const paddingLines = getPaddingLineSequences(prevNode, node); + + type.verify(context, prevNode, node, paddingLines); + } + + scopeInfo.prevNode = node; + } + + /** + * Verify padding lines between the given node and the previous node. + * Then process to enter to new scope. + * @param {ASTNode} node The node to verify. + * @returns {void} + * @private + */ + function verifyThenEnterScope(node) { + verify(node); + enterScope(); + } + + return { + Program: enterScope, + BlockStatement: enterScope, + SwitchStatement: enterScope, + StaticBlock: enterScope, + "Program:exit": exitScope, + "BlockStatement:exit": exitScope, + "SwitchStatement:exit": exitScope, + "StaticBlock:exit": exitScope, + + ":statement": verify, + + SwitchCase: verifyThenEnterScope, + "SwitchCase:exit": exitScope + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-arrow-callback.js b/node_modules/eslint/lib/rules/prefer-arrow-callback.js new file mode 100644 index 0000000..d22e508 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-arrow-callback.js @@ -0,0 +1,381 @@ +/** + * @fileoverview A rule to suggest using arrow functions as callbacks. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given variable is a function name. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is a function name. + */ +function isFunctionName(variable) { + return variable && variable.defs[0].type === "FunctionName"; +} + +/** + * Checks whether or not a given MetaProperty node equals to a given value. + * @param {ASTNode} node A MetaProperty node to check. + * @param {string} metaName The name of `MetaProperty.meta`. + * @param {string} propertyName The name of `MetaProperty.property`. + * @returns {boolean} `true` if the node is the specific value. + */ +function checkMetaProperty(node, metaName, propertyName) { + return node.meta.name === metaName && node.property.name === propertyName; +} + +/** + * Gets the variable object of `arguments` which is defined implicitly. + * @param {eslint-scope.Scope} scope A scope to get. + * @returns {eslint-scope.Variable} The found variable object. + */ +function getVariableOfArguments(scope) { + const variables = scope.variables; + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + if (variable.name === "arguments") { + + /* + * If there was a parameter which is named "arguments", the + * implicit "arguments" is not defined. + * So does fast return with null. + */ + return (variable.identifiers.length === 0) ? variable : null; + } + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks whether or not a given node is a callback. + * @param {ASTNode} node A node to check. + * @throws {Error} (Unreachable.) + * @returns {Object} + * {boolean} retv.isCallback - `true` if the node is a callback. + * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`. + */ +function getCallbackInfo(node) { + const retv = { isCallback: false, isLexicalThis: false }; + let currentNode = node; + let parent = node.parent; + let bound = false; + + while (currentNode) { + switch (parent.type) { + + // Checks parents recursively. + + case "LogicalExpression": + case "ChainExpression": + case "ConditionalExpression": + break; + + // Checks whether the parent node is `.bind(this)` call. + case "MemberExpression": + if ( + parent.object === currentNode && + !parent.property.computed && + parent.property.type === "Identifier" && + parent.property.name === "bind" + ) { + const maybeCallee = parent.parent.type === "ChainExpression" + ? parent.parent + : parent; + + if (astUtils.isCallee(maybeCallee)) { + if (!bound) { + bound = true; // Use only the first `.bind()` to make `isLexicalThis` value. + retv.isLexicalThis = ( + maybeCallee.parent.arguments.length === 1 && + maybeCallee.parent.arguments[0].type === "ThisExpression" + ); + } + parent = maybeCallee.parent; + } else { + return retv; + } + } else { + return retv; + } + break; + + // Checks whether the node is a callback. + case "CallExpression": + case "NewExpression": + if (parent.callee !== currentNode) { + retv.isCallback = true; + } + return retv; + + default: + return retv; + } + + currentNode = parent; + parent = parent.parent; + } + + /* c8 ignore next */ + throw new Error("unreachable"); +} + +/** + * Checks whether a simple list of parameters contains any duplicates. This does not handle complex + * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate + * parameter names anyway. Instead, it always returns `false` for complex parameter lists. + * @param {ASTNode[]} paramsList The list of parameters for a function + * @returns {boolean} `true` if the list of parameters contains any duplicates + */ +function hasDuplicateParams(paramsList) { + return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require using arrow functions for callbacks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-arrow-callback" + }, + + schema: [ + { + type: "object", + properties: { + allowNamedFunctions: { + type: "boolean", + default: false + }, + allowUnboundThis: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + fixable: "code", + + messages: { + preferArrowCallback: "Unexpected function expression." + } + }, + + create(context) { + const options = context.options[0] || {}; + + const allowUnboundThis = options.allowUnboundThis !== false; // default to true + const allowNamedFunctions = options.allowNamedFunctions; + const sourceCode = context.sourceCode; + + /* + * {Array<{this: boolean, super: boolean, meta: boolean}>} + * - this - A flag which shows there are one or more ThisExpression. + * - super - A flag which shows there are one or more Super. + * - meta - A flag which shows there are one or more MethProperty. + */ + let stack = []; + + /** + * Pushes new function scope with all `false` flags. + * @returns {void} + */ + function enterScope() { + stack.push({ this: false, super: false, meta: false }); + } + + /** + * Pops a function scope from the stack. + * @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope. + */ + function exitScope() { + return stack.pop(); + } + + return { + + // Reset internal state. + Program() { + stack = []; + }, + + // If there are below, it cannot replace with arrow functions merely. + ThisExpression() { + const info = stack[stack.length - 1]; + + if (info) { + info.this = true; + } + }, + + Super() { + const info = stack[stack.length - 1]; + + if (info) { + info.super = true; + } + }, + + MetaProperty(node) { + const info = stack[stack.length - 1]; + + if (info && checkMetaProperty(node, "new", "target")) { + info.meta = true; + } + }, + + // To skip nested scopes. + FunctionDeclaration: enterScope, + "FunctionDeclaration:exit": exitScope, + + // Main. + FunctionExpression: enterScope, + "FunctionExpression:exit"(node) { + const scopeInfo = exitScope(); + + // Skip named function expressions + if (allowNamedFunctions && node.id && node.id.name) { + return; + } + + // Skip generators. + if (node.generator) { + return; + } + + // Skip recursive functions. + const nameVar = sourceCode.getDeclaredVariables(node)[0]; + + if (isFunctionName(nameVar) && nameVar.references.length > 0) { + return; + } + + // Skip if it's using arguments. + const variable = getVariableOfArguments(sourceCode.getScope(node)); + + if (variable && variable.references.length > 0) { + return; + } + + // Reports if it's a callback which can replace with arrows. + const callbackInfo = getCallbackInfo(node); + + if (callbackInfo.isCallback && + (!allowUnboundThis || !scopeInfo.this || callbackInfo.isLexicalThis) && + !scopeInfo.super && + !scopeInfo.meta + ) { + context.report({ + node, + messageId: "preferArrowCallback", + *fix(fixer) { + if ((!callbackInfo.isLexicalThis && scopeInfo.this) || hasDuplicateParams(node.params)) { + + /* + * If the callback function does not have .bind(this) and contains a reference to `this`, there + * is no way to determine what `this` should be, so don't perform any fixes. + * If the callback function has duplicates in its list of parameters (possible in sloppy mode), + * don't replace it with an arrow function, because this is a SyntaxError with arrow functions. + */ + return; + } + + // Remove `.bind(this)` if exists. + if (callbackInfo.isLexicalThis) { + const memberNode = node.parent; + + /* + * If `.bind(this)` exists but the parent is not `.bind(this)`, don't remove it automatically. + * E.g. `(foo || function(){}).bind(this)` + */ + if (memberNode.type !== "MemberExpression") { + return; + } + + const callNode = memberNode.parent; + const firstTokenToRemove = sourceCode.getTokenAfter(memberNode.object, astUtils.isNotClosingParenToken); + const lastTokenToRemove = sourceCode.getLastToken(callNode); + + /* + * If the member expression is parenthesized, don't remove the right paren. + * E.g. `(function(){}.bind)(this)` + * ^^^^^^^^^^^^ + */ + if (astUtils.isParenthesised(sourceCode, memberNode)) { + return; + } + + // If comments exist in the `.bind(this)`, don't remove those. + if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) { + return; + } + + yield fixer.removeRange([firstTokenToRemove.range[0], lastTokenToRemove.range[1]]); + } + + // Convert the function expression to an arrow function. + const functionToken = sourceCode.getFirstToken(node, node.async ? 1 : 0); + const leftParenToken = sourceCode.getTokenAfter(functionToken, astUtils.isOpeningParenToken); + const tokenBeforeBody = sourceCode.getTokenBefore(node.body); + + if (sourceCode.commentsExistBetween(functionToken, leftParenToken)) { + + // Remove only extra tokens to keep comments. + yield fixer.remove(functionToken); + if (node.id) { + yield fixer.remove(node.id); + } + } else { + + // Remove extra tokens and spaces. + yield fixer.removeRange([functionToken.range[0], leftParenToken.range[0]]); + } + yield fixer.insertTextAfter(tokenBeforeBody, " =>"); + + // Get the node that will become the new arrow function. + let replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node; + + if (replacedNode.type === "ChainExpression") { + replacedNode = replacedNode.parent; + } + + /* + * If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then + * the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even + * though `foo || function() {}` is valid. + */ + if ( + replacedNode.parent.type !== "CallExpression" && + replacedNode.parent.type !== "ConditionalExpression" && + !astUtils.isParenthesised(sourceCode, replacedNode) && + !astUtils.isParenthesised(sourceCode, node) + ) { + yield fixer.insertTextBefore(replacedNode, "("); + yield fixer.insertTextAfter(replacedNode, ")"); + } + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-const.js b/node_modules/eslint/lib/rules/prefer-const.js new file mode 100644 index 0000000..b43975e --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-const.js @@ -0,0 +1,501 @@ +/** + * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/u; +const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|StaticBlock|SwitchCase)$/u; +const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/u; + +/** + * Checks whether a given node is located at `ForStatement.init` or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is located at `ForStatement.init`. + */ +function isInitOfForStatement(node) { + return node.parent.type === "ForStatement" && node.parent.init === node; +} + +/** + * Checks whether a given Identifier node becomes a VariableDeclaration or not. + * @param {ASTNode} identifier An Identifier node to check. + * @returns {boolean} `true` if the node can become a VariableDeclaration. + */ +function canBecomeVariableDeclaration(identifier) { + let node = identifier.parent; + + while (PATTERN_TYPE.test(node.type)) { + node = node.parent; + } + + return ( + node.type === "VariableDeclarator" || + ( + node.type === "AssignmentExpression" && + node.parent.type === "ExpressionStatement" && + DECLARATION_HOST_TYPE.test(node.parent.parent.type) + ) + ); +} + +/** + * Checks if an property or element is from outer scope or function parameters + * in destructing pattern. + * @param {string} name A variable name to be checked. + * @param {eslint-scope.Scope} initScope A scope to start find. + * @returns {boolean} Indicates if the variable is from outer scope or function parameters. + */ +function isOuterVariableInDestructing(name, initScope) { + + if (initScope.through.some(ref => ref.resolved && ref.resolved.name === name)) { + return true; + } + + const variable = astUtils.getVariableByName(initScope, name); + + if (variable !== null) { + return variable.defs.some(def => def.type === "Parameter"); + } + + return false; +} + +/** + * Gets the VariableDeclarator/AssignmentExpression node that a given reference + * belongs to. + * This is used to detect a mix of reassigned and never reassigned in a + * destructuring. + * @param {eslint-scope.Reference} reference A reference to get. + * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or + * null. + */ +function getDestructuringHost(reference) { + if (!reference.isWrite()) { + return null; + } + let node = reference.identifier.parent; + + while (PATTERN_TYPE.test(node.type)) { + node = node.parent; + } + + if (!DESTRUCTURING_HOST_TYPE.test(node.type)) { + return null; + } + return node; +} + +/** + * Determines if a destructuring assignment node contains + * any MemberExpression nodes. This is used to determine if a + * variable that is only written once using destructuring can be + * safely converted into a const declaration. + * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check. + * @returns {boolean} True if the destructuring pattern contains + * a MemberExpression, false if not. + */ +function hasMemberExpressionAssignment(node) { + switch (node.type) { + case "ObjectPattern": + return node.properties.some(prop => { + if (prop) { + + /* + * Spread elements have an argument property while + * others have a value property. Because different + * parsers use different node types for spread elements, + * we just check if there is an argument property. + */ + return hasMemberExpressionAssignment(prop.argument || prop.value); + } + + return false; + }); + + case "ArrayPattern": + return node.elements.some(element => { + if (element) { + return hasMemberExpressionAssignment(element); + } + + return false; + }); + + case "AssignmentPattern": + return hasMemberExpressionAssignment(node.left); + + case "MemberExpression": + return true; + + // no default + } + + return false; +} + +/** + * Gets an identifier node of a given variable. + * + * If the initialization exists or one or more reading references exist before + * the first assignment, the identifier node is the node of the declaration. + * Otherwise, the identifier node is the node of the first assignment. + * + * If the variable should not change to const, this function returns null. + * - If the variable is reassigned. + * - If the variable is never initialized nor assigned. + * - If the variable is initialized in a different scope from the declaration. + * - If the unique assignment of the variable cannot change to a declaration. + * e.g. `if (a) b = 1` / `return (b = 1)` + * - If the variable is declared in the global scope and `eslintUsed` is `true`. + * `/*exported foo` directive comment makes such variables. This rule does not + * warn such variables because this rule cannot distinguish whether the + * exported variables are reassigned or not. + * @param {eslint-scope.Variable} variable A variable to get. + * @param {boolean} ignoreReadBeforeAssign + * The value of `ignoreReadBeforeAssign` option. + * @returns {ASTNode|null} + * An Identifier node if the variable should change to const. + * Otherwise, null. + */ +function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { + if (variable.eslintUsed && variable.scope.type === "global") { + return null; + } + + // Finds the unique WriteReference. + let writer = null; + let isReadBeforeInit = false; + const references = variable.references; + + for (let i = 0; i < references.length; ++i) { + const reference = references[i]; + + if (reference.isWrite()) { + const isReassigned = ( + writer !== null && + writer.identifier !== reference.identifier + ); + + if (isReassigned) { + return null; + } + + const destructuringHost = getDestructuringHost(reference); + + if (destructuringHost !== null && destructuringHost.left !== void 0) { + const leftNode = destructuringHost.left; + let hasOuterVariables = false, + hasNonIdentifiers = false; + + if (leftNode.type === "ObjectPattern") { + const properties = leftNode.properties; + + hasOuterVariables = properties + .filter(prop => prop.value) + .map(prop => prop.value.name) + .some(name => isOuterVariableInDestructing(name, variable.scope)); + + hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); + + } else if (leftNode.type === "ArrayPattern") { + const elements = leftNode.elements; + + hasOuterVariables = elements + .map(element => element && element.name) + .some(name => isOuterVariableInDestructing(name, variable.scope)); + + hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); + } + + if (hasOuterVariables || hasNonIdentifiers) { + return null; + } + + } + + writer = reference; + + } else if (reference.isRead() && writer === null) { + if (ignoreReadBeforeAssign) { + return null; + } + isReadBeforeInit = true; + } + } + + /* + * If the assignment is from a different scope, ignore it. + * If the assignment cannot change to a declaration, ignore it. + */ + const shouldBeConst = ( + writer !== null && + writer.from === variable.scope && + canBecomeVariableDeclaration(writer.identifier) + ); + + if (!shouldBeConst) { + return null; + } + + if (isReadBeforeInit) { + return variable.defs[0].name; + } + + return writer.identifier; +} + +/** + * Groups by the VariableDeclarator/AssignmentExpression node that each + * reference of given variables belongs to. + * This is used to detect a mix of reassigned and never reassigned in a + * destructuring. + * @param {eslint-scope.Variable[]} variables Variables to group by destructuring. + * @param {boolean} ignoreReadBeforeAssign + * The value of `ignoreReadBeforeAssign` option. + * @returns {Map} Grouped identifier nodes. + */ +function groupByDestructuring(variables, ignoreReadBeforeAssign) { + const identifierMap = new Map(); + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + const references = variable.references; + const identifier = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign); + let prevId = null; + + for (let j = 0; j < references.length; ++j) { + const reference = references[j]; + const id = reference.identifier; + + /* + * Avoid counting a reference twice or more for default values of + * destructuring. + */ + if (id === prevId) { + continue; + } + prevId = id; + + // Add the identifier node into the destructuring group. + const group = getDestructuringHost(reference); + + if (group) { + if (identifierMap.has(group)) { + identifierMap.get(group).push(identifier); + } else { + identifierMap.set(group, [identifier]); + } + } + } + } + + return identifierMap; +} + +/** + * Finds the nearest parent of node with a given type. + * @param {ASTNode} node The node to search from. + * @param {string} type The type field of the parent node. + * @param {Function} shouldStop A predicate that returns true if the traversal should stop, and false otherwise. + * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists. + */ +function findUp(node, type, shouldStop) { + if (!node || shouldStop(node)) { + return null; + } + if (node.type === type) { + return node; + } + return findUp(node.parent, type, shouldStop); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `const` declarations for variables that are never reassigned after declared", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-const" + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + destructuring: { enum: ["any", "all"], default: "any" }, + ignoreReadBeforeAssign: { type: "boolean", default: false } + }, + additionalProperties: false + } + ], + messages: { + useConst: "'{{name}}' is never reassigned. Use 'const' instead." + } + }, + + create(context) { + const options = context.options[0] || {}; + const sourceCode = context.sourceCode; + const shouldMatchAnyDestructuredVariable = options.destructuring !== "all"; + const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true; + const variables = []; + let reportCount = 0; + let checkedId = null; + let checkedName = ""; + + + /** + * Reports given identifier nodes if all of the nodes should be declared + * as const. + * + * The argument 'nodes' is an array of Identifier nodes. + * This node is the result of 'getIdentifierIfShouldBeConst()', so it's + * nullable. In simple declaration or assignment cases, the length of + * the array is 1. In destructuring cases, the length of the array can + * be 2 or more. + * @param {(eslint-scope.Reference|null)[]} nodes + * References which are grouped by destructuring to report. + * @returns {void} + */ + function checkGroup(nodes) { + const nodesToReport = nodes.filter(Boolean); + + if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) { + const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); + const isVarDecParentNull = varDeclParent === null; + + if (!isVarDecParentNull && varDeclParent.declarations.length > 0) { + const firstDeclaration = varDeclParent.declarations[0]; + + if (firstDeclaration.init) { + const firstDecParent = firstDeclaration.init.parent; + + /* + * First we check the declaration type and then depending on + * if the type is a "VariableDeclarator" or its an "ObjectPattern" + * we compare the name and id from the first identifier, if the names are different + * we assign the new name, id and reset the count of reportCount and nodeCount in + * order to check each block for the number of reported errors and base our fix + * based on comparing nodes.length and nodesToReport.length. + */ + + if (firstDecParent.type === "VariableDeclarator") { + + if (firstDecParent.id.name !== checkedName) { + checkedName = firstDecParent.id.name; + reportCount = 0; + } + + if (firstDecParent.id.type === "ObjectPattern") { + if (firstDecParent.init.name !== checkedName) { + checkedName = firstDecParent.init.name; + reportCount = 0; + } + } + + if (firstDecParent.id !== checkedId) { + checkedId = firstDecParent.id; + reportCount = 0; + } + } + } + } + + let shouldFix = varDeclParent && + + // Don't do a fix unless all variables in the declarations are initialized (or it's in a for-in or for-of loop) + (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || + varDeclParent.declarations.every(declaration => declaration.init)) && + + /* + * If options.destructuring is "all", then this warning will not occur unless + * every assignment in the destructuring should be const. In that case, it's safe + * to apply the fix. + */ + nodesToReport.length === nodes.length; + + if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) { + + if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) { + + /* + * Add nodesToReport.length to a count, then comparing the count to the length + * of the declarations in the current block. + */ + + reportCount += nodesToReport.length; + + let totalDeclarationsCount = 0; + + varDeclParent.declarations.forEach(declaration => { + if (declaration.id.type === "ObjectPattern") { + totalDeclarationsCount += declaration.id.properties.length; + } else if (declaration.id.type === "ArrayPattern") { + totalDeclarationsCount += declaration.id.elements.length; + } else { + totalDeclarationsCount += 1; + } + }); + + shouldFix = shouldFix && (reportCount === totalDeclarationsCount); + } + } + + nodesToReport.forEach(node => { + context.report({ + node, + messageId: "useConst", + data: node, + fix: shouldFix + ? fixer => { + const letKeywordToken = sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind); + + /** + * Extend the replacement range to the whole declaration, + * in order to prevent other fixes in the same pass + * https://github.com/eslint/eslint/issues/13899 + */ + return new FixTracker(fixer, sourceCode) + .retainRange(varDeclParent.range) + .replaceTextRange(letKeywordToken.range, "const"); + } + : null + }); + }); + } + } + + return { + "Program:exit"() { + groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup); + }, + + VariableDeclaration(node) { + if (node.kind === "let" && !isInitOfForStatement(node)) { + variables.push(...sourceCode.getDeclaredVariables(node)); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-destructuring.js b/node_modules/eslint/lib/rules/prefer-destructuring.js new file mode 100644 index 0000000..c6075c5 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-destructuring.js @@ -0,0 +1,301 @@ +/** + * @fileoverview Prefer destructuring from arrays and objects + * @author Alex LaFroscia + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PRECEDENCE_OF_ASSIGNMENT_EXPR = astUtils.getPrecedence({ type: "AssignmentExpression" }); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require destructuring from arrays and/or objects", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-destructuring" + }, + + fixable: "code", + + schema: [ + { + + /* + * old support {array: Boolean, object: Boolean} + * new support {VariableDeclarator: {}, AssignmentExpression: {}} + */ + oneOf: [ + { + type: "object", + properties: { + VariableDeclarator: { + type: "object", + properties: { + array: { + type: "boolean" + }, + object: { + type: "boolean" + } + }, + additionalProperties: false + }, + AssignmentExpression: { + type: "object", + properties: { + array: { + type: "boolean" + }, + object: { + type: "boolean" + } + }, + additionalProperties: false + } + }, + additionalProperties: false + }, + { + type: "object", + properties: { + array: { + type: "boolean" + }, + object: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + }, + { + type: "object", + properties: { + enforceForRenamedProperties: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + + messages: { + preferDestructuring: "Use {{type}} destructuring." + } + }, + create(context) { + + const enabledTypes = context.options[0]; + const enforceForRenamedProperties = context.options[1] && context.options[1].enforceForRenamedProperties; + let normalizedOptions = { + VariableDeclarator: { array: true, object: true }, + AssignmentExpression: { array: true, object: true } + }; + + if (enabledTypes) { + normalizedOptions = typeof enabledTypes.array !== "undefined" || typeof enabledTypes.object !== "undefined" + ? { VariableDeclarator: enabledTypes, AssignmentExpression: enabledTypes } + : enabledTypes; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks if destructuring type should be checked. + * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator" + * @param {string} destructuringType "array" or "object" + * @returns {boolean} `true` if the destructuring type should be checked for the given node + */ + function shouldCheck(nodeType, destructuringType) { + return normalizedOptions && + normalizedOptions[nodeType] && + normalizedOptions[nodeType][destructuringType]; + } + + /** + * Determines if the given node is accessing an array index + * + * This is used to differentiate array index access from object property + * access. + * @param {ASTNode} node the node to evaluate + * @returns {boolean} whether or not the node is an integer + */ + function isArrayIndexAccess(node) { + return Number.isInteger(node.property.value); + } + + /** + * Report that the given node should use destructuring + * @param {ASTNode} reportNode the node to report + * @param {string} type the type of destructuring that should have been done + * @param {Function|null} fix the fix function or null to pass to context.report + * @returns {void} + */ + function report(reportNode, type, fix) { + context.report({ + node: reportNode, + messageId: "preferDestructuring", + data: { type }, + fix + }); + } + + /** + * Determines if a node should be fixed into object destructuring + * + * The fixer only fixes the simplest case of object destructuring, + * like: `let x = a.x`; + * + * Assignment expression is not fixed. + * Array destructuring is not fixed. + * Renamed property is not fixed. + * @param {ASTNode} node the node to evaluate + * @returns {boolean} whether or not the node should be fixed + */ + function shouldFix(node) { + return node.type === "VariableDeclarator" && + node.id.type === "Identifier" && + node.init.type === "MemberExpression" && + !node.init.computed && + node.init.property.type === "Identifier" && + node.id.name === node.init.property.name; + } + + /** + * Fix a node into object destructuring. + * This function only handles the simplest case of object destructuring, + * see {@link shouldFix}. + * @param {SourceCodeFixer} fixer the fixer object + * @param {ASTNode} node the node to be fixed. + * @returns {Object} a fix for the node + */ + function fixIntoObjectDestructuring(fixer, node) { + const rightNode = node.init; + const sourceCode = context.sourceCode; + + // Don't fix if that would remove any comments. Only comments inside `rightNode.object` can be preserved. + if (sourceCode.getCommentsInside(node).length > sourceCode.getCommentsInside(rightNode.object).length) { + return null; + } + + let objectText = sourceCode.getText(rightNode.object); + + if (astUtils.getPrecedence(rightNode.object) < PRECEDENCE_OF_ASSIGNMENT_EXPR) { + objectText = `(${objectText})`; + } + + return fixer.replaceText( + node, + `{${rightNode.property.name}} = ${objectText}` + ); + } + + /** + * Check that the `prefer-destructuring` rules are followed based on the + * given left- and right-hand side of the assignment. + * + * Pulled out into a separate method so that VariableDeclarators and + * AssignmentExpressions can share the same verification logic. + * @param {ASTNode} leftNode the left-hand side of the assignment + * @param {ASTNode} rightNode the right-hand side of the assignment + * @param {ASTNode} reportNode the node to report the error on + * @returns {void} + */ + function performCheck(leftNode, rightNode, reportNode) { + if ( + rightNode.type !== "MemberExpression" || + rightNode.object.type === "Super" || + rightNode.property.type === "PrivateIdentifier" + ) { + return; + } + + if (isArrayIndexAccess(rightNode)) { + if (shouldCheck(reportNode.type, "array")) { + report(reportNode, "array", null); + } + return; + } + + const fix = shouldFix(reportNode) + ? fixer => fixIntoObjectDestructuring(fixer, reportNode) + : null; + + if (shouldCheck(reportNode.type, "object") && enforceForRenamedProperties) { + report(reportNode, "object", fix); + return; + } + + if (shouldCheck(reportNode.type, "object")) { + const property = rightNode.property; + + if ( + (property.type === "Literal" && leftNode.name === property.value) || + (property.type === "Identifier" && leftNode.name === property.name && !rightNode.computed) + ) { + report(reportNode, "object", fix); + } + } + } + + /** + * Check if a given variable declarator is coming from an property access + * that should be using destructuring instead + * @param {ASTNode} node the variable declarator to check + * @returns {void} + */ + function checkVariableDeclarator(node) { + + // Skip if variable is declared without assignment + if (!node.init) { + return; + } + + // We only care about member expressions past this point + if (node.init.type !== "MemberExpression") { + return; + } + + performCheck(node.id, node.init, node); + } + + /** + * Run the `prefer-destructuring` check on an AssignmentExpression + * @param {ASTNode} node the AssignmentExpression node + * @returns {void} + */ + function checkAssignmentExpression(node) { + if (node.operator === "=") { + performCheck(node.left, node.right, node); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclarator: checkVariableDeclarator, + AssignmentExpression: checkAssignmentExpression + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js b/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js new file mode 100644 index 0000000..6d807f9 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js @@ -0,0 +1,191 @@ +/** + * @fileoverview Rule to disallow Math.pow in favor of the ** operator + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { CALL, ReferenceTracker } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({ type: "BinaryExpression", operator: "**" }); + +/** + * Determines whether the given node needs parens if used as the base in an exponentiation binary expression. + * @param {ASTNode} base The node to check. + * @returns {boolean} `true` if the node needs to be parenthesised. + */ +function doesBaseNeedParens(base) { + return ( + + // '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c + astUtils.getPrecedence(base) <= PRECEDENCE_OF_EXPONENTIATION_EXPR || + + // An unary operator cannot be used immediately before an exponentiation expression + base.type === "AwaitExpression" || + base.type === "UnaryExpression" + ); +} + +/** + * Determines whether the given node needs parens if used as the exponent in an exponentiation binary expression. + * @param {ASTNode} exponent The node to check. + * @returns {boolean} `true` if the node needs to be parenthesised. + */ +function doesExponentNeedParens(exponent) { + + // '**' is right-associative, there is no need for parens when Math.pow(a, b ** c) is converted to a ** b ** c + return astUtils.getPrecedence(exponent) < PRECEDENCE_OF_EXPONENTIATION_EXPR; +} + +/** + * Determines whether an exponentiation binary expression at the place of the given node would need parens. + * @param {ASTNode} node A node that would be replaced by an exponentiation binary expression. + * @param {SourceCode} sourceCode A SourceCode object. + * @returns {boolean} `true` if the expression needs to be parenthesised. + */ +function doesExponentiationExpressionNeedParens(node, sourceCode) { + const parent = node.parent.type === "ChainExpression" ? node.parent.parent : node.parent; + + const parentPrecedence = astUtils.getPrecedence(parent); + const needsParens = ( + parent.type === "ClassDeclaration" || + ( + parent.type.endsWith("Expression") && + (parentPrecedence === -1 || parentPrecedence >= PRECEDENCE_OF_EXPONENTIATION_EXPR) && + !(parent.type === "BinaryExpression" && parent.operator === "**" && parent.right === node) && + !((parent.type === "CallExpression" || parent.type === "NewExpression") && parent.arguments.includes(node)) && + !(parent.type === "MemberExpression" && parent.computed && parent.property === node) && + !(parent.type === "ArrayExpression") + ) + ); + + return needsParens && !astUtils.isParenthesised(sourceCode, node); +} + +/** + * Optionally parenthesizes given text. + * @param {string} text The text to parenthesize. + * @param {boolean} shouldParenthesize If `true`, the text will be parenthesised. + * @returns {string} parenthesised or unchanged text. + */ +function parenthesizeIfShould(text, shouldParenthesize) { + return shouldParenthesize ? `(${text})` : text; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `Math.pow` in favor of the `**` operator", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-exponentiation-operator" + }, + + schema: [], + fixable: "code", + + messages: { + useExponentiation: "Use the '**' operator instead of 'Math.pow'." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Reports the given node. + * @param {ASTNode} node 'Math.pow()' node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "useExponentiation", + fix(fixer) { + if ( + node.arguments.length !== 2 || + node.arguments.some(arg => arg.type === "SpreadElement") || + sourceCode.getCommentsInside(node).length > 0 + ) { + return null; + } + + const base = node.arguments[0], + exponent = node.arguments[1], + baseText = sourceCode.getText(base), + exponentText = sourceCode.getText(exponent), + shouldParenthesizeBase = doesBaseNeedParens(base), + shouldParenthesizeExponent = doesExponentNeedParens(exponent), + shouldParenthesizeAll = doesExponentiationExpressionNeedParens(node, sourceCode); + + let prefix = "", + suffix = ""; + + if (!shouldParenthesizeAll) { + if (!shouldParenthesizeBase) { + const firstReplacementToken = sourceCode.getFirstToken(base), + tokenBefore = sourceCode.getTokenBefore(node); + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken) + ) { + prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c + } + } + if (!shouldParenthesizeExponent) { + const lastReplacementToken = sourceCode.getLastToken(exponent), + tokenAfter = sourceCode.getTokenAfter(node); + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent(lastReplacementToken, tokenAfter) + ) { + suffix = " "; // Math.pow(a, b)in c -> a**b in c + } + } + } + + const baseReplacement = parenthesizeIfShould(baseText, shouldParenthesizeBase), + exponentReplacement = parenthesizeIfShould(exponentText, shouldParenthesizeExponent), + replacement = parenthesizeIfShould(`${baseReplacement}**${exponentReplacement}`, shouldParenthesizeAll); + + return fixer.replaceText(node, `${prefix}${replacement}${suffix}`); + } + }); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + Math: { + pow: { [CALL]: true } + } + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences(trackMap)) { + report(refNode); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-named-capture-group.js b/node_modules/eslint/lib/rules/prefer-named-capture-group.js new file mode 100644 index 0000000..a82ee1f --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-named-capture-group.js @@ -0,0 +1,178 @@ +/** + * @fileoverview Rule to enforce requiring named capture groups in regular expression. + * @author Pig Fang + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStringIfConstant +} = require("@eslint-community/eslint-utils"); +const regexpp = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new regexpp.RegExpParser(); + +/** + * Creates fixer suggestions for the regex, if statically determinable. + * @param {number} groupStart Starting index of the regex group. + * @param {string} pattern The regular expression pattern to be checked. + * @param {string} rawText Source text of the regexNode. + * @param {ASTNode} regexNode AST node which contains the regular expression. + * @returns {Array} Fixer suggestions for the regex, if statically determinable. + */ +function suggestIfPossible(groupStart, pattern, rawText, regexNode) { + switch (regexNode.type) { + case "Literal": + if (typeof regexNode.value === "string" && rawText.includes("\\")) { + return null; + } + break; + case "TemplateLiteral": + if (regexNode.expressions.length || rawText.slice(1, -1) !== pattern) { + return null; + } + break; + default: + return null; + } + + const start = regexNode.range[0] + groupStart + 2; + + return [ + { + fix(fixer) { + const existingTemps = pattern.match(/temp\d+/gu) || []; + const highestTempCount = existingTemps.reduce( + (previous, next) => + Math.max(previous, Number(next.slice("temp".length))), + 0 + ); + + return fixer.insertTextBeforeRange( + [start, start], + `?` + ); + }, + messageId: "addGroupName" + }, + { + fix(fixer) { + return fixer.insertTextBeforeRange( + [start, start], + "?:" + ); + }, + messageId: "addNonCapture" + } + ]; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce using named capture group in regular expression", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-named-capture-group" + }, + + hasSuggestions: true, + + schema: [], + + messages: { + addGroupName: "Add name to capture group.", + addNonCapture: "Convert group to non-capturing.", + required: "Capture group '{{group}}' should be converted to a named or non-capturing group." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Function to check regular expression. + * @param {string} pattern The regular expression pattern to be checked. + * @param {ASTNode} node AST node which contains the regular expression or a call/new expression. + * @param {ASTNode} regexNode AST node which contains the regular expression. + * @param {string|null} flags The regular expression flags to be checked. + * @returns {void} + */ + function checkRegex(pattern, node, regexNode, flags) { + let ast; + + try { + ast = parser.parsePattern(pattern, 0, pattern.length, { + unicode: Boolean(flags && flags.includes("u")), + unicodeSets: Boolean(flags && flags.includes("v")) + }); + } catch { + + // ignore regex syntax errors + return; + } + + regexpp.visitRegExpAST(ast, { + onCapturingGroupEnter(group) { + if (!group.name) { + const rawText = sourceCode.getText(regexNode); + const suggest = suggestIfPossible(group.start, pattern, rawText, regexNode); + + context.report({ + node, + messageId: "required", + data: { + group: group.raw + }, + suggest + }); + } + } + }); + } + + return { + Literal(node) { + if (node.regex) { + checkRegex(node.regex.pattern, node, node, node.regex.flags); + } + }, + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true + } + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences(traceMap)) { + const regex = getStringIfConstant(refNode.arguments[0]); + const flags = getStringIfConstant(refNode.arguments[1]); + + if (regex) { + checkRegex(regex, refNode, refNode.arguments[0], flags); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-numeric-literals.js b/node_modules/eslint/lib/rules/prefer-numeric-literals.js new file mode 100644 index 0000000..118d6dc --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-numeric-literals.js @@ -0,0 +1,148 @@ +/** + * @fileoverview Rule to disallow `parseInt()` in favor of binary, octal, and hexadecimal literals + * @author Annie Zhang, Henry Zhu + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const radixMap = new Map([ + [2, { system: "binary", literalPrefix: "0b" }], + [8, { system: "octal", literalPrefix: "0o" }], + [16, { system: "hexadecimal", literalPrefix: "0x" }] +]); + +/** + * Checks to see if a CallExpression's callee node is `parseInt` or + * `Number.parseInt`. + * @param {ASTNode} calleeNode The callee node to evaluate. + * @returns {boolean} True if the callee is `parseInt` or `Number.parseInt`, + * false otherwise. + */ +function isParseInt(calleeNode) { + return ( + astUtils.isSpecificId(calleeNode, "parseInt") || + astUtils.isSpecificMemberAccess(calleeNode, "Number", "parseInt") + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-numeric-literals" + }, + + schema: [], + + messages: { + useLiteral: "Use {{system}} literals instead of {{functionName}}()." + }, + + fixable: "code" + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + + "CallExpression[arguments.length=2]"(node) { + const [strNode, radixNode] = node.arguments, + str = astUtils.getStaticStringValue(strNode), + radix = radixNode.value; + + if ( + str !== null && + astUtils.isStringLiteral(strNode) && + radixNode.type === "Literal" && + typeof radix === "number" && + radixMap.has(radix) && + isParseInt(node.callee) + ) { + + const { system, literalPrefix } = radixMap.get(radix); + + context.report({ + node, + messageId: "useLiteral", + data: { + system, + functionName: sourceCode.getText(node.callee) + }, + fix(fixer) { + if (sourceCode.getCommentsInside(node).length) { + return null; + } + + const replacement = `${literalPrefix}${str}`; + + if (+replacement !== parseInt(str, radix)) { + + /* + * If the newly-produced literal would be invalid, (e.g. 0b1234), + * or it would yield an incorrect parseInt result for some other reason, don't make a fix. + * + * If `str` had numeric separators, `+replacement` will evaluate to `NaN` because unary `+` + * per the specification doesn't support numeric separators. Thus, the above condition will be `true` + * (`NaN !== anything` is always `true`) regardless of the `parseInt(str, radix)` value. + * Consequently, no autofixes will be made. This is correct behavior because `parseInt` also + * doesn't support numeric separators, but it does parse part of the string before the first `_`, + * so the autofix would be invalid: + * + * parseInt("1_1", 2) // === 1 + * 0b1_1 // === 3 + */ + return null; + } + + const tokenBefore = sourceCode.getTokenBefore(node), + tokenAfter = sourceCode.getTokenAfter(node); + let prefix = "", + suffix = ""; + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, replacement) + ) { + prefix = " "; + } + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent(replacement, tokenAfter) + ) { + suffix = " "; + } + + return fixer.replaceText(node, `${prefix}${replacement}${suffix}`); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-object-has-own.js b/node_modules/eslint/lib/rules/prefer-object-has-own.js new file mode 100644 index 0000000..97ea64f --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-object-has-own.js @@ -0,0 +1,114 @@ +/** + * @fileoverview Prefers Object.hasOwn() instead of Object.prototype.hasOwnProperty.call() + * @author Nitin Kumar + * @author Gautam Arora + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given node is considered to be an access to a property of `Object.prototype`. + * @param {ASTNode} node `MemberExpression` node to evaluate. + * @returns {boolean} `true` if `node.object` is `Object`, `Object.prototype`, or `{}` (empty 'ObjectExpression' node). + */ +function hasLeftHandObject(node) { + + /* + * ({}).hasOwnProperty.call(obj, prop) - `true` + * ({ foo }.hasOwnProperty.call(obj, prop)) - `false`, object literal should be empty + */ + if (node.object.type === "ObjectExpression" && node.object.properties.length === 0) { + return true; + } + + const objectNodeToCheck = node.object.type === "MemberExpression" && astUtils.getStaticPropertyName(node.object) === "prototype" ? node.object.object : node.object; + + if (objectNodeToCheck.type === "Identifier" && objectNodeToCheck.name === "Object") { + return true; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + docs: { + description: + "Disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-object-has-own" + }, + schema: [], + messages: { + useHasOwn: "Use 'Object.hasOwn()' instead of 'Object.prototype.hasOwnProperty.call()'." + }, + fixable: "code" + }, + create(context) { + + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + if (!(node.callee.type === "MemberExpression" && node.callee.object.type === "MemberExpression")) { + return; + } + + const calleePropertyName = astUtils.getStaticPropertyName(node.callee); + const objectPropertyName = astUtils.getStaticPropertyName(node.callee.object); + const isObject = hasLeftHandObject(node.callee.object); + + // check `Object` scope + const scope = sourceCode.getScope(node); + const variable = astUtils.getVariableByName(scope, "Object"); + + if ( + calleePropertyName === "call" && + objectPropertyName === "hasOwnProperty" && + isObject && + variable && variable.scope.type === "global" + ) { + context.report({ + node, + messageId: "useHasOwn", + fix(fixer) { + + if (sourceCode.getCommentsInside(node.callee).length > 0) { + return null; + } + + const tokenJustBeforeNode = sourceCode.getTokenBefore(node.callee, { includeComments: true }); + + // for https://github.com/eslint/eslint/pull/15346#issuecomment-991417335 + if ( + tokenJustBeforeNode && + tokenJustBeforeNode.range[1] === node.callee.range[0] && + !astUtils.canTokensBeAdjacent(tokenJustBeforeNode, "Object.hasOwn") + ) { + return fixer.replaceText(node.callee, " Object.hasOwn"); + } + + return fixer.replaceText(node.callee, "Object.hasOwn"); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-object-spread.js b/node_modules/eslint/lib/rules/prefer-object-spread.js new file mode 100644 index 0000000..60b0c31 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-object-spread.js @@ -0,0 +1,298 @@ +/** + * @fileoverview Prefers object spread property over Object.assign + * @author Sharmila Jesupaul + */ + +"use strict"; + +const { CALL, ReferenceTracker } = require("@eslint-community/eslint-utils"); +const { + isCommaToken, + isOpeningParenToken, + isClosingParenToken, + isParenthesised +} = require("./utils/ast-utils"); + +const ANY_SPACE = /\s/u; + +/** + * Helper that checks if the Object.assign call has array spread + * @param {ASTNode} node The node that the rule warns on + * @returns {boolean} - Returns true if the Object.assign call has array spread + */ +function hasArraySpread(node) { + return node.arguments.some(arg => arg.type === "SpreadElement"); +} + +/** + * Determines whether the given node is an accessor property (getter/setter). + * @param {ASTNode} node Node to check. + * @returns {boolean} `true` if the node is a getter or a setter. + */ +function isAccessorProperty(node) { + return node.type === "Property" && + (node.kind === "get" || node.kind === "set"); +} + +/** + * Determines whether the given object expression node has accessor properties (getters/setters). + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {boolean} `true` if the node has at least one getter/setter. + */ +function hasAccessors(node) { + return node.properties.some(isAccessorProperty); +} + +/** + * Determines whether the given call expression node has object expression arguments with accessor properties (getters/setters). + * @param {ASTNode} node `CallExpression` node to check. + * @returns {boolean} `true` if the node has at least one argument that is an object expression with at least one getter/setter. + */ +function hasArgumentsWithAccessors(node) { + return node.arguments + .filter(arg => arg.type === "ObjectExpression") + .some(hasAccessors); +} + +/** + * Helper that checks if the node needs parentheses to be valid JS. + * The default is to wrap the node in parentheses to avoid parsing errors. + * @param {ASTNode} node The node that the rule warns on + * @param {Object} sourceCode in context sourcecode object + * @returns {boolean} - Returns true if the node needs parentheses + */ +function needsParens(node, sourceCode) { + const parent = node.parent; + + switch (parent.type) { + case "VariableDeclarator": + case "ArrayExpression": + case "ReturnStatement": + case "CallExpression": + case "Property": + return false; + case "AssignmentExpression": + return parent.left === node && !isParenthesised(sourceCode, node); + default: + return !isParenthesised(sourceCode, node); + } +} + +/** + * Determines if an argument needs parentheses. The default is to not add parens. + * @param {ASTNode} node The node to be checked. + * @param {Object} sourceCode in context sourcecode object + * @returns {boolean} True if the node needs parentheses + */ +function argNeedsParens(node, sourceCode) { + switch (node.type) { + case "AssignmentExpression": + case "ArrowFunctionExpression": + case "ConditionalExpression": + return !isParenthesised(sourceCode, node); + default: + return false; + } +} + +/** + * Get the parenthesis tokens of a given ObjectExpression node. + * This includes the braces of the object literal and enclosing parentheses. + * @param {ASTNode} node The node to get. + * @param {Token} leftArgumentListParen The opening paren token of the argument list. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token[]} The parenthesis tokens of the node. This is sorted by the location. + */ +function getParenTokens(node, leftArgumentListParen, sourceCode) { + const parens = [sourceCode.getFirstToken(node), sourceCode.getLastToken(node)]; + let leftNext = sourceCode.getTokenBefore(node); + let rightNext = sourceCode.getTokenAfter(node); + + // Note: don't include the parens of the argument list. + while ( + leftNext && + rightNext && + leftNext.range[0] > leftArgumentListParen.range[0] && + isOpeningParenToken(leftNext) && + isClosingParenToken(rightNext) + ) { + parens.push(leftNext, rightNext); + leftNext = sourceCode.getTokenBefore(leftNext); + rightNext = sourceCode.getTokenAfter(rightNext); + } + + return parens.sort((a, b) => a.range[0] - b.range[0]); +} + +/** + * Get the range of a given token and around whitespaces. + * @param {Token} token The token to get range. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {number} The end of the range of the token and around whitespaces. + */ +function getStartWithSpaces(token, sourceCode) { + const text = sourceCode.text; + let start = token.range[0]; + + // If the previous token is a line comment then skip this step to avoid commenting this token out. + { + const prevToken = sourceCode.getTokenBefore(token, { includeComments: true }); + + if (prevToken && prevToken.type === "Line") { + return start; + } + } + + // Detect spaces before the token. + while (ANY_SPACE.test(text[start - 1] || "")) { + start -= 1; + } + + return start; +} + +/** + * Get the range of a given token and around whitespaces. + * @param {Token} token The token to get range. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {number} The start of the range of the token and around whitespaces. + */ +function getEndWithSpaces(token, sourceCode) { + const text = sourceCode.text; + let end = token.range[1]; + + // Detect spaces after the token. + while (ANY_SPACE.test(text[end] || "")) { + end += 1; + } + + return end; +} + +/** + * Autofixes the Object.assign call to use an object spread instead. + * @param {ASTNode|null} node The node that the rule warns on, i.e. the Object.assign call + * @param {string} sourceCode sourceCode of the Object.assign call + * @returns {Function} autofixer - replaces the Object.assign with a spread object. + */ +function defineFixer(node, sourceCode) { + return function *(fixer) { + const leftParen = sourceCode.getTokenAfter(node.callee, isOpeningParenToken); + const rightParen = sourceCode.getLastToken(node); + + // Remove everything before the opening paren: callee `Object.assign`, type arguments, and whitespace between the callee and the paren. + yield fixer.removeRange([node.range[0], leftParen.range[0]]); + + // Replace the parens of argument list to braces. + if (needsParens(node, sourceCode)) { + yield fixer.replaceText(leftParen, "({"); + yield fixer.replaceText(rightParen, "})"); + } else { + yield fixer.replaceText(leftParen, "{"); + yield fixer.replaceText(rightParen, "}"); + } + + // Process arguments. + for (const argNode of node.arguments) { + const innerParens = getParenTokens(argNode, leftParen, sourceCode); + const left = innerParens.shift(); + const right = innerParens.pop(); + + if (argNode.type === "ObjectExpression") { + const maybeTrailingComma = sourceCode.getLastToken(argNode, 1); + const maybeArgumentComma = sourceCode.getTokenAfter(right); + + /* + * Make bare this object literal. + * And remove spaces inside of the braces for better formatting. + */ + for (const innerParen of innerParens) { + yield fixer.remove(innerParen); + } + const leftRange = [left.range[0], getEndWithSpaces(left, sourceCode)]; + const rightRange = [ + Math.max(getStartWithSpaces(right, sourceCode), leftRange[1]), // Ensure ranges don't overlap + right.range[1] + ]; + + yield fixer.removeRange(leftRange); + yield fixer.removeRange(rightRange); + + // Remove the comma of this argument if it's duplication. + if ( + (argNode.properties.length === 0 || isCommaToken(maybeTrailingComma)) && + isCommaToken(maybeArgumentComma) + ) { + yield fixer.remove(maybeArgumentComma); + } + } else { + + // Make spread. + if (argNeedsParens(argNode, sourceCode)) { + yield fixer.insertTextBefore(left, "...("); + yield fixer.insertTextAfter(right, ")"); + } else { + yield fixer.insertTextBefore(left, "..."); + } + } + } + }; +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-object-spread" + }, + + schema: [], + fixable: "code", + + messages: { + useSpreadMessage: "Use an object spread instead of `Object.assign` eg: `{ ...foo }`.", + useLiteralMessage: "Use an object literal instead of `Object.assign`. eg: `{ foo: bar }`." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + Object: { + assign: { [CALL]: true } + } + }; + + // Iterate all calls of `Object.assign` (only of the global variable `Object`). + for (const { node: refNode } of tracker.iterateGlobalReferences(trackMap)) { + if ( + refNode.arguments.length >= 1 && + refNode.arguments[0].type === "ObjectExpression" && + !hasArraySpread(refNode) && + !( + refNode.arguments.length > 1 && + hasArgumentsWithAccessors(refNode) + ) + ) { + const messageId = refNode.arguments.length === 1 + ? "useLiteralMessage" + : "useSpreadMessage"; + const fix = defineFixer(refNode, sourceCode); + + context.report({ node: refNode, messageId, fix }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js b/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js new file mode 100644 index 0000000..e990265 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js @@ -0,0 +1,132 @@ +/** + * @fileoverview restrict values that can be used as Promise rejection reasons + * @author Teddy Katz + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require using Error objects as Promise rejection reasons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-promise-reject-errors" + }, + + fixable: null, + + schema: [ + { + type: "object", + properties: { + allowEmptyReject: { type: "boolean", default: false } + }, + additionalProperties: false + } + ], + + messages: { + rejectAnError: "Expected the Promise rejection reason to be an Error." + } + }, + + create(context) { + + const ALLOW_EMPTY_REJECT = context.options.length && context.options[0].allowEmptyReject; + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error + * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise + * @returns {void} + */ + function checkRejectCall(callExpression) { + if (!callExpression.arguments.length && ALLOW_EMPTY_REJECT) { + return; + } + if ( + !callExpression.arguments.length || + !astUtils.couldBeError(callExpression.arguments[0]) || + callExpression.arguments[0].type === "Identifier" && callExpression.arguments[0].name === "undefined" + ) { + context.report({ + node: callExpression, + messageId: "rejectAnError" + }); + } + } + + /** + * Determines whether a function call is a Promise.reject() call + * @param {ASTNode} node A CallExpression node + * @returns {boolean} `true` if the call is a Promise.reject() call + */ + function isPromiseRejectCall(node) { + return astUtils.isSpecificMemberAccess(node.callee, "Promise", "reject"); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + + // Check `Promise.reject(value)` calls. + CallExpression(node) { + if (isPromiseRejectCall(node)) { + checkRejectCall(node); + } + }, + + /* + * Check for `new Promise((resolve, reject) => {})`, and check for reject() calls. + * This function is run on "NewExpression:exit" instead of "NewExpression" to ensure that + * the nodes in the expression already have the `parent` property. + */ + "NewExpression:exit"(node) { + if ( + node.callee.type === "Identifier" && node.callee.name === "Promise" && + node.arguments.length && astUtils.isFunction(node.arguments[0]) && + node.arguments[0].params.length > 1 && node.arguments[0].params[1].type === "Identifier" + ) { + sourceCode.getDeclaredVariables(node.arguments[0]) + + /* + * Find the first variable that matches the second parameter's name. + * If the first parameter has the same name as the second parameter, then the variable will actually + * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten + * by the second parameter. It's not possible for an expression with the variable to be evaluated before + * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or + * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for + * this case. + */ + .find(variable => variable.name === node.arguments[0].params[1].name) + + // Get the references to that variable. + .references + + // Only check the references that read the parameter's value. + .filter(ref => ref.isRead()) + + // Only check the references that are used as the callee in a function call, e.g. `reject(foo)`. + .filter(ref => ref.identifier.parent.type === "CallExpression" && ref.identifier === ref.identifier.parent.callee) + + // Check the argument of the function call to determine whether it's an Error. + .forEach(ref => checkRejectCall(ref.identifier.parent)); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-reflect.js b/node_modules/eslint/lib/rules/prefer-reflect.js new file mode 100644 index 0000000..d579b48 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-reflect.js @@ -0,0 +1,127 @@ +/** + * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods + * @author Keith Cirkel + * @deprecated in ESLint v3.9.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `Reflect` methods where applicable", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-reflect" + }, + + deprecated: true, + + replacedBy: [], + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + enum: [ + "apply", + "call", + "delete", + "defineProperty", + "getOwnPropertyDescriptor", + "getPrototypeOf", + "setPrototypeOf", + "isExtensible", + "getOwnPropertyNames", + "preventExtensions" + ] + }, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + preferReflect: "Avoid using {{existing}}, instead use {{substitute}}." + } + }, + + create(context) { + const existingNames = { + apply: "Function.prototype.apply", + call: "Function.prototype.call", + defineProperty: "Object.defineProperty", + getOwnPropertyDescriptor: "Object.getOwnPropertyDescriptor", + getPrototypeOf: "Object.getPrototypeOf", + setPrototypeOf: "Object.setPrototypeOf", + isExtensible: "Object.isExtensible", + getOwnPropertyNames: "Object.getOwnPropertyNames", + preventExtensions: "Object.preventExtensions" + }; + + const reflectSubstitutes = { + apply: "Reflect.apply", + call: "Reflect.apply", + defineProperty: "Reflect.defineProperty", + getOwnPropertyDescriptor: "Reflect.getOwnPropertyDescriptor", + getPrototypeOf: "Reflect.getPrototypeOf", + setPrototypeOf: "Reflect.setPrototypeOf", + isExtensible: "Reflect.isExtensible", + getOwnPropertyNames: "Reflect.getOwnPropertyNames", + preventExtensions: "Reflect.preventExtensions" + }; + + const exceptions = (context.options[0] || {}).exceptions || []; + + /** + * Reports the Reflect violation based on the `existing` and `substitute` + * @param {Object} node The node that violates the rule. + * @param {string} existing The existing method name that has been used. + * @param {string} substitute The Reflect substitute that should be used. + * @returns {void} + */ + function report(node, existing, substitute) { + context.report({ + node, + messageId: "preferReflect", + data: { + existing, + substitute + } + }); + } + + return { + CallExpression(node) { + const methodName = (node.callee.property || {}).name; + const isReflectCall = (node.callee.object || {}).name === "Reflect"; + const hasReflectSubstitute = Object.prototype.hasOwnProperty.call(reflectSubstitutes, methodName); + const userConfiguredException = exceptions.includes(methodName); + + if (hasReflectSubstitute && !isReflectCall && !userConfiguredException) { + report(node, existingNames[methodName], reflectSubstitutes[methodName]); + } + }, + UnaryExpression(node) { + const isDeleteOperator = node.operator === "delete"; + const targetsIdentifier = node.argument.type === "Identifier"; + const userConfiguredException = exceptions.includes("delete"); + + if (isDeleteOperator && !targetsIdentifier && !userConfiguredException) { + report(node, "the delete keyword", "Reflect.deleteProperty"); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/prefer-regex-literals.js b/node_modules/eslint/lib/rules/prefer-regex-literals.js new file mode 100644 index 0000000..ffaaeac --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-regex-literals.js @@ -0,0 +1,507 @@ +/** + * @fileoverview Rule to disallow use of the `RegExp` constructor in favor of regular expression literals + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { CALL, CONSTRUCT, ReferenceTracker, findVariable } = require("@eslint-community/eslint-utils"); +const { RegExpValidator, visitRegExpAST, RegExpParser } = require("@eslint-community/regexpp"); +const { canTokensBeAdjacent } = require("./utils/ast-utils"); +const { REGEXPP_LATEST_ECMA_VERSION } = require("./utils/regular-expressions"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is a string literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a string literal. + */ +function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; +} + +/** + * Determines whether the given node is a regex literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a regex literal. + */ +function isRegexLiteral(node) { + return node.type === "Literal" && Object.prototype.hasOwnProperty.call(node, "regex"); +} + +const validPrecedingTokens = new Set([ + "(", + ";", + "[", + ",", + "=", + "+", + "*", + "-", + "?", + "~", + "%", + "**", + "!", + "typeof", + "instanceof", + "&&", + "||", + "??", + "return", + "...", + "delete", + "void", + "in", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "<<", + ">>", + ">>>", + "&", + "|", + "^", + ":", + "{", + "=>", + "*=", + "<<=", + ">>=", + ">>>=", + "^=", + "|=", + "&=", + "??=", + "||=", + "&&=", + "**=", + "+=", + "-=", + "/=", + "%=", + "/", + "do", + "break", + "continue", + "debugger", + "case", + "throw" +]); + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow use of the `RegExp` constructor in favor of regular expression literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-regex-literals" + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + disallowRedundantWrapping: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedRegExp: "Use a regular expression literal instead of the 'RegExp' constructor.", + replaceWithLiteral: "Replace with an equivalent regular expression literal.", + replaceWithLiteralAndFlags: "Replace with an equivalent regular expression literal with flags '{{ flags }}'.", + replaceWithIntendedLiteralAndFlags: "Replace with a regular expression literal with flags '{{ flags }}'.", + unexpectedRedundantRegExp: "Regular expression literal is unnecessarily wrapped within a 'RegExp' constructor.", + unexpectedRedundantRegExpWithFlags: "Use regular expression literal with flags instead of the 'RegExp' constructor." + } + }, + + create(context) { + const [{ disallowRedundantWrapping = false } = {}] = context.options; + const sourceCode = context.sourceCode; + + /** + * Determines whether the given identifier node is a reference to a global variable. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} True if the identifier is a reference to a global variable. + */ + function isGlobalReference(node) { + const scope = sourceCode.getScope(node); + const variable = findVariable(scope, node); + + return variable !== null && variable.scope.type === "global" && variable.defs.length === 0; + } + + /** + * Determines whether the given node is a String.raw`` tagged template expression + * with a static template literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is String.raw`` with a static template. + */ + function isStringRawTaggedStaticTemplateLiteral(node) { + return node.type === "TaggedTemplateExpression" && + astUtils.isSpecificMemberAccess(node.tag, "String", "raw") && + isGlobalReference(astUtils.skipChainExpression(node.tag).object) && + astUtils.isStaticTemplateLiteral(node.quasi); + } + + /** + * Gets the value of a string + * @param {ASTNode} node The node to get the string of. + * @returns {string|null} The value of the node. + */ + function getStringValue(node) { + if (isStringLiteral(node)) { + return node.value; + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return node.quasis[0].value.cooked; + } + + if (isStringRawTaggedStaticTemplateLiteral(node)) { + return node.quasi.quasis[0].value.raw; + } + + return null; + } + + /** + * Determines whether the given node is considered to be a static string by the logic of this rule. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a static string. + */ + function isStaticString(node) { + return isStringLiteral(node) || + astUtils.isStaticTemplateLiteral(node) || + isStringRawTaggedStaticTemplateLiteral(node); + } + + /** + * Determines whether the relevant arguments of the given are all static string literals. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if all arguments are static strings. + */ + function hasOnlyStaticStringArguments(node) { + const args = node.arguments; + + if ((args.length === 1 || args.length === 2) && args.every(isStaticString)) { + return true; + } + + return false; + } + + /** + * Determines whether the arguments of the given node indicate that a regex literal is unnecessarily wrapped. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node already contains a regex literal argument. + */ + function isUnnecessarilyWrappedRegexLiteral(node) { + const args = node.arguments; + + if (args.length === 1 && isRegexLiteral(args[0])) { + return true; + } + + if (args.length === 2 && isRegexLiteral(args[0]) && isStaticString(args[1])) { + return true; + } + + return false; + } + + /** + * Returns a ecmaVersion compatible for regexpp. + * @param {number} ecmaVersion The ecmaVersion to convert. + * @returns {import("@eslint-community/regexpp/ecma-versions").EcmaVersion} The resulting ecmaVersion compatible for regexpp. + */ + function getRegexppEcmaVersion(ecmaVersion) { + if (ecmaVersion <= 5) { + return 5; + } + return Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION); + } + + const regexppEcmaVersion = getRegexppEcmaVersion(context.languageOptions.ecmaVersion); + + /** + * Makes a character escaped or else returns null. + * @param {string} character The character to escape. + * @returns {string} The resulting escaped character. + */ + function resolveEscapes(character) { + switch (character) { + case "\n": + case "\\\n": + return "\\n"; + + case "\r": + case "\\\r": + return "\\r"; + + case "\t": + case "\\\t": + return "\\t"; + + case "\v": + case "\\\v": + return "\\v"; + + case "\f": + case "\\\f": + return "\\f"; + + case "/": + return "\\/"; + + default: + return null; + } + } + + /** + * Checks whether the given regex and flags are valid for the ecma version or not. + * @param {string} pattern The regex pattern to check. + * @param {string | undefined} flags The regex flags to check. + * @returns {boolean} True if the given regex pattern and flags are valid for the ecma version. + */ + function isValidRegexForEcmaVersion(pattern, flags) { + const validator = new RegExpValidator({ ecmaVersion: regexppEcmaVersion }); + + try { + validator.validatePattern(pattern, 0, pattern.length, { + unicode: flags ? flags.includes("u") : false, + unicodeSets: flags ? flags.includes("v") : false + }); + if (flags) { + validator.validateFlags(flags); + } + return true; + } catch { + return false; + } + } + + /** + * Checks whether two given regex flags contain the same flags or not. + * @param {string} flagsA The regex flags. + * @param {string} flagsB The regex flags. + * @returns {boolean} True if two regex flags contain same flags. + */ + function areFlagsEqual(flagsA, flagsB) { + return [...flagsA].sort().join("") === [...flagsB].sort().join(""); + } + + + /** + * Merges two regex flags. + * @param {string} flagsA The regex flags. + * @param {string} flagsB The regex flags. + * @returns {string} The merged regex flags. + */ + function mergeRegexFlags(flagsA, flagsB) { + const flagsSet = new Set([ + ...flagsA, + ...flagsB + ]); + + return [...flagsSet].join(""); + } + + /** + * Checks whether a give node can be fixed to the given regex pattern and flags. + * @param {ASTNode} node The node to check. + * @param {string} pattern The regex pattern to check. + * @param {string} flags The regex flags + * @returns {boolean} True if a node can be fixed to the given regex pattern and flags. + */ + function canFixTo(node, pattern, flags) { + const tokenBefore = sourceCode.getTokenBefore(node); + + return sourceCode.getCommentsInside(node).length === 0 && + (!tokenBefore || validPrecedingTokens.has(tokenBefore.value)) && + isValidRegexForEcmaVersion(pattern, flags); + } + + /** + * Returns a safe output code considering the before and after tokens. + * @param {ASTNode} node The regex node. + * @param {string} newRegExpValue The new regex expression value. + * @returns {string} The output code. + */ + function getSafeOutput(node, newRegExpValue) { + const tokenBefore = sourceCode.getTokenBefore(node); + const tokenAfter = sourceCode.getTokenAfter(node); + + return (tokenBefore && !canTokensBeAdjacent(tokenBefore, newRegExpValue) && tokenBefore.range[1] === node.range[0] ? " " : "") + + newRegExpValue + + (tokenAfter && !canTokensBeAdjacent(newRegExpValue, tokenAfter) && node.range[1] === tokenAfter.range[0] ? " " : ""); + + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true + } + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences(traceMap)) { + if (disallowRedundantWrapping && isUnnecessarilyWrappedRegexLiteral(refNode)) { + const regexNode = refNode.arguments[0]; + + if (refNode.arguments.length === 2) { + const suggests = []; + + const argFlags = getStringValue(refNode.arguments[1]) || ""; + + if (canFixTo(refNode, regexNode.regex.pattern, argFlags)) { + suggests.push({ + messageId: "replaceWithLiteralAndFlags", + pattern: regexNode.regex.pattern, + flags: argFlags + }); + } + + const literalFlags = regexNode.regex.flags || ""; + const mergedFlags = mergeRegexFlags(literalFlags, argFlags); + + if ( + !areFlagsEqual(mergedFlags, argFlags) && + canFixTo(refNode, regexNode.regex.pattern, mergedFlags) + ) { + suggests.push({ + messageId: "replaceWithIntendedLiteralAndFlags", + pattern: regexNode.regex.pattern, + flags: mergedFlags + }); + } + + context.report({ + node: refNode, + messageId: "unexpectedRedundantRegExpWithFlags", + suggest: suggests.map(({ flags, pattern, messageId }) => ({ + messageId, + data: { + flags + }, + fix(fixer) { + return fixer.replaceText(refNode, getSafeOutput(refNode, `/${pattern}/${flags}`)); + } + })) + }); + } else { + const outputs = []; + + if (canFixTo(refNode, regexNode.regex.pattern, regexNode.regex.flags)) { + outputs.push(sourceCode.getText(regexNode)); + } + + + context.report({ + node: refNode, + messageId: "unexpectedRedundantRegExp", + suggest: outputs.map(output => ({ + messageId: "replaceWithLiteral", + fix(fixer) { + return fixer.replaceText( + refNode, + getSafeOutput(refNode, output) + ); + } + })) + }); + } + } else if (hasOnlyStaticStringArguments(refNode)) { + let regexContent = getStringValue(refNode.arguments[0]); + let noFix = false; + let flags; + + if (refNode.arguments[1]) { + flags = getStringValue(refNode.arguments[1]); + } + + if (!canFixTo(refNode, regexContent, flags)) { + noFix = true; + } + + if (!/^[-a-zA-Z0-9\\[\](){} \t\r\n\v\f!@#$%^&*+^_=/~`.> accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), ""); + } + + /** + * Returns a template literal form of the given node. + * @param {ASTNode} currentNode A node that should be converted to a template literal + * @param {string} textBeforeNode Text that should appear before the node + * @param {string} textAfterNode Text that should appear after the node + * @returns {string} A string form of this node, represented as a template literal + */ + function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) { + if (currentNode.type === "Literal" && typeof currentNode.value === "string") { + + /* + * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted + * as a template placeholder. However, if the code already contains a backslash before the ${ or ` + * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause + * an actual backslash character to appear before the dollar sign). + */ + return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched => { + if (matched.lastIndexOf("\\") % 2) { + return `\\${matched}`; + } + return matched; + + // Unescape any quotes that appear in the original Literal that no longer need to be escaped. + }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), currentNode.raw[0])}\``; + } + + if (currentNode.type === "TemplateLiteral") { + return sourceCode.getText(currentNode); + } + + if (isConcatenation(currentNode) && hasStringLiteral(currentNode)) { + const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+"); + const textBeforePlus = getTextBetween(currentNode.left, plusSign); + const textAfterPlus = getTextBetween(plusSign, currentNode.right); + const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left); + const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right); + + if (leftEndsWithCurly) { + + // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket. + // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}` + return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) + + getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1); + } + if (rightStartsWithCurly) { + + // Otherwise, if the right side of the expression starts with a template curly, add the text there. + // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz` + return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) + + getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1); + } + + /* + * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put + * the text between them. + */ + return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`; + } + + return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``; + } + + /** + * Returns a fixer object that converts a non-string binary expression to a template literal + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A node that should be converted to a template literal + * @returns {Object} A fix for this binary expression + */ + function fixNonStringBinaryExpression(fixer, node) { + const topBinaryExpr = getTopConcatBinaryExpression(node.parent); + + if (hasOctalOrNonOctalDecimalEscapeSequence(topBinaryExpr)) { + return null; + } + + return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null)); + } + + /** + * Reports if a given node is string concatenation with non string literals. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkForStringConcat(node) { + if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) { + return; + } + + const topBinaryExpr = getTopConcatBinaryExpression(node.parent); + + // Checks whether or not this node had been checked already. + if (done[topBinaryExpr.range[0]]) { + return; + } + done[topBinaryExpr.range[0]] = true; + + if (hasNonStringLiteral(topBinaryExpr)) { + context.report({ + node: topBinaryExpr, + messageId: "unexpectedStringConcatenation", + fix: fixer => fixNonStringBinaryExpression(fixer, node) + }); + } + } + + return { + Program() { + done = Object.create(null); + }, + + Literal: checkForStringConcat, + TemplateLiteral: checkForStringConcat + }; + } +}; diff --git a/node_modules/eslint/lib/rules/quote-props.js b/node_modules/eslint/lib/rules/quote-props.js new file mode 100644 index 0000000..8abab15 --- /dev/null +++ b/node_modules/eslint/lib/rules/quote-props.js @@ -0,0 +1,307 @@ +/** + * @fileoverview Rule to flag non-quoted property names in object literals. + * @author Mathias Bynens + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const espree = require("espree"); +const astUtils = require("./utils/ast-utils"); +const keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require quotes around object literal property names", + recommended: false, + url: "https://eslint.org/docs/latest/rules/quote-props" + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always", "as-needed", "consistent", "consistent-as-needed"] + } + ], + minItems: 0, + maxItems: 1 + }, + { + type: "array", + items: [ + { + enum: ["always", "as-needed", "consistent", "consistent-as-needed"] + }, + { + type: "object", + properties: { + keywords: { + type: "boolean" + }, + unnecessary: { + type: "boolean" + }, + numbers: { + type: "boolean" + } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + } + ] + }, + + fixable: "code", + messages: { + requireQuotesDueToReservedWord: "Properties should be quoted as '{{property}}' is a reserved word.", + inconsistentlyQuotedProperty: "Inconsistently quoted property '{{key}}' found.", + unnecessarilyQuotedProperty: "Unnecessarily quoted property '{{property}}' found.", + unquotedReservedProperty: "Unquoted reserved word '{{property}}' used as key.", + unquotedNumericProperty: "Unquoted number literal '{{property}}' used as key.", + unquotedPropertyFound: "Unquoted property '{{property}}' found.", + redundantQuoting: "Properties shouldn't be quoted as all quotes are redundant." + } + }, + + create(context) { + + const MODE = context.options[0], + KEYWORDS = context.options[1] && context.options[1].keywords, + CHECK_UNNECESSARY = !context.options[1] || context.options[1].unnecessary !== false, + NUMBERS = context.options[1] && context.options[1].numbers, + + sourceCode = context.sourceCode; + + + /** + * Checks whether a certain string constitutes an ES3 token + * @param {string} tokenStr The string to be checked. + * @returns {boolean} `true` if it is an ES3 token. + */ + function isKeyword(tokenStr) { + return keywords.includes(tokenStr); + } + + /** + * Checks if an espree-tokenized key has redundant quotes (i.e. whether quotes are unnecessary) + * @param {string} rawKey The raw key value from the source + * @param {espreeTokens} tokens The espree-tokenized node key + * @param {boolean} [skipNumberLiterals=false] Indicates whether number literals should be checked + * @returns {boolean} Whether or not a key has redundant quotes. + * @private + */ + function areQuotesRedundant(rawKey, tokens, skipNumberLiterals) { + return tokens.length === 1 && tokens[0].start === 0 && tokens[0].end === rawKey.length && + (["Identifier", "Keyword", "Null", "Boolean"].includes(tokens[0].type) || + (tokens[0].type === "Numeric" && !skipNumberLiterals && String(+tokens[0].value) === tokens[0].value)); + } + + /** + * Returns a string representation of a property node with quotes removed + * @param {ASTNode} key Key AST Node, which may or may not be quoted + * @returns {string} A replacement string for this property + */ + function getUnquotedKey(key) { + return key.type === "Identifier" ? key.name : key.value; + } + + /** + * Returns a string representation of a property node with quotes added + * @param {ASTNode} key Key AST Node, which may or may not be quoted + * @returns {string} A replacement string for this property + */ + function getQuotedKey(key) { + if (key.type === "Literal" && typeof key.value === "string") { + + // If the key is already a string literal, don't replace the quotes with double quotes. + return sourceCode.getText(key); + } + + // Otherwise, the key is either an identifier or a number literal. + return `"${key.type === "Identifier" ? key.name : key.value}"`; + } + + /** + * Ensures that a property's key is quoted only when necessary + * @param {ASTNode} node Property AST node + * @returns {void} + */ + function checkUnnecessaryQuotes(node) { + const key = node.key; + + if (node.method || node.computed || node.shorthand) { + return; + } + + if (key.type === "Literal" && typeof key.value === "string") { + let tokens; + + try { + tokens = espree.tokenize(key.value); + } catch { + return; + } + + if (tokens.length !== 1) { + return; + } + + const isKeywordToken = isKeyword(tokens[0].value); + + if (isKeywordToken && KEYWORDS) { + return; + } + + if (CHECK_UNNECESSARY && areQuotesRedundant(key.value, tokens, NUMBERS)) { + context.report({ + node, + messageId: "unnecessarilyQuotedProperty", + data: { property: key.value }, + fix: fixer => fixer.replaceText(key, getUnquotedKey(key)) + }); + } + } else if (KEYWORDS && key.type === "Identifier" && isKeyword(key.name)) { + context.report({ + node, + messageId: "unquotedReservedProperty", + data: { property: key.name }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)) + }); + } else if (NUMBERS && key.type === "Literal" && astUtils.isNumericLiteral(key)) { + context.report({ + node, + messageId: "unquotedNumericProperty", + data: { property: key.value }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)) + }); + } + } + + /** + * Ensures that a property's key is quoted + * @param {ASTNode} node Property AST node + * @returns {void} + */ + function checkOmittedQuotes(node) { + const key = node.key; + + if (!node.method && !node.computed && !node.shorthand && !(key.type === "Literal" && typeof key.value === "string")) { + context.report({ + node, + messageId: "unquotedPropertyFound", + data: { property: key.name || key.value }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)) + }); + } + } + + /** + * Ensures that an object's keys are consistently quoted, optionally checks for redundancy of quotes + * @param {ASTNode} node Property AST node + * @param {boolean} checkQuotesRedundancy Whether to check quotes' redundancy + * @returns {void} + */ + function checkConsistency(node, checkQuotesRedundancy) { + const quotedProps = [], + unquotedProps = []; + let keywordKeyName = null, + necessaryQuotes = false; + + node.properties.forEach(property => { + const key = property.key; + + if (!key || property.method || property.computed || property.shorthand) { + return; + } + + if (key.type === "Literal" && typeof key.value === "string") { + + quotedProps.push(property); + + if (checkQuotesRedundancy) { + let tokens; + + try { + tokens = espree.tokenize(key.value); + } catch { + necessaryQuotes = true; + return; + } + + necessaryQuotes = necessaryQuotes || !areQuotesRedundant(key.value, tokens) || KEYWORDS && isKeyword(tokens[0].value); + } + } else if (KEYWORDS && checkQuotesRedundancy && key.type === "Identifier" && isKeyword(key.name)) { + unquotedProps.push(property); + necessaryQuotes = true; + keywordKeyName = key.name; + } else { + unquotedProps.push(property); + } + }); + + if (checkQuotesRedundancy && quotedProps.length && !necessaryQuotes) { + quotedProps.forEach(property => { + context.report({ + node: property, + messageId: "redundantQuoting", + fix: fixer => fixer.replaceText(property.key, getUnquotedKey(property.key)) + }); + }); + } else if (unquotedProps.length && keywordKeyName) { + unquotedProps.forEach(property => { + context.report({ + node: property, + messageId: "requireQuotesDueToReservedWord", + data: { property: keywordKeyName }, + fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) + }); + }); + } else if (quotedProps.length && unquotedProps.length) { + unquotedProps.forEach(property => { + context.report({ + node: property, + messageId: "inconsistentlyQuotedProperty", + data: { key: property.key.name || property.key.value }, + fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) + }); + }); + } + } + + return { + Property(node) { + if (MODE === "always" || !MODE) { + checkOmittedQuotes(node); + } + if (MODE === "as-needed") { + checkUnnecessaryQuotes(node); + } + }, + ObjectExpression(node) { + if (MODE === "consistent") { + checkConsistency(node, false); + } + if (MODE === "consistent-as-needed") { + checkConsistency(node, true); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/quotes.js b/node_modules/eslint/lib/rules/quotes.js new file mode 100644 index 0000000..6eda7c0 --- /dev/null +++ b/node_modules/eslint/lib/rules/quotes.js @@ -0,0 +1,347 @@ +/** + * @fileoverview A rule to choose between single and double quote marks + * @author Matt DuVall , Brandon Payton + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const QUOTE_SETTINGS = { + double: { + quote: "\"", + alternateQuote: "'", + description: "doublequote" + }, + single: { + quote: "'", + alternateQuote: "\"", + description: "singlequote" + }, + backtick: { + quote: "`", + alternateQuote: "\"", + description: "backtick" + } +}; + +// An unescaped newline is a newline preceded by an even number of backslashes. +const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`, "u"); + +/** + * Switches quoting of javascript string between ' " and ` + * escaping and unescaping as necessary. + * Only escaping of the minimal set of characters is changed. + * Note: escaping of newlines when switching from backtick to other quotes is not handled. + * @param {string} str A string to convert. + * @returns {string} The string with changed quotes. + * @private + */ +QUOTE_SETTINGS.double.convert = +QUOTE_SETTINGS.single.convert = +QUOTE_SETTINGS.backtick.convert = function(str) { + const newQuote = this.quote; + const oldQuote = str[0]; + + if (newQuote === oldQuote) { + return str; + } + return newQuote + str.slice(1, -1).replace(/\\(\$\{|\r\n?|\n|.)|["'`]|\$\{|(\r\n?|\n)/gu, (match, escaped, newline) => { + if (escaped === oldQuote || oldQuote === "`" && escaped === "${") { + return escaped; // unescape + } + if (match === newQuote || newQuote === "`" && match === "${") { + return `\\${match}`; // escape + } + if (newline && oldQuote === "`") { + return "\\n"; // escape newlines + } + return match; + }) + newQuote; +}; + +const AVOID_ESCAPE = "avoid-escape"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce the consistent use of either backticks, double, or single quotes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/quotes" + }, + + fixable: "code", + + schema: [ + { + enum: ["single", "double", "backtick"] + }, + { + anyOf: [ + { + enum: ["avoid-escape"] + }, + { + type: "object", + properties: { + avoidEscape: { + type: "boolean" + }, + allowTemplateLiterals: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + wrongQuotes: "Strings must use {{description}}." + } + }, + + create(context) { + + const quoteOption = context.options[0], + settings = QUOTE_SETTINGS[quoteOption || "double"], + options = context.options[1], + allowTemplateLiterals = options && options.allowTemplateLiterals === true, + sourceCode = context.sourceCode; + let avoidEscape = options && options.avoidEscape === true; + + // deprecated + if (options === AVOID_ESCAPE) { + avoidEscape = true; + } + + /** + * Determines if a given node is part of JSX syntax. + * + * This function returns `true` in the following cases: + * + * - `
` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`. + * - `
foo
` ... If the literal is a text content, the parent of the literal is `JSXElement`. + * - `<>foo` ... If the literal is a text content, the parent of the literal is `JSXFragment`. + * + * In particular, this function returns `false` in the following cases: + * + * - `
` + * - `
{"foo"}
` + * + * In both cases, inside of the braces is handled as normal JavaScript. + * The braces are `JSXExpressionContainer` nodes. + * @param {ASTNode} node The Literal node to check. + * @returns {boolean} True if the node is a part of JSX, false if not. + * @private + */ + function isJSXLiteral(node) { + return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment"; + } + + /** + * Checks whether or not a given node is a directive. + * The directive is a `ExpressionStatement` which has only a string literal not surrounded by + * parentheses. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a directive. + * @private + */ + function isDirective(node) { + return ( + node.type === "ExpressionStatement" && + node.expression.type === "Literal" && + typeof node.expression.value === "string" && + !astUtils.isParenthesised(sourceCode, node.expression) + ); + } + + /** + * Checks whether a specified node is either part of, or immediately follows a (possibly empty) directive prologue. + * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive} + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether a specified node is either part of, or immediately follows a (possibly empty) directive prologue. + * @private + */ + function isExpressionInOrJustAfterDirectivePrologue(node) { + if (!astUtils.isTopLevelExpressionStatement(node.parent)) { + return false; + } + const block = node.parent.parent; + + // Check the node is at a prologue. + for (let i = 0; i < block.body.length; ++i) { + const statement = block.body[i]; + + if (statement === node.parent) { + return true; + } + if (!isDirective(statement)) { + break; + } + } + + return false; + } + + /** + * Checks whether or not a given node is allowed as non backtick. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is allowed as non backtick. + * @private + */ + function isAllowedAsNonBacktick(node) { + const parent = node.parent; + + switch (parent.type) { + + // Directive Prologues. + case "ExpressionStatement": + return !astUtils.isParenthesised(sourceCode, node) && isExpressionInOrJustAfterDirectivePrologue(node); + + // LiteralPropertyName. + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return parent.key === node && !parent.computed; + + // ModuleSpecifier. + case "ImportDeclaration": + case "ExportNamedDeclaration": + return parent.source === node; + + // ModuleExportName or ModuleSpecifier. + case "ExportAllDeclaration": + return parent.exported === node || parent.source === node; + + // ModuleExportName. + case "ImportSpecifier": + return parent.imported === node; + + // ModuleExportName. + case "ExportSpecifier": + return parent.local === node || parent.exported === node; + + // Others don't allow. + default: + return false; + } + } + + /** + * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings. + * @param {ASTNode} node A TemplateLiteral node to check. + * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings. + * @private + */ + function isUsingFeatureOfTemplateLiteral(node) { + const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi; + + if (hasTag) { + return true; + } + + const hasStringInterpolation = node.expressions.length > 0; + + if (hasStringInterpolation) { + return true; + } + + const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw); + + if (isMultilineString) { + return true; + } + + return false; + } + + return { + + Literal(node) { + const val = node.value, + rawVal = node.raw; + + if (settings && typeof val === "string") { + let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) || + isJSXLiteral(node) || + astUtils.isSurroundedBy(rawVal, settings.quote); + + if (!isValid && avoidEscape) { + isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.includes(settings.quote); + } + + if (!isValid) { + context.report({ + node, + messageId: "wrongQuotes", + data: { + description: settings.description + }, + fix(fixer) { + if (quoteOption === "backtick" && astUtils.hasOctalOrNonOctalDecimalEscapeSequence(rawVal)) { + + /* + * An octal or non-octal decimal escape sequence in a template literal would + * produce syntax error, even in non-strict mode. + */ + return null; + } + + return fixer.replaceText(node, settings.convert(node.raw)); + } + }); + } + } + }, + + TemplateLiteral(node) { + + // Don't throw an error if backticks are expected or a template literal feature is in use. + if ( + allowTemplateLiterals || + quoteOption === "backtick" || + isUsingFeatureOfTemplateLiteral(node) + ) { + return; + } + + context.report({ + node, + messageId: "wrongQuotes", + data: { + description: settings.description + }, + fix(fixer) { + if (astUtils.isTopLevelExpressionStatement(node.parent) && !astUtils.isParenthesised(sourceCode, node)) { + + /* + * TemplateLiterals aren't actually directives, but fixing them might turn + * them into directives and change the behavior of the code. + */ + return null; + } + return fixer.replaceText(node, settings.convert(sourceCode.getText(node))); + } + }); + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/radix.js b/node_modules/eslint/lib/rules/radix.js new file mode 100644 index 0000000..7df97d9 --- /dev/null +++ b/node_modules/eslint/lib/rules/radix.js @@ -0,0 +1,198 @@ +/** + * @fileoverview Rule to flag use of parseInt without a radix argument + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const MODE_ALWAYS = "always", + MODE_AS_NEEDED = "as-needed"; + +const validRadixValues = new Set(Array.from({ length: 37 - 2 }, (_, index) => index + 2)); + +/** + * Checks whether a given variable is shadowed or not. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is shadowed. + */ +function isShadowed(variable) { + return variable.defs.length >= 1; +} + +/** + * Checks whether a given node is a MemberExpression of `parseInt` method or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a MemberExpression of `parseInt` + * method. + */ +function isParseIntMethod(node) { + return ( + node.type === "MemberExpression" && + !node.computed && + node.property.type === "Identifier" && + node.property.name === "parseInt" + ); +} + +/** + * Checks whether a given node is a valid value of radix or not. + * + * The following values are invalid. + * + * - A literal except integers between 2 and 36. + * - undefined. + * @param {ASTNode} radix A node of radix to check. + * @returns {boolean} `true` if the node is valid. + */ +function isValidRadix(radix) { + return !( + (radix.type === "Literal" && !validRadixValues.has(radix.value)) || + (radix.type === "Identifier" && radix.name === "undefined") + ); +} + +/** + * Checks whether a given node is a default value of radix or not. + * @param {ASTNode} radix A node of radix to check. + * @returns {boolean} `true` if the node is the literal node of `10`. + */ +function isDefaultRadix(radix) { + return radix.type === "Literal" && radix.value === 10; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce the consistent use of the radix argument when using `parseInt()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/radix" + }, + + hasSuggestions: true, + + schema: [ + { + enum: ["always", "as-needed"] + } + ], + + messages: { + missingParameters: "Missing parameters.", + redundantRadix: "Redundant radix parameter.", + missingRadix: "Missing radix parameter.", + invalidRadix: "Invalid radix parameter, must be an integer between 2 and 36.", + addRadixParameter10: "Add radix parameter `10` for parsing decimal numbers." + } + }, + + create(context) { + const mode = context.options[0] || MODE_ALWAYS; + const sourceCode = context.sourceCode; + + /** + * Checks the arguments of a given CallExpression node and reports it if it + * offends this rule. + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + function checkArguments(node) { + const args = node.arguments; + + switch (args.length) { + case 0: + context.report({ + node, + messageId: "missingParameters" + }); + break; + + case 1: + if (mode === MODE_ALWAYS) { + context.report({ + node, + messageId: "missingRadix", + suggest: [ + { + messageId: "addRadixParameter10", + fix(fixer) { + const tokens = sourceCode.getTokens(node); + const lastToken = tokens[tokens.length - 1]; // Parenthesis. + const secondToLastToken = tokens[tokens.length - 2]; // May or may not be a comma. + const hasTrailingComma = secondToLastToken.type === "Punctuator" && secondToLastToken.value === ","; + + return fixer.insertTextBefore(lastToken, hasTrailingComma ? " 10," : ", 10"); + } + } + ] + }); + } + break; + + default: + if (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) { + context.report({ + node, + messageId: "redundantRadix" + }); + } else if (!isValidRadix(args[1])) { + context.report({ + node, + messageId: "invalidRadix" + }); + } + break; + } + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + let variable; + + // Check `parseInt()` + variable = astUtils.getVariableByName(scope, "parseInt"); + if (variable && !isShadowed(variable)) { + variable.references.forEach(reference => { + const idNode = reference.identifier; + + if (astUtils.isCallee(idNode)) { + checkArguments(idNode.parent); + } + }); + } + + // Check `Number.parseInt()` + variable = astUtils.getVariableByName(scope, "Number"); + if (variable && !isShadowed(variable)) { + variable.references.forEach(reference => { + const parentNode = reference.identifier.parent; + const maybeCallee = parentNode.parent.type === "ChainExpression" + ? parentNode.parent + : parentNode; + + if (isParseIntMethod(parentNode) && astUtils.isCallee(maybeCallee)) { + checkArguments(maybeCallee.parent); + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/require-atomic-updates.js b/node_modules/eslint/lib/rules/require-atomic-updates.js new file mode 100644 index 0000000..ba369a2 --- /dev/null +++ b/node_modules/eslint/lib/rules/require-atomic-updates.js @@ -0,0 +1,317 @@ +/** + * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield` + * @author Teddy Katz + * @author Toru Nagashima + */ +"use strict"; + +/** + * Make the map from identifiers to each reference. + * @param {escope.Scope} scope The scope to get references. + * @param {Map} [outReferenceMap] The map from identifier nodes to each reference object. + * @returns {Map} `referenceMap`. + */ +function createReferenceMap(scope, outReferenceMap = new Map()) { + for (const reference of scope.references) { + if (reference.resolved === null) { + continue; + } + + outReferenceMap.set(reference.identifier, reference); + } + for (const childScope of scope.childScopes) { + if (childScope.type !== "function") { + createReferenceMap(childScope, outReferenceMap); + } + } + + return outReferenceMap; +} + +/** + * Get `reference.writeExpr` of a given reference. + * If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a` + * @param {escope.Reference} reference The reference to get. + * @returns {Expression|null} The `reference.writeExpr`. + */ +function getWriteExpr(reference) { + if (reference.writeExpr) { + return reference.writeExpr; + } + let node = reference.identifier; + + while (node) { + const t = node.parent.type; + + if (t === "AssignmentExpression" && node.parent.left === node) { + return node.parent.right; + } + if (t === "MemberExpression" && node.parent.object === node) { + node = node.parent; + continue; + } + + break; + } + + return null; +} + +/** + * Checks if an expression is a variable that can only be observed within the given function. + * @param {Variable|null} variable The variable to check + * @param {boolean} isMemberAccess If `true` then this is a member access. + * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure. + */ +function isLocalVariableWithoutEscape(variable, isMemberAccess) { + if (!variable) { + return false; // A global variable which was not defined. + } + + // If the reference is a property access and the variable is a parameter, it handles the variable is not local. + if (isMemberAccess && variable.defs.some(d => d.type === "Parameter")) { + return false; + } + + const functionScope = variable.scope.variableScope; + + return variable.references.every(reference => + reference.from.variableScope === functionScope); +} + +/** + * Represents segment information. + */ +class SegmentInfo { + constructor() { + this.info = new WeakMap(); + } + + /** + * Initialize the segment information. + * @param {PathSegment} segment The segment to initialize. + * @returns {void} + */ + initialize(segment) { + const outdatedReadVariables = new Set(); + const freshReadVariables = new Set(); + + for (const prevSegment of segment.prevSegments) { + const info = this.info.get(prevSegment); + + if (info) { + info.outdatedReadVariables.forEach(Set.prototype.add, outdatedReadVariables); + info.freshReadVariables.forEach(Set.prototype.add, freshReadVariables); + } + } + + this.info.set(segment, { outdatedReadVariables, freshReadVariables }); + } + + /** + * Mark a given variable as read on given segments. + * @param {PathSegment[]} segments The segments that it read the variable on. + * @param {Variable} variable The variable to be read. + * @returns {void} + */ + markAsRead(segments, variable) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info) { + info.freshReadVariables.add(variable); + + // If a variable is freshly read again, then it's no more out-dated. + info.outdatedReadVariables.delete(variable); + } + } + } + + /** + * Move `freshReadVariables` to `outdatedReadVariables`. + * @param {PathSegment[]} segments The segments to process. + * @returns {void} + */ + makeOutdated(segments) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info) { + info.freshReadVariables.forEach(Set.prototype.add, info.outdatedReadVariables); + info.freshReadVariables.clear(); + } + } + } + + /** + * Check if a given variable is outdated on the current segments. + * @param {PathSegment[]} segments The current segments. + * @param {Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is outdated on the segments. + */ + isOutdated(segments, variable) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info && info.outdatedReadVariables.has(variable)) { + return true; + } + } + return false; + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow assignments that can lead to race conditions due to usage of `await` or `yield`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-atomic-updates" + }, + + fixable: null, + + schema: [{ + type: "object", + properties: { + allowProperties: { + type: "boolean", + default: false + } + }, + additionalProperties: false + }], + + messages: { + nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`.", + nonAtomicObjectUpdate: "Possible race condition: `{{value}}` might be assigned based on an outdated state of `{{object}}`." + } + }, + + create(context) { + const allowProperties = !!context.options[0] && context.options[0].allowProperties; + + const sourceCode = context.sourceCode; + const assignmentReferences = new Map(); + const segmentInfo = new SegmentInfo(); + let stack = null; + + return { + onCodePathStart(codePath, node) { + const scope = sourceCode.getScope(node); + const shouldVerify = + scope.type === "function" && + (scope.block.async || scope.block.generator); + + stack = { + upper: stack, + codePath, + referenceMap: shouldVerify ? createReferenceMap(scope) : null + }; + }, + onCodePathEnd() { + stack = stack.upper; + }, + + // Initialize the segment information. + onCodePathSegmentStart(segment) { + segmentInfo.initialize(segment); + }, + + // Handle references to prepare verification. + Identifier(node) { + const { codePath, referenceMap } = stack; + const reference = referenceMap && referenceMap.get(node); + + // Ignore if this is not a valid variable reference. + if (!reference) { + return; + } + const variable = reference.resolved; + const writeExpr = getWriteExpr(reference); + const isMemberAccess = reference.identifier.parent.type === "MemberExpression"; + + // Add a fresh read variable. + if (reference.isRead() && !(writeExpr && writeExpr.parent.operator === "=")) { + segmentInfo.markAsRead(codePath.currentSegments, variable); + } + + /* + * Register the variable to verify after ESLint traversed the `writeExpr` node + * if this reference is an assignment to a variable which is referred from other closure. + */ + if (writeExpr && + writeExpr.parent.right === writeExpr && // ← exclude variable declarations. + !isLocalVariableWithoutEscape(variable, isMemberAccess) + ) { + let refs = assignmentReferences.get(writeExpr); + + if (!refs) { + refs = []; + assignmentReferences.set(writeExpr, refs); + } + + refs.push(reference); + } + }, + + /* + * Verify assignments. + * If the reference exists in `outdatedReadVariables` list, report it. + */ + ":expression:exit"(node) { + const { codePath, referenceMap } = stack; + + // referenceMap exists if this is in a resumable function scope. + if (!referenceMap) { + return; + } + + // Mark the read variables on this code path as outdated. + if (node.type === "AwaitExpression" || node.type === "YieldExpression") { + segmentInfo.makeOutdated(codePath.currentSegments); + } + + // Verify. + const references = assignmentReferences.get(node); + + if (references) { + assignmentReferences.delete(node); + + for (const reference of references) { + const variable = reference.resolved; + + if (segmentInfo.isOutdated(codePath.currentSegments, variable)) { + if (node.parent.left === reference.identifier) { + context.report({ + node: node.parent, + messageId: "nonAtomicUpdate", + data: { + value: variable.name + } + }); + } else if (!allowProperties) { + context.report({ + node: node.parent, + messageId: "nonAtomicObjectUpdate", + data: { + value: sourceCode.getText(node.parent.left), + object: variable.name + } + }); + } + + } + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/require-await.js b/node_modules/eslint/lib/rules/require-await.js new file mode 100644 index 0000000..952dde5 --- /dev/null +++ b/node_modules/eslint/lib/rules/require-await.js @@ -0,0 +1,113 @@ +/** + * @fileoverview Rule to disallow async functions which have no `await` expression. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Capitalize the 1st letter of the given text. + * @param {string} text The text to capitalize. + * @returns {string} The text that the 1st letter was capitalized. + */ +function capitalizeFirstLetter(text) { + return text[0].toUpperCase() + text.slice(1); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow async functions which have no `await` expression", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-await" + }, + + schema: [], + + messages: { + missingAwait: "{{name}} has no 'await' expression." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Push the scope info object to the stack. + * @returns {void} + */ + function enterFunction() { + scopeInfo = { + upper: scopeInfo, + hasAwait: false + }; + } + + /** + * Pop the top scope info object from the stack. + * Also, it reports the function if needed. + * @param {ASTNode} node The node to report. + * @returns {void} + */ + function exitFunction(node) { + if (!node.generator && node.async && !scopeInfo.hasAwait && !astUtils.isEmptyFunction(node)) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: "missingAwait", + data: { + name: capitalizeFirstLetter( + astUtils.getFunctionNameWithKind(node) + ) + } + }); + } + + scopeInfo = scopeInfo.upper; + } + + return { + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression: enterFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + AwaitExpression() { + if (!scopeInfo) { + return; + } + + scopeInfo.hasAwait = true; + }, + ForOfStatement(node) { + if (!scopeInfo) { + return; + } + + if (node.await) { + scopeInfo.hasAwait = true; + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/require-jsdoc.js b/node_modules/eslint/lib/rules/require-jsdoc.js new file mode 100644 index 0000000..b6fedf2 --- /dev/null +++ b/node_modules/eslint/lib/rules/require-jsdoc.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Rule to check for jsdoc presence. + * @author Gyandeep Singh + * @deprecated in ESLint v5.10.0 + */ +"use strict"; + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require JSDoc comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-jsdoc" + }, + + schema: [ + { + type: "object", + properties: { + require: { + type: "object", + properties: { + ClassDeclaration: { + type: "boolean", + default: false + }, + MethodDefinition: { + type: "boolean", + default: false + }, + FunctionDeclaration: { + type: "boolean", + default: true + }, + ArrowFunctionExpression: { + type: "boolean", + default: false + }, + FunctionExpression: { + type: "boolean", + default: false + } + }, + additionalProperties: false, + default: {} + } + }, + additionalProperties: false + } + ], + + deprecated: true, + replacedBy: [], + + messages: { + missingJSDocComment: "Missing JSDoc comment." + } + }, + + create(context) { + const source = context.sourceCode; + const DEFAULT_OPTIONS = { + FunctionDeclaration: true, + MethodDefinition: false, + ClassDeclaration: false, + ArrowFunctionExpression: false, + FunctionExpression: false + }; + const options = Object.assign(DEFAULT_OPTIONS, context.options[0] && context.options[0].require); + + /** + * Report the error message + * @param {ASTNode} node node to report + * @returns {void} + */ + function report(node) { + context.report({ node, messageId: "missingJSDocComment" }); + } + + /** + * Check if the jsdoc comment is present or not. + * @param {ASTNode} node node to examine + * @returns {void} + */ + function checkJsDoc(node) { + const jsdocComment = source.getJSDocComment(node); + + if (!jsdocComment) { + report(node); + } + } + + return { + FunctionDeclaration(node) { + if (options.FunctionDeclaration) { + checkJsDoc(node); + } + }, + FunctionExpression(node) { + if ( + (options.MethodDefinition && node.parent.type === "MethodDefinition") || + (options.FunctionExpression && (node.parent.type === "VariableDeclarator" || (node.parent.type === "Property" && node === node.parent.value))) + ) { + checkJsDoc(node); + } + }, + ClassDeclaration(node) { + if (options.ClassDeclaration) { + checkJsDoc(node); + } + }, + ArrowFunctionExpression(node) { + if (options.ArrowFunctionExpression && node.parent.type === "VariableDeclarator") { + checkJsDoc(node); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/require-unicode-regexp.js b/node_modules/eslint/lib/rules/require-unicode-regexp.js new file mode 100644 index 0000000..dd687f8 --- /dev/null +++ b/node_modules/eslint/lib/rules/require-unicode-regexp.js @@ -0,0 +1,129 @@ +/** + * @fileoverview Rule to enforce the use of `u` flag on RegExp. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStringIfConstant +} = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils.js"); +const { isValidWithUnicodeFlag } = require("./utils/regular-expressions"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce the use of `u` or `v` flag on RegExp", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-unicode-regexp" + }, + + hasSuggestions: true, + + messages: { + addUFlag: "Add the 'u' flag.", + requireUFlag: "Use the 'u' flag." + }, + + schema: [] + }, + + create(context) { + + const sourceCode = context.sourceCode; + + return { + "Literal[regex]"(node) { + const flags = node.regex.flags || ""; + + if (!flags.includes("u") && !flags.includes("v")) { + context.report({ + messageId: "requireUFlag", + node, + suggest: isValidWithUnicodeFlag(context.languageOptions.ecmaVersion, node.regex.pattern) + ? [ + { + fix(fixer) { + return fixer.insertTextAfter(node, "u"); + }, + messageId: "addUFlag" + } + ] + : null + }); + } + }, + + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + RegExp: { [CALL]: true, [CONSTRUCT]: true } + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences(trackMap)) { + const [patternNode, flagsNode] = refNode.arguments; + + if (patternNode && patternNode.type === "SpreadElement") { + continue; + } + const pattern = getStringIfConstant(patternNode, scope); + const flags = getStringIfConstant(flagsNode, scope); + + if (!flagsNode || (typeof flags === "string" && !flags.includes("u") && !flags.includes("v"))) { + context.report({ + messageId: "requireUFlag", + node: refNode, + suggest: typeof pattern === "string" && isValidWithUnicodeFlag(context.languageOptions.ecmaVersion, pattern) + ? [ + { + fix(fixer) { + if (flagsNode) { + if ((flagsNode.type === "Literal" && typeof flagsNode.value === "string") || flagsNode.type === "TemplateLiteral") { + const flagsNodeText = sourceCode.getText(flagsNode); + + return fixer.replaceText(flagsNode, [ + flagsNodeText.slice(0, flagsNodeText.length - 1), + flagsNodeText.slice(flagsNodeText.length - 1) + ].join("u")); + } + + // We intentionally don't suggest concatenating + "u" to non-literals + return null; + } + + const penultimateToken = sourceCode.getLastToken(refNode, { skip: 1 }); // skip closing parenthesis + + return fixer.insertTextAfter( + penultimateToken, + astUtils.isCommaToken(penultimateToken) + ? ' "u",' + : ', "u"' + ); + }, + messageId: "addUFlag" + } + ] + : null + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/require-yield.js b/node_modules/eslint/lib/rules/require-yield.js new file mode 100644 index 0000000..f801af0 --- /dev/null +++ b/node_modules/eslint/lib/rules/require-yield.js @@ -0,0 +1,77 @@ +/** + * @fileoverview Rule to flag the generator functions that does not have yield. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require generator functions to contain `yield`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/require-yield" + }, + + schema: [], + + messages: { + missingYield: "This generator function does not have 'yield'." + } + }, + + create(context) { + const stack = []; + + /** + * If the node is a generator function, start counting `yield` keywords. + * @param {Node} node A function node to check. + * @returns {void} + */ + function beginChecking(node) { + if (node.generator) { + stack.push(0); + } + } + + /** + * If the node is a generator function, end counting `yield` keywords, then + * reports result. + * @param {Node} node A function node to check. + * @returns {void} + */ + function endChecking(node) { + if (!node.generator) { + return; + } + + const countYield = stack.pop(); + + if (countYield === 0 && node.body.body.length > 0) { + context.report({ node, messageId: "missingYield" }); + } + } + + return { + FunctionDeclaration: beginChecking, + "FunctionDeclaration:exit": endChecking, + FunctionExpression: beginChecking, + "FunctionExpression:exit": endChecking, + + // Increases the count of `yield` keyword. + YieldExpression() { + + if (stack.length > 0) { + stack[stack.length - 1] += 1; + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/rest-spread-spacing.js b/node_modules/eslint/lib/rules/rest-spread-spacing.js new file mode 100644 index 0000000..7791238 --- /dev/null +++ b/node_modules/eslint/lib/rules/rest-spread-spacing.js @@ -0,0 +1,120 @@ +/** + * @fileoverview Enforce spacing between rest and spread operators and their expressions. + * @author Kai Cataldo + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce spacing between rest and spread operators and their expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/rest-spread-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"] + } + ], + + messages: { + unexpectedWhitespace: "Unexpected whitespace after {{type}} operator.", + expectedWhitespace: "Expected whitespace after {{type}} operator." + } + }, + + create(context) { + const sourceCode = context.sourceCode, + alwaysSpace = context.options[0] === "always"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whitespace between rest/spread operators and their expressions + * @param {ASTNode} node The node to check + * @returns {void} + */ + function checkWhiteSpace(node) { + const operator = sourceCode.getFirstToken(node), + nextToken = sourceCode.getTokenAfter(operator), + hasWhitespace = sourceCode.isSpaceBetweenTokens(operator, nextToken); + let type; + + switch (node.type) { + case "SpreadElement": + type = "spread"; + if (node.parent.type === "ObjectExpression") { + type += " property"; + } + break; + case "RestElement": + type = "rest"; + if (node.parent.type === "ObjectPattern") { + type += " property"; + } + break; + case "ExperimentalSpreadProperty": + type = "spread property"; + break; + case "ExperimentalRestProperty": + type = "rest property"; + break; + default: + return; + } + + if (alwaysSpace && !hasWhitespace) { + context.report({ + node, + loc: operator.loc, + messageId: "expectedWhitespace", + data: { + type + }, + fix(fixer) { + return fixer.replaceTextRange([operator.range[1], nextToken.range[0]], " "); + } + }); + } else if (!alwaysSpace && hasWhitespace) { + context.report({ + node, + loc: { + start: operator.loc.end, + end: nextToken.loc.start + }, + messageId: "unexpectedWhitespace", + data: { + type + }, + fix(fixer) { + return fixer.removeRange([operator.range[1], nextToken.range[0]]); + } + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + SpreadElement: checkWhiteSpace, + RestElement: checkWhiteSpace, + ExperimentalSpreadProperty: checkWhiteSpace, + ExperimentalRestProperty: checkWhiteSpace + }; + } +}; diff --git a/node_modules/eslint/lib/rules/semi-spacing.js b/node_modules/eslint/lib/rules/semi-spacing.js new file mode 100644 index 0000000..770f62d --- /dev/null +++ b/node_modules/eslint/lib/rules/semi-spacing.js @@ -0,0 +1,245 @@ +/** + * @fileoverview Validates spacing before and after semicolon + * @author Mathias Schreck + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing before and after semicolons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: false + }, + after: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedWhitespaceBefore: "Unexpected whitespace before semicolon.", + unexpectedWhitespaceAfter: "Unexpected whitespace after semicolon.", + missingWhitespaceBefore: "Missing whitespace before semicolon.", + missingWhitespaceAfter: "Missing whitespace after semicolon." + } + }, + + create(context) { + + const config = context.options[0], + sourceCode = context.sourceCode; + let requireSpaceBefore = false, + requireSpaceAfter = true; + + if (typeof config === "object") { + requireSpaceBefore = config.before; + requireSpaceAfter = config.after; + } + + /** + * Checks if a given token has leading whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has leading space, false if not. + */ + function hasLeadingSpace(token) { + const tokenBefore = sourceCode.getTokenBefore(token); + + return tokenBefore && astUtils.isTokenOnSameLine(tokenBefore, token) && sourceCode.isSpaceBetweenTokens(tokenBefore, token); + } + + /** + * Checks if a given token has trailing whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has trailing space, false if not. + */ + function hasTrailingSpace(token) { + const tokenAfter = sourceCode.getTokenAfter(token); + + return tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) && sourceCode.isSpaceBetweenTokens(token, tokenAfter); + } + + /** + * Checks if the given token is the last token in its line. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is the last in its line. + */ + function isLastTokenInCurrentLine(token) { + const tokenAfter = sourceCode.getTokenAfter(token); + + return !(tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter)); + } + + /** + * Checks if the given token is the first token in its line + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is the first in its line. + */ + function isFirstTokenInCurrentLine(token) { + const tokenBefore = sourceCode.getTokenBefore(token); + + return !(tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore)); + } + + /** + * Checks if the next token of a given token is a closing parenthesis. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the next token of a given token is a closing parenthesis. + */ + function isBeforeClosingParen(token) { + const nextToken = sourceCode.getTokenAfter(token); + + return (nextToken && astUtils.isClosingBraceToken(nextToken) || astUtils.isClosingParenToken(nextToken)); + } + + /** + * Report location example : + * + * for unexpected space `before` + * + * var a = 'b' ; + * ^^^ + * + * for unexpected space `after` + * + * var a = 'b'; c = 10; + * ^^ + * + * Reports if the given token has invalid spacing. + * @param {Token} token The semicolon token to check. + * @param {ASTNode} node The corresponding node of the token. + * @returns {void} + */ + function checkSemicolonSpacing(token, node) { + if (astUtils.isSemicolonToken(token)) { + if (hasLeadingSpace(token)) { + if (!requireSpaceBefore) { + const tokenBefore = sourceCode.getTokenBefore(token); + const loc = { + start: tokenBefore.loc.end, + end: token.loc.start + }; + + context.report({ + node, + loc, + messageId: "unexpectedWhitespaceBefore", + fix(fixer) { + + return fixer.removeRange([tokenBefore.range[1], token.range[0]]); + } + }); + } + } else { + if (requireSpaceBefore) { + const loc = token.loc; + + context.report({ + node, + loc, + messageId: "missingWhitespaceBefore", + fix(fixer) { + return fixer.insertTextBefore(token, " "); + } + }); + } + } + + if (!isFirstTokenInCurrentLine(token) && !isLastTokenInCurrentLine(token) && !isBeforeClosingParen(token)) { + if (hasTrailingSpace(token)) { + if (!requireSpaceAfter) { + const tokenAfter = sourceCode.getTokenAfter(token); + const loc = { + start: token.loc.end, + end: tokenAfter.loc.start + }; + + context.report({ + node, + loc, + messageId: "unexpectedWhitespaceAfter", + fix(fixer) { + + return fixer.removeRange([token.range[1], tokenAfter.range[0]]); + } + }); + } + } else { + if (requireSpaceAfter) { + const loc = token.loc; + + context.report({ + node, + loc, + messageId: "missingWhitespaceAfter", + fix(fixer) { + return fixer.insertTextAfter(token, " "); + } + }); + } + } + } + } + } + + /** + * Checks the spacing of the semicolon with the assumption that the last token is the semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNode(node) { + const token = sourceCode.getLastToken(node); + + checkSemicolonSpacing(token, node); + } + + return { + VariableDeclaration: checkNode, + ExpressionStatement: checkNode, + BreakStatement: checkNode, + ContinueStatement: checkNode, + DebuggerStatement: checkNode, + DoWhileStatement: checkNode, + ReturnStatement: checkNode, + ThrowStatement: checkNode, + ImportDeclaration: checkNode, + ExportNamedDeclaration: checkNode, + ExportAllDeclaration: checkNode, + ExportDefaultDeclaration: checkNode, + ForStatement(node) { + if (node.init) { + checkSemicolonSpacing(sourceCode.getTokenAfter(node.init), node); + } + + if (node.test) { + checkSemicolonSpacing(sourceCode.getTokenAfter(node.test), node); + } + }, + PropertyDefinition: checkNode + }; + } +}; diff --git a/node_modules/eslint/lib/rules/semi-style.js b/node_modules/eslint/lib/rules/semi-style.js new file mode 100644 index 0000000..67ed1e4 --- /dev/null +++ b/node_modules/eslint/lib/rules/semi-style.js @@ -0,0 +1,155 @@ +/** + * @fileoverview Rule to enforce location of semicolons. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const SELECTOR = [ + "BreakStatement", "ContinueStatement", "DebuggerStatement", + "DoWhileStatement", "ExportAllDeclaration", + "ExportDefaultDeclaration", "ExportNamedDeclaration", + "ExpressionStatement", "ImportDeclaration", "ReturnStatement", + "ThrowStatement", "VariableDeclaration", "PropertyDefinition" +].join(","); + +/** + * Get the child node list of a given node. + * This returns `BlockStatement#body`, `StaticBlock#body`, `Program#body`, + * `ClassBody#body`, or `SwitchCase#consequent`. + * This is used to check whether a node is the first/last child. + * @param {Node} node A node to get child node list. + * @returns {Node[]|null} The child node list. + */ +function getChildren(node) { + const t = node.type; + + if ( + t === "BlockStatement" || + t === "StaticBlock" || + t === "Program" || + t === "ClassBody" + ) { + return node.body; + } + if (t === "SwitchCase") { + return node.consequent; + } + return null; +} + +/** + * Check whether a given node is the last statement in the parent block. + * @param {Node} node A node to check. + * @returns {boolean} `true` if the node is the last statement in the parent block. + */ +function isLastChild(node) { + const t = node.parent.type; + + if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword. + return true; + } + if (t === "DoWhileStatement") { // before `while` keyword. + return true; + } + const nodeList = getChildren(node.parent); + + return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc. +} + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce location of semicolons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi-style" + }, + + schema: [{ enum: ["last", "first"] }], + fixable: "whitespace", + + messages: { + expectedSemiColon: "Expected this semicolon to be at {{pos}}." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "last"; + + /** + * Check the given semicolon token. + * @param {Token} semiToken The semicolon token to check. + * @param {"first"|"last"} expected The expected location to check. + * @returns {void} + */ + function check(semiToken, expected) { + const prevToken = sourceCode.getTokenBefore(semiToken); + const nextToken = sourceCode.getTokenAfter(semiToken); + const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken); + const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken); + + if ((expected === "last" && !prevIsSameLine) || (expected === "first" && !nextIsSameLine)) { + context.report({ + loc: semiToken.loc, + messageId: "expectedSemiColon", + data: { + pos: (expected === "last") + ? "the end of the previous line" + : "the beginning of the next line" + }, + fix(fixer) { + if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) { + return null; + } + + const start = prevToken ? prevToken.range[1] : semiToken.range[0]; + const end = nextToken ? nextToken.range[0] : semiToken.range[1]; + const text = (expected === "last") ? ";\n" : "\n;"; + + return fixer.replaceTextRange([start, end], text); + } + }); + } + } + + return { + [SELECTOR](node) { + if (option === "first" && isLastChild(node)) { + return; + } + + const lastToken = sourceCode.getLastToken(node); + + if (astUtils.isSemicolonToken(lastToken)) { + check(lastToken, option); + } + }, + + ForStatement(node) { + const firstSemi = node.init && sourceCode.getTokenAfter(node.init, astUtils.isSemicolonToken); + const secondSemi = node.test && sourceCode.getTokenAfter(node.test, astUtils.isSemicolonToken); + + if (firstSemi) { + check(firstSemi, "last"); + } + if (secondSemi) { + check(secondSemi, "last"); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/semi.js b/node_modules/eslint/lib/rules/semi.js new file mode 100644 index 0000000..6a47353 --- /dev/null +++ b/node_modules/eslint/lib/rules/semi.js @@ -0,0 +1,435 @@ +/** + * @fileoverview Rule to flag missing semicolons. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow semicolons instead of ASI", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi" + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["never"] + }, + { + type: "object", + properties: { + beforeStatementContinuationChars: { + enum: ["always", "any", "never"] + } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + }, + { + type: "array", + items: [ + { + enum: ["always"] + }, + { + type: "object", + properties: { + omitLastInOneLineBlock: { type: "boolean" }, + omitLastInOneLineClassBody: { type: "boolean" } + }, + additionalProperties: false + } + ], + minItems: 0, + maxItems: 2 + } + ] + }, + + messages: { + missingSemi: "Missing semicolon.", + extraSemi: "Extra semicolon." + } + }, + + create(context) { + + const OPT_OUT_PATTERN = /^[-[(/+`]/u; // One of [(/+-` + const unsafeClassFieldNames = new Set(["get", "set", "static"]); + const unsafeClassFieldFollowers = new Set(["*", "in", "instanceof"]); + const options = context.options[1]; + const never = context.options[0] === "never"; + const exceptOneLine = Boolean(options && options.omitLastInOneLineBlock); + const exceptOneLineClassBody = Boolean(options && options.omitLastInOneLineClassBody); + const beforeStatementContinuationChars = options && options.beforeStatementContinuationChars || "any"; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports a semicolon error with appropriate location and message. + * @param {ASTNode} node The node with an extra or missing semicolon. + * @param {boolean} missing True if the semicolon is missing. + * @returns {void} + */ + function report(node, missing) { + const lastToken = sourceCode.getLastToken(node); + let messageId, + fix, + loc; + + if (!missing) { + messageId = "missingSemi"; + loc = { + start: lastToken.loc.end, + end: astUtils.getNextLocation(sourceCode, lastToken.loc.end) + }; + fix = function(fixer) { + return fixer.insertTextAfter(lastToken, ";"); + }; + } else { + messageId = "extraSemi"; + loc = lastToken.loc; + fix = function(fixer) { + + /* + * Expand the replacement range to include the surrounding + * tokens to avoid conflicting with no-extra-semi. + * https://github.com/eslint/eslint/issues/7928 + */ + return new FixTracker(fixer, sourceCode) + .retainSurroundingTokens(lastToken) + .remove(lastToken); + }; + } + + context.report({ + node, + loc, + messageId, + fix + }); + + } + + /** + * Check whether a given semicolon token is redundant. + * @param {Token} semiToken A semicolon token to check. + * @returns {boolean} `true` if the next token is `;` or `}`. + */ + function isRedundantSemi(semiToken) { + const nextToken = sourceCode.getTokenAfter(semiToken); + + return ( + !nextToken || + astUtils.isClosingBraceToken(nextToken) || + astUtils.isSemicolonToken(nextToken) + ); + } + + /** + * Check whether a given token is the closing brace of an arrow function. + * @param {Token} lastToken A token to check. + * @returns {boolean} `true` if the token is the closing brace of an arrow function. + */ + function isEndOfArrowBlock(lastToken) { + if (!astUtils.isClosingBraceToken(lastToken)) { + return false; + } + const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]); + + return ( + node.type === "BlockStatement" && + node.parent.type === "ArrowFunctionExpression" + ); + } + + /** + * Checks if a given PropertyDefinition node followed by a semicolon + * can safely remove that semicolon. It is not to safe to remove if + * the class field name is "get", "set", or "static", or if + * followed by a generator method. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node cannot have the semicolon + * removed. + */ + function maybeClassFieldAsiHazard(node) { + + if (node.type !== "PropertyDefinition") { + return false; + } + + /* + * Computed property names and non-identifiers are always safe + * as they can be distinguished from keywords easily. + */ + const needsNameCheck = !node.computed && node.key.type === "Identifier"; + + /* + * Certain names are problematic unless they also have a + * a way to distinguish between keywords and property + * names. + */ + if (needsNameCheck && unsafeClassFieldNames.has(node.key.name)) { + + /* + * Special case: If the field name is `static`, + * it is only valid if the field is marked as static, + * so "static static" is okay but "static" is not. + */ + const isStaticStatic = node.static && node.key.name === "static"; + + /* + * For other unsafe names, we only care if there is no + * initializer. No initializer = hazard. + */ + if (!isStaticStatic && !node.value) { + return true; + } + } + + const followingToken = sourceCode.getTokenAfter(node); + + return unsafeClassFieldFollowers.has(followingToken.value); + } + + /** + * Check whether a given node is on the same line with the next token. + * @param {Node} node A statement node to check. + * @returns {boolean} `true` if the node is on the same line with the next token. + */ + function isOnSameLineWithNextToken(node) { + const prevToken = sourceCode.getLastToken(node, 1); + const nextToken = sourceCode.getTokenAfter(node); + + return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken); + } + + /** + * Check whether a given node can connect the next line if the next line is unreliable. + * @param {Node} node A statement node to check. + * @returns {boolean} `true` if the node can connect the next line. + */ + function maybeAsiHazardAfter(node) { + const t = node.type; + + if (t === "DoWhileStatement" || + t === "BreakStatement" || + t === "ContinueStatement" || + t === "DebuggerStatement" || + t === "ImportDeclaration" || + t === "ExportAllDeclaration" + ) { + return false; + } + if (t === "ReturnStatement") { + return Boolean(node.argument); + } + if (t === "ExportNamedDeclaration") { + return Boolean(node.declaration); + } + if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) { + return false; + } + + return true; + } + + /** + * Check whether a given token can connect the previous statement. + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`. + */ + function maybeAsiHazardBefore(token) { + return ( + Boolean(token) && + OPT_OUT_PATTERN.test(token.value) && + token.value !== "++" && + token.value !== "--" + ); + } + + /** + * Check if the semicolon of a given node is unnecessary, only true if: + * - next token is a valid statement divider (`;` or `}`). + * - next token is on a new line and the node is not connectable to the new line. + * @param {Node} node A statement node to check. + * @returns {boolean} whether the semicolon is unnecessary. + */ + function canRemoveSemicolon(node) { + if (isRedundantSemi(sourceCode.getLastToken(node))) { + return true; // `;;` or `;}` + } + if (maybeClassFieldAsiHazard(node)) { + return false; + } + if (isOnSameLineWithNextToken(node)) { + return false; // One liner. + } + + // continuation characters should not apply to class fields + if ( + node.type !== "PropertyDefinition" && + beforeStatementContinuationChars === "never" && + !maybeAsiHazardAfter(node) + ) { + return true; // ASI works. This statement doesn't connect to the next. + } + if (!maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) { + return true; // ASI works. The next token doesn't connect to this statement. + } + + return false; + } + + /** + * Checks a node to see if it's the last item in a one-liner block. + * Block is any `BlockStatement` or `StaticBlock` node. Block is a one-liner if its + * braces (and consequently everything between them) are on the same line. + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is the last item in a one-liner block. + */ + function isLastInOneLinerBlock(node) { + const parent = node.parent; + const nextToken = sourceCode.getTokenAfter(node); + + if (!nextToken || nextToken.value !== "}") { + return false; + } + + if (parent.type === "BlockStatement") { + return parent.loc.start.line === parent.loc.end.line; + } + + if (parent.type === "StaticBlock") { + const openingBrace = sourceCode.getFirstToken(parent, { skip: 1 }); // skip the `static` token + + return openingBrace.loc.start.line === parent.loc.end.line; + } + + return false; + } + + /** + * Checks a node to see if it's the last item in a one-liner `ClassBody` node. + * ClassBody is a one-liner if its braces (and consequently everything between them) are on the same line. + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is the last item in a one-liner ClassBody. + */ + function isLastInOneLinerClassBody(node) { + const parent = node.parent; + const nextToken = sourceCode.getTokenAfter(node); + + if (!nextToken || nextToken.value !== "}") { + return false; + } + + if (parent.type === "ClassBody") { + return parent.loc.start.line === parent.loc.end.line; + } + + return false; + } + + /** + * Checks a node to see if it's followed by a semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolon(node) { + const isSemi = astUtils.isSemicolonToken(sourceCode.getLastToken(node)); + + if (never) { + if (isSemi && canRemoveSemicolon(node)) { + report(node, true); + } else if ( + !isSemi && beforeStatementContinuationChars === "always" && + node.type !== "PropertyDefinition" && + maybeAsiHazardBefore(sourceCode.getTokenAfter(node)) + ) { + report(node); + } + } else { + const oneLinerBlock = (exceptOneLine && isLastInOneLinerBlock(node)); + const oneLinerClassBody = (exceptOneLineClassBody && isLastInOneLinerClassBody(node)); + const oneLinerBlockOrClassBody = oneLinerBlock || oneLinerClassBody; + + if (isSemi && oneLinerBlockOrClassBody) { + report(node, true); + } else if (!isSemi && !oneLinerBlockOrClassBody) { + report(node); + } + } + } + + /** + * Checks to see if there's a semicolon after a variable declaration. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolonForVariableDeclaration(node) { + const parent = node.parent; + + if ((parent.type !== "ForStatement" || parent.init !== node) && + (!/^For(?:In|Of)Statement/u.test(parent.type) || parent.left !== node) + ) { + checkForSemicolon(node); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForSemicolonForVariableDeclaration, + ExpressionStatement: checkForSemicolon, + ReturnStatement: checkForSemicolon, + ThrowStatement: checkForSemicolon, + DoWhileStatement: checkForSemicolon, + DebuggerStatement: checkForSemicolon, + BreakStatement: checkForSemicolon, + ContinueStatement: checkForSemicolon, + ImportDeclaration: checkForSemicolon, + ExportAllDeclaration: checkForSemicolon, + ExportNamedDeclaration(node) { + if (!node.declaration) { + checkForSemicolon(node); + } + }, + ExportDefaultDeclaration(node) { + if (!/(?:Class|Function)Declaration/u.test(node.declaration.type)) { + checkForSemicolon(node); + } + }, + PropertyDefinition: checkForSemicolon + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/sort-imports.js b/node_modules/eslint/lib/rules/sort-imports.js new file mode 100644 index 0000000..04814ed --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-imports.js @@ -0,0 +1,241 @@ +/** + * @fileoverview Rule to require sorting of import declarations + * @author Christian Schuller + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce sorted import declarations within modules", + recommended: false, + url: "https://eslint.org/docs/latest/rules/sort-imports" + }, + + schema: [ + { + type: "object", + properties: { + ignoreCase: { + type: "boolean", + default: false + }, + memberSyntaxSortOrder: { + type: "array", + items: { + enum: ["none", "all", "multiple", "single"] + }, + uniqueItems: true, + minItems: 4, + maxItems: 4 + }, + ignoreDeclarationSort: { + type: "boolean", + default: false + }, + ignoreMemberSort: { + type: "boolean", + default: false + }, + allowSeparatedGroups: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + fixable: "code", + + messages: { + sortImportsAlphabetically: "Imports should be sorted alphabetically.", + sortMembersAlphabetically: "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", + unexpectedSyntaxOrder: "Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax." + } + }, + + create(context) { + + const configuration = context.options[0] || {}, + ignoreCase = configuration.ignoreCase || false, + ignoreDeclarationSort = configuration.ignoreDeclarationSort || false, + ignoreMemberSort = configuration.ignoreMemberSort || false, + memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"], + allowSeparatedGroups = configuration.allowSeparatedGroups || false, + sourceCode = context.sourceCode; + let previousDeclaration = null; + + /** + * Gets the used member syntax style. + * + * import "my-module.js" --> none + * import * as myModule from "my-module.js" --> all + * import {myMember} from "my-module.js" --> single + * import {foo, bar} from "my-module.js" --> multiple + * @param {ASTNode} node the ImportDeclaration node. + * @returns {string} used member parameter style, ["all", "multiple", "single"] + */ + function usedMemberSyntax(node) { + if (node.specifiers.length === 0) { + return "none"; + } + if (node.specifiers[0].type === "ImportNamespaceSpecifier") { + return "all"; + } + if (node.specifiers.length === 1) { + return "single"; + } + return "multiple"; + + } + + /** + * Gets the group by member parameter index for given declaration. + * @param {ASTNode} node the ImportDeclaration node. + * @returns {number} the declaration group by member index. + */ + function getMemberParameterGroupIndex(node) { + return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node)); + } + + /** + * Gets the local name of the first imported module. + * @param {ASTNode} node the ImportDeclaration node. + * @returns {?string} the local name of the first imported module. + */ + function getFirstLocalMemberName(node) { + if (node.specifiers[0]) { + return node.specifiers[0].local.name; + } + return null; + + } + + /** + * Calculates number of lines between two nodes. It is assumed that the given `left` node appears before + * the given `right` node in the source code. Lines are counted from the end of the `left` node till the + * start of the `right` node. If the given nodes are on the same line, it returns `0`, same as if they were + * on two consecutive lines. + * @param {ASTNode} left node that appears before the given `right` node. + * @param {ASTNode} right node that appears after the given `left` node. + * @returns {number} number of lines between nodes. + */ + function getNumberOfLinesBetween(left, right) { + return Math.max(right.loc.start.line - left.loc.end.line - 1, 0); + } + + return { + ImportDeclaration(node) { + if (!ignoreDeclarationSort) { + if ( + previousDeclaration && + allowSeparatedGroups && + getNumberOfLinesBetween(previousDeclaration, node) > 0 + ) { + + // reset declaration sort + previousDeclaration = null; + } + + if (previousDeclaration) { + const currentMemberSyntaxGroupIndex = getMemberParameterGroupIndex(node), + previousMemberSyntaxGroupIndex = getMemberParameterGroupIndex(previousDeclaration); + let currentLocalMemberName = getFirstLocalMemberName(node), + previousLocalMemberName = getFirstLocalMemberName(previousDeclaration); + + if (ignoreCase) { + previousLocalMemberName = previousLocalMemberName && previousLocalMemberName.toLowerCase(); + currentLocalMemberName = currentLocalMemberName && currentLocalMemberName.toLowerCase(); + } + + /* + * When the current declaration uses a different member syntax, + * then check if the ordering is correct. + * Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name. + */ + if (currentMemberSyntaxGroupIndex !== previousMemberSyntaxGroupIndex) { + if (currentMemberSyntaxGroupIndex < previousMemberSyntaxGroupIndex) { + context.report({ + node, + messageId: "unexpectedSyntaxOrder", + data: { + syntaxA: memberSyntaxSortOrder[currentMemberSyntaxGroupIndex], + syntaxB: memberSyntaxSortOrder[previousMemberSyntaxGroupIndex] + } + }); + } + } else { + if (previousLocalMemberName && + currentLocalMemberName && + currentLocalMemberName < previousLocalMemberName + ) { + context.report({ + node, + messageId: "sortImportsAlphabetically" + }); + } + } + } + + previousDeclaration = node; + } + + if (!ignoreMemberSort) { + const importSpecifiers = node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"); + const getSortableName = ignoreCase ? specifier => specifier.local.name.toLowerCase() : specifier => specifier.local.name; + const firstUnsortedIndex = importSpecifiers.map(getSortableName).findIndex((name, index, array) => array[index - 1] > name); + + if (firstUnsortedIndex !== -1) { + context.report({ + node: importSpecifiers[firstUnsortedIndex], + messageId: "sortMembersAlphabetically", + data: { memberName: importSpecifiers[firstUnsortedIndex].local.name }, + fix(fixer) { + if (importSpecifiers.some(specifier => + sourceCode.getCommentsBefore(specifier).length || sourceCode.getCommentsAfter(specifier).length)) { + + // If there are comments in the ImportSpecifier list, don't rearrange the specifiers. + return null; + } + + return fixer.replaceTextRange( + [importSpecifiers[0].range[0], importSpecifiers[importSpecifiers.length - 1].range[1]], + importSpecifiers + + // Clone the importSpecifiers array to avoid mutating it + .slice() + + // Sort the array into the desired order + .sort((specifierA, specifierB) => { + const aName = getSortableName(specifierA); + const bName = getSortableName(specifierB); + + return aName > bName ? 1 : -1; + }) + + // Build a string out of the sorted list of import specifiers and the text between the originals + .reduce((sourceText, specifier, index) => { + const textAfterSpecifier = index === importSpecifiers.length - 1 + ? "" + : sourceCode.getText().slice(importSpecifiers[index].range[1], importSpecifiers[index + 1].range[0]); + + return sourceText + sourceCode.getText(specifier) + textAfterSpecifier; + }, "") + ); + } + }); + } + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/sort-keys.js b/node_modules/eslint/lib/rules/sort-keys.js new file mode 100644 index 0000000..088b589 --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-keys.js @@ -0,0 +1,230 @@ +/** + * @fileoverview Rule to require object keys to be sorted + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + naturalCompare = require("natural-compare"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets the property name of the given `Property` node. + * + * - If the property's key is an `Identifier` node, this returns the key's name + * whether it's a computed property or not. + * - If the property has a static name, this returns the static name. + * - Otherwise, this returns null. + * @param {ASTNode} node The `Property` node to get. + * @returns {string|null} The property name or null. + * @private + */ +function getPropertyName(node) { + const staticName = astUtils.getStaticPropertyName(node); + + if (staticName !== null) { + return staticName; + } + + return node.key.name || null; +} + +/** + * Functions which check that the given 2 names are in specific order. + * + * Postfix `I` is meant insensitive. + * Postfix `N` is meant natural. + * @private + */ +const isValidOrders = { + asc(a, b) { + return a <= b; + }, + ascI(a, b) { + return a.toLowerCase() <= b.toLowerCase(); + }, + ascN(a, b) { + return naturalCompare(a, b) <= 0; + }, + ascIN(a, b) { + return naturalCompare(a.toLowerCase(), b.toLowerCase()) <= 0; + }, + desc(a, b) { + return isValidOrders.asc(b, a); + }, + descI(a, b) { + return isValidOrders.ascI(b, a); + }, + descN(a, b) { + return isValidOrders.ascN(b, a); + }, + descIN(a, b) { + return isValidOrders.ascIN(b, a); + } +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require object keys to be sorted", + recommended: false, + url: "https://eslint.org/docs/latest/rules/sort-keys" + }, + + schema: [ + { + enum: ["asc", "desc"] + }, + { + type: "object", + properties: { + caseSensitive: { + type: "boolean", + default: true + }, + natural: { + type: "boolean", + default: false + }, + minKeys: { + type: "integer", + minimum: 2, + default: 2 + }, + allowLineSeparatedGroups: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + sortKeys: "Expected object keys to be in {{natural}}{{insensitive}}{{order}}ending order. '{{thisName}}' should be before '{{prevName}}'." + } + }, + + create(context) { + + // Parse options. + const order = context.options[0] || "asc"; + const options = context.options[1]; + const insensitive = options && options.caseSensitive === false; + const natural = options && options.natural; + const minKeys = options && options.minKeys; + const allowLineSeparatedGroups = options && options.allowLineSeparatedGroups || false; + const isValidOrder = isValidOrders[ + order + (insensitive ? "I" : "") + (natural ? "N" : "") + ]; + + // The stack to save the previous property's name for each object literals. + let stack = null; + const sourceCode = context.sourceCode; + + return { + ObjectExpression(node) { + stack = { + upper: stack, + prevNode: null, + prevBlankLine: false, + prevName: null, + numKeys: node.properties.length + }; + }, + + "ObjectExpression:exit"() { + stack = stack.upper; + }, + + SpreadElement(node) { + if (node.parent.type === "ObjectExpression") { + stack.prevName = null; + } + }, + + Property(node) { + if (node.parent.type === "ObjectPattern") { + return; + } + + const prevName = stack.prevName; + const numKeys = stack.numKeys; + const thisName = getPropertyName(node); + + // Get tokens between current node and previous node + const tokens = stack.prevNode && sourceCode + .getTokensBetween(stack.prevNode, node, { includeComments: true }); + + let isBlankLineBetweenNodes = stack.prevBlankLine; + + if (tokens) { + + // check blank line between tokens + tokens.forEach((token, index) => { + const previousToken = tokens[index - 1]; + + if (previousToken && (token.loc.start.line - previousToken.loc.end.line > 1)) { + isBlankLineBetweenNodes = true; + } + }); + + // check blank line between the current node and the last token + if (!isBlankLineBetweenNodes && (node.loc.start.line - tokens[tokens.length - 1].loc.end.line > 1)) { + isBlankLineBetweenNodes = true; + } + + // check blank line between the first token and the previous node + if (!isBlankLineBetweenNodes && (tokens[0].loc.start.line - stack.prevNode.loc.end.line > 1)) { + isBlankLineBetweenNodes = true; + } + } + + stack.prevNode = node; + + if (thisName !== null) { + stack.prevName = thisName; + } + + if (allowLineSeparatedGroups && isBlankLineBetweenNodes) { + stack.prevBlankLine = thisName === null; + return; + } + + if (prevName === null || thisName === null || numKeys < minKeys) { + return; + } + + if (!isValidOrder(prevName, thisName)) { + context.report({ + node, + loc: node.key.loc, + messageId: "sortKeys", + data: { + thisName, + prevName, + order, + insensitive: insensitive ? "insensitive " : "", + natural: natural ? "natural " : "" + } + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/sort-vars.js b/node_modules/eslint/lib/rules/sort-vars.js new file mode 100644 index 0000000..8fd723f --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-vars.js @@ -0,0 +1,104 @@ +/** + * @fileoverview Rule to require sorting of variables within a single Variable Declaration block + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require variables within the same declaration block to be sorted", + recommended: false, + url: "https://eslint.org/docs/latest/rules/sort-vars" + }, + + schema: [ + { + type: "object", + properties: { + ignoreCase: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + fixable: "code", + + messages: { + sortVars: "Variables within the same declaration block should be sorted alphabetically." + } + }, + + create(context) { + + const configuration = context.options[0] || {}, + ignoreCase = configuration.ignoreCase || false, + sourceCode = context.sourceCode; + + return { + VariableDeclaration(node) { + const idDeclarations = node.declarations.filter(decl => decl.id.type === "Identifier"); + const getSortableName = ignoreCase ? decl => decl.id.name.toLowerCase() : decl => decl.id.name; + const unfixable = idDeclarations.some(decl => decl.init !== null && decl.init.type !== "Literal"); + let fixed = false; + + idDeclarations.slice(1).reduce((memo, decl) => { + const lastVariableName = getSortableName(memo), + currentVariableName = getSortableName(decl); + + if (currentVariableName < lastVariableName) { + context.report({ + node: decl, + messageId: "sortVars", + fix(fixer) { + if (unfixable || fixed) { + return null; + } + return fixer.replaceTextRange( + [idDeclarations[0].range[0], idDeclarations[idDeclarations.length - 1].range[1]], + idDeclarations + + // Clone the idDeclarations array to avoid mutating it + .slice() + + // Sort the array into the desired order + .sort((declA, declB) => { + const aName = getSortableName(declA); + const bName = getSortableName(declB); + + return aName > bName ? 1 : -1; + }) + + // Build a string out of the sorted list of identifier declarations and the text between the originals + .reduce((sourceText, identifier, index) => { + const textAfterIdentifier = index === idDeclarations.length - 1 + ? "" + : sourceCode.getText().slice(idDeclarations[index].range[1], idDeclarations[index + 1].range[0]); + + return sourceText + sourceCode.getText(identifier) + textAfterIdentifier; + }, "") + + ); + } + }); + fixed = true; + return memo; + } + return decl; + + }, idDeclarations[0]); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/space-before-blocks.js b/node_modules/eslint/lib/rules/space-before-blocks.js new file mode 100644 index 0000000..a580a4f --- /dev/null +++ b/node_modules/eslint/lib/rules/space-before-blocks.js @@ -0,0 +1,201 @@ +/** + * @fileoverview A rule to ensure whitespace before blocks. + * @author Mathias Schreck + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents the body of a function. + * @param {ASTNode} node the node to check. + * @returns {boolean} `true` if the node is function body. + */ +function isFunctionBody(node) { + const parent = node.parent; + + return ( + node.type === "BlockStatement" && + astUtils.isFunction(parent) && + parent.body === node + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing before blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-before-blocks" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + keywords: { + enum: ["always", "never", "off"] + }, + functions: { + enum: ["always", "never", "off"] + }, + classes: { + enum: ["always", "never", "off"] + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + unexpectedSpace: "Unexpected space before opening brace.", + missingSpace: "Missing space before opening brace." + } + }, + + create(context) { + const config = context.options[0], + sourceCode = context.sourceCode; + let alwaysFunctions = true, + alwaysKeywords = true, + alwaysClasses = true, + neverFunctions = false, + neverKeywords = false, + neverClasses = false; + + if (typeof config === "object") { + alwaysFunctions = config.functions === "always"; + alwaysKeywords = config.keywords === "always"; + alwaysClasses = config.classes === "always"; + neverFunctions = config.functions === "never"; + neverKeywords = config.keywords === "never"; + neverClasses = config.classes === "never"; + } else if (config === "never") { + alwaysFunctions = false; + alwaysKeywords = false; + alwaysClasses = false; + neverFunctions = true; + neverKeywords = true; + neverClasses = true; + } + + /** + * Checks whether the spacing before the given block is already controlled by another rule: + * - `arrow-spacing` checks spaces after `=>`. + * - `keyword-spacing` checks spaces after keywords in certain contexts. + * - `switch-colon-spacing` checks spaces after `:` of switch cases. + * @param {Token} precedingToken first token before the block. + * @param {ASTNode|Token} node `BlockStatement` node or `{` token of a `SwitchStatement` node. + * @returns {boolean} `true` if requiring or disallowing spaces before the given block could produce conflicts with other rules. + */ + function isConflicted(precedingToken, node) { + return ( + astUtils.isArrowToken(precedingToken) || + ( + astUtils.isKeywordToken(precedingToken) && + !isFunctionBody(node) + ) || + ( + astUtils.isColonToken(precedingToken) && + node.parent && + node.parent.type === "SwitchCase" && + precedingToken === astUtils.getSwitchCaseColonToken(node.parent, sourceCode) + ) + ); + } + + /** + * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line. + * @param {ASTNode|Token} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPrecedingSpace(node) { + const precedingToken = sourceCode.getTokenBefore(node); + + if (precedingToken && !isConflicted(precedingToken, node) && astUtils.isTokenOnSameLine(precedingToken, node)) { + const hasSpace = sourceCode.isSpaceBetweenTokens(precedingToken, node); + let requireSpace; + let requireNoSpace; + + if (isFunctionBody(node)) { + requireSpace = alwaysFunctions; + requireNoSpace = neverFunctions; + } else if (node.type === "ClassBody") { + requireSpace = alwaysClasses; + requireNoSpace = neverClasses; + } else { + requireSpace = alwaysKeywords; + requireNoSpace = neverKeywords; + } + + if (requireSpace && !hasSpace) { + context.report({ + node, + messageId: "missingSpace", + fix(fixer) { + return fixer.insertTextBefore(node, " "); + } + }); + } else if (requireNoSpace && hasSpace) { + context.report({ + node, + messageId: "unexpectedSpace", + fix(fixer) { + return fixer.removeRange([precedingToken.range[1], node.range[0]]); + } + }); + } + } + } + + /** + * Checks if the CaseBlock of an given SwitchStatement node has a preceding space. + * @param {ASTNode} node The node of a SwitchStatement. + * @returns {void} undefined. + */ + function checkSpaceBeforeCaseBlock(node) { + const cases = node.cases; + let openingBrace; + + if (cases.length > 0) { + openingBrace = sourceCode.getTokenBefore(cases[0]); + } else { + openingBrace = sourceCode.getLastToken(node, 1); + } + + checkPrecedingSpace(openingBrace); + } + + return { + BlockStatement: checkPrecedingSpace, + ClassBody: checkPrecedingSpace, + SwitchStatement: checkSpaceBeforeCaseBlock + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/space-before-function-paren.js b/node_modules/eslint/lib/rules/space-before-function-paren.js new file mode 100644 index 0000000..c5faa8c --- /dev/null +++ b/node_modules/eslint/lib/rules/space-before-function-paren.js @@ -0,0 +1,164 @@ +/** + * @fileoverview Rule to validate spacing before function paren. + * @author Mathias Schreck + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing before `function` definition opening parenthesis", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-before-function-paren" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + anonymous: { + enum: ["always", "never", "ignore"] + }, + named: { + enum: ["always", "never", "ignore"] + }, + asyncArrow: { + enum: ["always", "never", "ignore"] + } + }, + additionalProperties: false + } + ] + } + ], + + messages: { + unexpectedSpace: "Unexpected space before function parentheses.", + missingSpace: "Missing space before function parentheses." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const baseConfig = typeof context.options[0] === "string" ? context.options[0] : "always"; + const overrideConfig = typeof context.options[0] === "object" ? context.options[0] : {}; + + /** + * Determines whether a function has a name. + * @param {ASTNode} node The function node. + * @returns {boolean} Whether the function has a name. + */ + function isNamedFunction(node) { + if (node.id) { + return true; + } + + const parent = node.parent; + + return parent.type === "MethodDefinition" || + (parent.type === "Property" && + ( + parent.kind === "get" || + parent.kind === "set" || + parent.method + ) + ); + } + + /** + * Gets the config for a given function + * @param {ASTNode} node The function node + * @returns {string} "always", "never", or "ignore" + */ + function getConfigForFunction(node) { + if (node.type === "ArrowFunctionExpression") { + + // Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar + if (node.async && astUtils.isOpeningParenToken(sourceCode.getFirstToken(node, { skip: 1 }))) { + return overrideConfig.asyncArrow || baseConfig; + } + } else if (isNamedFunction(node)) { + return overrideConfig.named || baseConfig; + + // `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}` + } else if (!node.generator) { + return overrideConfig.anonymous || baseConfig; + } + + return "ignore"; + } + + /** + * Checks the parens of a function node + * @param {ASTNode} node A function node + * @returns {void} + */ + function checkFunction(node) { + const functionConfig = getConfigForFunction(node); + + if (functionConfig === "ignore") { + return; + } + + const rightToken = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken); + const leftToken = sourceCode.getTokenBefore(rightToken); + const hasSpacing = sourceCode.isSpaceBetweenTokens(leftToken, rightToken); + + if (hasSpacing && functionConfig === "never") { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: rightToken.loc.start + }, + messageId: "unexpectedSpace", + fix(fixer) { + const comments = sourceCode.getCommentsBefore(rightToken); + + // Don't fix anything if there's a single line comment between the left and the right token + if (comments.some(comment => comment.type === "Line")) { + return null; + } + return fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + comments.reduce((text, comment) => text + sourceCode.getText(comment), "") + ); + } + }); + } else if (!hasSpacing && functionConfig === "always") { + context.report({ + node, + loc: rightToken.loc, + messageId: "missingSpace", + fix: fixer => fixer.insertTextAfter(leftToken, " ") + }); + } + } + + return { + ArrowFunctionExpression: checkFunction, + FunctionDeclaration: checkFunction, + FunctionExpression: checkFunction + }; + } +}; diff --git a/node_modules/eslint/lib/rules/space-in-parens.js b/node_modules/eslint/lib/rules/space-in-parens.js new file mode 100644 index 0000000..c6c06d2 --- /dev/null +++ b/node_modules/eslint/lib/rules/space-in-parens.js @@ -0,0 +1,282 @@ +/** + * @fileoverview Disallows or enforces spaces inside of parentheses. + * @author Jonathan Rajavuori + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing inside parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-in-parens" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + enum: ["{}", "[]", "()", "empty"] + }, + uniqueItems: true + } + }, + additionalProperties: false + } + ], + + messages: { + missingOpeningSpace: "There must be a space after this paren.", + missingClosingSpace: "There must be a space before this paren.", + rejectedOpeningSpace: "There should be no space after this paren.", + rejectedClosingSpace: "There should be no space before this paren." + } + }, + + create(context) { + const ALWAYS = context.options[0] === "always", + exceptionsArrayOptions = (context.options[1] && context.options[1].exceptions) || [], + options = {}; + + let exceptions; + + if (exceptionsArrayOptions.length) { + options.braceException = exceptionsArrayOptions.includes("{}"); + options.bracketException = exceptionsArrayOptions.includes("[]"); + options.parenException = exceptionsArrayOptions.includes("()"); + options.empty = exceptionsArrayOptions.includes("empty"); + } + + /** + * Produces an object with the opener and closer exception values + * @returns {Object} `openers` and `closers` exception values + * @private + */ + function getExceptions() { + const openers = [], + closers = []; + + if (options.braceException) { + openers.push("{"); + closers.push("}"); + } + + if (options.bracketException) { + openers.push("["); + closers.push("]"); + } + + if (options.parenException) { + openers.push("("); + closers.push(")"); + } + + if (options.empty) { + openers.push(")"); + closers.push("("); + } + + return { + openers, + closers + }; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + const sourceCode = context.sourceCode; + + /** + * Determines if a token is one of the exceptions for the opener paren + * @param {Object} token The token to check + * @returns {boolean} True if the token is one of the exceptions for the opener paren + */ + function isOpenerException(token) { + return exceptions.openers.includes(token.value); + } + + /** + * Determines if a token is one of the exceptions for the closer paren + * @param {Object} token The token to check + * @returns {boolean} True if the token is one of the exceptions for the closer paren + */ + function isCloserException(token) { + return exceptions.closers.includes(token.value); + } + + /** + * Determines if an opening paren is immediately followed by a required space + * @param {Object} openingParenToken The paren token + * @param {Object} tokenAfterOpeningParen The token after it + * @returns {boolean} True if the opening paren is missing a required space + */ + function openerMissingSpace(openingParenToken, tokenAfterOpeningParen) { + if (sourceCode.isSpaceBetweenTokens(openingParenToken, tokenAfterOpeningParen)) { + return false; + } + + if (!options.empty && astUtils.isClosingParenToken(tokenAfterOpeningParen)) { + return false; + } + + if (ALWAYS) { + return !isOpenerException(tokenAfterOpeningParen); + } + return isOpenerException(tokenAfterOpeningParen); + } + + /** + * Determines if an opening paren is immediately followed by a disallowed space + * @param {Object} openingParenToken The paren token + * @param {Object} tokenAfterOpeningParen The token after it + * @returns {boolean} True if the opening paren has a disallowed space + */ + function openerRejectsSpace(openingParenToken, tokenAfterOpeningParen) { + if (!astUtils.isTokenOnSameLine(openingParenToken, tokenAfterOpeningParen)) { + return false; + } + + if (tokenAfterOpeningParen.type === "Line") { + return false; + } + + if (!sourceCode.isSpaceBetweenTokens(openingParenToken, tokenAfterOpeningParen)) { + return false; + } + + if (ALWAYS) { + return isOpenerException(tokenAfterOpeningParen); + } + return !isOpenerException(tokenAfterOpeningParen); + } + + /** + * Determines if a closing paren is immediately preceded by a required space + * @param {Object} tokenBeforeClosingParen The token before the paren + * @param {Object} closingParenToken The paren token + * @returns {boolean} True if the closing paren is missing a required space + */ + function closerMissingSpace(tokenBeforeClosingParen, closingParenToken) { + if (sourceCode.isSpaceBetweenTokens(tokenBeforeClosingParen, closingParenToken)) { + return false; + } + + if (!options.empty && astUtils.isOpeningParenToken(tokenBeforeClosingParen)) { + return false; + } + + if (ALWAYS) { + return !isCloserException(tokenBeforeClosingParen); + } + return isCloserException(tokenBeforeClosingParen); + } + + /** + * Determines if a closer paren is immediately preceded by a disallowed space + * @param {Object} tokenBeforeClosingParen The token before the paren + * @param {Object} closingParenToken The paren token + * @returns {boolean} True if the closing paren has a disallowed space + */ + function closerRejectsSpace(tokenBeforeClosingParen, closingParenToken) { + if (!astUtils.isTokenOnSameLine(tokenBeforeClosingParen, closingParenToken)) { + return false; + } + + if (!sourceCode.isSpaceBetweenTokens(tokenBeforeClosingParen, closingParenToken)) { + return false; + } + + if (ALWAYS) { + return isCloserException(tokenBeforeClosingParen); + } + return !isCloserException(tokenBeforeClosingParen); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkParenSpaces(node) { + exceptions = getExceptions(); + const tokens = sourceCode.tokensAndComments; + + tokens.forEach((token, i) => { + const prevToken = tokens[i - 1]; + const nextToken = tokens[i + 1]; + + // if token is not an opening or closing paren token, do nothing + if (!astUtils.isOpeningParenToken(token) && !astUtils.isClosingParenToken(token)) { + return; + } + + // if token is an opening paren and is not followed by a required space + if (token.value === "(" && openerMissingSpace(token, nextToken)) { + context.report({ + node, + loc: token.loc, + messageId: "missingOpeningSpace", + fix(fixer) { + return fixer.insertTextAfter(token, " "); + } + }); + } + + // if token is an opening paren and is followed by a disallowed space + if (token.value === "(" && openerRejectsSpace(token, nextToken)) { + context.report({ + node, + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "rejectedOpeningSpace", + fix(fixer) { + return fixer.removeRange([token.range[1], nextToken.range[0]]); + } + }); + } + + // if token is a closing paren and is not preceded by a required space + if (token.value === ")" && closerMissingSpace(prevToken, token)) { + context.report({ + node, + loc: token.loc, + messageId: "missingClosingSpace", + fix(fixer) { + return fixer.insertTextBefore(token, " "); + } + }); + } + + // if token is a closing paren and is preceded by a disallowed space + if (token.value === ")" && closerRejectsSpace(prevToken, token)) { + context.report({ + node, + loc: { start: prevToken.loc.end, end: token.loc.start }, + messageId: "rejectedClosingSpace", + fix(fixer) { + return fixer.removeRange([prevToken.range[1], token.range[0]]); + } + }); + } + }); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/space-infix-ops.js b/node_modules/eslint/lib/rules/space-infix-ops.js new file mode 100644 index 0000000..81a95f8 --- /dev/null +++ b/node_modules/eslint/lib/rules/space-infix-ops.js @@ -0,0 +1,195 @@ +/** + * @fileoverview Require spaces around infix operators + * @author Michael Ficarra + */ +"use strict"; + +const { isEqToken } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require spacing around infix operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-infix-ops" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + int32Hint: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + missingSpace: "Operator '{{operator}}' must be spaced." + } + }, + + create(context) { + const int32Hint = context.options[0] ? context.options[0].int32Hint === true : false; + const sourceCode = context.sourceCode; + + /** + * Returns the first token which violates the rule + * @param {ASTNode} left The left node of the main node + * @param {ASTNode} right The right node of the main node + * @param {string} op The operator of the main node + * @returns {Object} The violator token or null + * @private + */ + function getFirstNonSpacedToken(left, right, op) { + const operator = sourceCode.getFirstTokenBetween(left, right, token => token.value === op); + const prev = sourceCode.getTokenBefore(operator); + const next = sourceCode.getTokenAfter(operator); + + if (!sourceCode.isSpaceBetweenTokens(prev, operator) || !sourceCode.isSpaceBetweenTokens(operator, next)) { + return operator; + } + + return null; + } + + /** + * Reports an AST node as a rule violation + * @param {ASTNode} mainNode The node to report + * @param {Object} culpritToken The token which has a problem + * @returns {void} + * @private + */ + function report(mainNode, culpritToken) { + context.report({ + node: mainNode, + loc: culpritToken.loc, + messageId: "missingSpace", + data: { + operator: culpritToken.value + }, + fix(fixer) { + const previousToken = sourceCode.getTokenBefore(culpritToken); + const afterToken = sourceCode.getTokenAfter(culpritToken); + let fixString = ""; + + if (culpritToken.range[0] - previousToken.range[1] === 0) { + fixString = " "; + } + + fixString += culpritToken.value; + + if (afterToken.range[0] - culpritToken.range[1] === 0) { + fixString += " "; + } + + return fixer.replaceText(culpritToken, fixString); + } + }); + } + + /** + * Check if the node is binary then report + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkBinary(node) { + const leftNode = (node.left.typeAnnotation) ? node.left.typeAnnotation : node.left; + const rightNode = node.right; + + // search for = in AssignmentPattern nodes + const operator = node.operator || "="; + + const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, operator); + + if (nonSpacedNode) { + if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) { + report(node, nonSpacedNode); + } + } + } + + /** + * Check if the node is conditional + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkConditional(node) { + const nonSpacedConsequentNode = getFirstNonSpacedToken(node.test, node.consequent, "?"); + const nonSpacedAlternateNode = getFirstNonSpacedToken(node.consequent, node.alternate, ":"); + + if (nonSpacedConsequentNode) { + report(node, nonSpacedConsequentNode); + } + + if (nonSpacedAlternateNode) { + report(node, nonSpacedAlternateNode); + } + } + + /** + * Check if the node is a variable + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkVar(node) { + const leftNode = (node.id.typeAnnotation) ? node.id.typeAnnotation : node.id; + const rightNode = node.init; + + if (rightNode) { + const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, "="); + + if (nonSpacedNode) { + report(node, nonSpacedNode); + } + } + } + + return { + AssignmentExpression: checkBinary, + AssignmentPattern: checkBinary, + BinaryExpression: checkBinary, + LogicalExpression: checkBinary, + ConditionalExpression: checkConditional, + VariableDeclarator: checkVar, + + PropertyDefinition(node) { + if (!node.value) { + return; + } + + /* + * Because of computed properties and type annotations, some + * tokens may exist between `node.key` and `=`. + * Therefore, find the `=` from the right. + */ + const operatorToken = sourceCode.getTokenBefore(node.value, isEqToken); + const leftToken = sourceCode.getTokenBefore(operatorToken); + const rightToken = sourceCode.getTokenAfter(operatorToken); + + if ( + !sourceCode.isSpaceBetweenTokens(leftToken, operatorToken) || + !sourceCode.isSpaceBetweenTokens(operatorToken, rightToken) + ) { + report(node, operatorToken); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/space-unary-ops.js b/node_modules/eslint/lib/rules/space-unary-ops.js new file mode 100644 index 0000000..381381d --- /dev/null +++ b/node_modules/eslint/lib/rules/space-unary-ops.js @@ -0,0 +1,321 @@ +/** + * @fileoverview This rule should require or disallow spaces before or after unary operations. + * @author Marcin Kumorek + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent spacing before or after unary operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-unary-ops" + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + words: { + type: "boolean", + default: true + }, + nonwords: { + type: "boolean", + default: false + }, + overrides: { + type: "object", + additionalProperties: { + type: "boolean" + } + } + }, + additionalProperties: false + } + ], + messages: { + unexpectedBefore: "Unexpected space before unary operator '{{operator}}'.", + unexpectedAfter: "Unexpected space after unary operator '{{operator}}'.", + unexpectedAfterWord: "Unexpected space after unary word operator '{{word}}'.", + wordOperator: "Unary word operator '{{word}}' must be followed by whitespace.", + operator: "Unary operator '{{operator}}' must be followed by whitespace.", + beforeUnaryExpressions: "Space is required before unary expressions '{{token}}'." + } + }, + + create(context) { + const options = context.options[0] || { words: true, nonwords: false }; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the node is the first "!" in a "!!" convert to Boolean expression + * @param {ASTnode} node AST node + * @returns {boolean} Whether or not the node is first "!" in "!!" + */ + function isFirstBangInBangBangExpression(node) { + return node && node.type === "UnaryExpression" && node.argument.operator === "!" && + node.argument && node.argument.type === "UnaryExpression" && node.argument.operator === "!"; + } + + /** + * Checks if an override exists for a given operator. + * @param {string} operator Operator + * @returns {boolean} Whether or not an override has been provided for the operator + */ + function overrideExistsForOperator(operator) { + return options.overrides && Object.prototype.hasOwnProperty.call(options.overrides, operator); + } + + /** + * Gets the value that the override was set to for this operator + * @param {string} operator Operator + * @returns {boolean} Whether or not an override enforces a space with this operator + */ + function overrideEnforcesSpaces(operator) { + return options.overrides[operator]; + } + + /** + * Verify Unary Word Operator has spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function verifyWordHasSpaces(node, firstToken, secondToken, word) { + if (secondToken.range[0] === firstToken.range[1]) { + context.report({ + node, + messageId: "wordOperator", + data: { + word + }, + fix(fixer) { + return fixer.insertTextAfter(firstToken, " "); + } + }); + } + } + + /** + * Verify Unary Word Operator doesn't have spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word) { + if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedAfterWord", + data: { + word + }, + fix(fixer) { + return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); + } + }); + } + } + } + + /** + * Check Unary Word Operators for spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, word) { + if (overrideExistsForOperator(word)) { + if (overrideEnforcesSpaces(word)) { + verifyWordHasSpaces(node, firstToken, secondToken, word); + } else { + verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); + } + } else if (options.words) { + verifyWordHasSpaces(node, firstToken, secondToken, word); + } else { + verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); + } + } + + /** + * Verifies YieldExpressions satisfy spacing requirements + * @param {ASTnode} node AST node + * @returns {void} + */ + function checkForSpacesAfterYield(node) { + const tokens = sourceCode.getFirstTokens(node, 3), + word = "yield"; + + if (!node.argument || node.delegate) { + return; + } + + checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], word); + } + + /** + * Verifies AwaitExpressions satisfy spacing requirements + * @param {ASTNode} node AwaitExpression AST node + * @returns {void} + */ + function checkForSpacesAfterAwait(node) { + const tokens = sourceCode.getFirstTokens(node, 3); + + checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], "await"); + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator + * @param {ASTnode} node AST node + * @param {Object} firstToken First token in the expression + * @param {Object} secondToken Second token in the expression + * @returns {void} + */ + function verifyNonWordsHaveSpaces(node, firstToken, secondToken) { + if (node.prefix) { + if (isFirstBangInBangBangExpression(node)) { + return; + } + if (firstToken.range[1] === secondToken.range[0]) { + context.report({ + node, + messageId: "operator", + data: { + operator: firstToken.value + }, + fix(fixer) { + return fixer.insertTextAfter(firstToken, " "); + } + }); + } + } else { + if (firstToken.range[1] === secondToken.range[0]) { + context.report({ + node, + messageId: "beforeUnaryExpressions", + data: { + token: secondToken.value + }, + fix(fixer) { + return fixer.insertTextBefore(secondToken, " "); + } + }); + } + } + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator + * @param {ASTnode} node AST node + * @param {Object} firstToken First token in the expression + * @param {Object} secondToken Second token in the expression + * @returns {void} + */ + function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) { + if (node.prefix) { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedAfter", + data: { + operator: firstToken.value + }, + fix(fixer) { + if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) { + return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); + } + return null; + } + }); + } + } else { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedBefore", + data: { + operator: secondToken.value + }, + fix(fixer) { + return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); + } + }); + } + } + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements + * @param {ASTnode} node AST node + * @returns {void} + */ + function checkForSpaces(node) { + const tokens = node.type === "UpdateExpression" && !node.prefix + ? sourceCode.getLastTokens(node, 2) + : sourceCode.getFirstTokens(node, 2); + const firstToken = tokens[0]; + const secondToken = tokens[1]; + + if ((node.type === "NewExpression" || node.prefix) && firstToken.type === "Keyword") { + checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, firstToken.value); + return; + } + + const operator = node.prefix ? tokens[0].value : tokens[1].value; + + if (overrideExistsForOperator(operator)) { + if (overrideEnforcesSpaces(operator)) { + verifyNonWordsHaveSpaces(node, firstToken, secondToken); + } else { + verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); + } + } else if (options.nonwords) { + verifyNonWordsHaveSpaces(node, firstToken, secondToken); + } else { + verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + UnaryExpression: checkForSpaces, + UpdateExpression: checkForSpaces, + NewExpression: checkForSpaces, + YieldExpression: checkForSpacesAfterYield, + AwaitExpression: checkForSpacesAfterAwait + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/spaced-comment.js b/node_modules/eslint/lib/rules/spaced-comment.js new file mode 100644 index 0000000..2eb7f0e --- /dev/null +++ b/node_modules/eslint/lib/rules/spaced-comment.js @@ -0,0 +1,382 @@ +/** + * @fileoverview Source code for spaced-comments rule + * @author Gyandeep Singh + */ +"use strict"; + +const escapeRegExp = require("escape-string-regexp"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Escapes the control characters of a given string. + * @param {string} s A string to escape. + * @returns {string} An escaped string. + */ +function escape(s) { + return `(?:${escapeRegExp(s)})`; +} + +/** + * Escapes the control characters of a given string. + * And adds a repeat flag. + * @param {string} s A string to escape. + * @returns {string} An escaped string. + */ +function escapeAndRepeat(s) { + return `${escape(s)}+`; +} + +/** + * Parses `markers` option. + * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments. + * @param {string[]} [markers] A marker list. + * @returns {string[]} A marker list. + */ +function parseMarkersOption(markers) { + + // `*` is a marker for JSDoc comments. + if (!markers.includes("*")) { + return markers.concat("*"); + } + + return markers; +} + +/** + * Creates string pattern for exceptions. + * Generated pattern: + * + * 1. A space or an exception pattern sequence. + * @param {string[]} exceptions An exception pattern list. + * @returns {string} A regular expression string for exceptions. + */ +function createExceptionsPattern(exceptions) { + let pattern = ""; + + /* + * A space or an exception pattern sequence. + * [] ==> "\s" + * ["-"] ==> "(?:\s|\-+$)" + * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)" + * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24) + */ + if (exceptions.length === 0) { + + // a space. + pattern += "\\s"; + } else { + + // a space or... + pattern += "(?:\\s|"; + + if (exceptions.length === 1) { + + // a sequence of the exception pattern. + pattern += escapeAndRepeat(exceptions[0]); + } else { + + // a sequence of one of the exception patterns. + pattern += "(?:"; + pattern += exceptions.map(escapeAndRepeat).join("|"); + pattern += ")"; + } + pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`; + } + + return pattern; +} + +/** + * Creates RegExp object for `always` mode. + * Generated pattern for beginning of comment: + * + * 1. First, a marker or nothing. + * 2. Next, a space or an exception pattern sequence. + * @param {string[]} markers A marker list. + * @param {string[]} exceptions An exception pattern list. + * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode. + */ +function createAlwaysStylePattern(markers, exceptions) { + let pattern = "^"; + + /* + * A marker or nothing. + * ["*"] ==> "\*?" + * ["*", "!"] ==> "(?:\*|!)?" + * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F + */ + if (markers.length === 1) { + + // the marker. + pattern += escape(markers[0]); + } else { + + // one of markers. + pattern += "(?:"; + pattern += markers.map(escape).join("|"); + pattern += ")"; + } + + pattern += "?"; // or nothing. + pattern += createExceptionsPattern(exceptions); + + return new RegExp(pattern, "u"); +} + +/** + * Creates RegExp object for `never` mode. + * Generated pattern for beginning of comment: + * + * 1. First, a marker or nothing (captured). + * 2. Next, a space or a tab. + * @param {string[]} markers A marker list. + * @returns {RegExp} A RegExp object for `never` mode. + */ +function createNeverStylePattern(markers) { + const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`; + + return new RegExp(pattern, "u"); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce consistent spacing after the `//` or `/*` in a comment", + recommended: false, + url: "https://eslint.org/docs/latest/rules/spaced-comment" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string" + } + }, + markers: { + type: "array", + items: { + type: "string" + } + }, + line: { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string" + } + }, + markers: { + type: "array", + items: { + type: "string" + } + } + }, + additionalProperties: false + }, + block: { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string" + } + }, + markers: { + type: "array", + items: { + type: "string" + } + }, + balanced: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + }, + additionalProperties: false + } + ], + + messages: { + unexpectedSpaceAfterMarker: "Unexpected space or tab after marker ({{refChar}}) in comment.", + expectedExceptionAfter: "Expected exception block, space or tab after '{{refChar}}' in comment.", + unexpectedSpaceBefore: "Unexpected space or tab before '*/' in comment.", + unexpectedSpaceAfter: "Unexpected space or tab after '{{refChar}}' in comment.", + expectedSpaceBefore: "Expected space or tab before '*/' in comment.", + expectedSpaceAfter: "Expected space or tab after '{{refChar}}' in comment." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + // Unless the first option is never, require a space + const requireSpace = context.options[0] !== "never"; + + /* + * Parse the second options. + * If markers don't include `"*"`, it's added automatically for JSDoc + * comments. + */ + const config = context.options[1] || {}; + const balanced = config.block && config.block.balanced; + + const styleRules = ["block", "line"].reduce((rule, type) => { + const markers = parseMarkersOption(config[type] && config[type].markers || config.markers || []); + const exceptions = config[type] && config[type].exceptions || config.exceptions || []; + const endNeverPattern = "[ \t]+$"; + + // Create RegExp object for valid patterns. + rule[type] = { + beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers), + endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`, "u") : new RegExp(endNeverPattern, "u"), + hasExceptions: exceptions.length > 0, + captureMarker: new RegExp(`^(${markers.map(escape).join("|")})`, "u"), + markers: new Set(markers) + }; + + return rule; + }, {}); + + /** + * Reports a beginning spacing error with an appropriate message. + * @param {ASTNode} node A comment node to check. + * @param {string} messageId An error message to report. + * @param {Array} match An array of match results for markers. + * @param {string} refChar Character used for reference in the error message. + * @returns {void} + */ + function reportBegin(node, messageId, match, refChar) { + const type = node.type.toLowerCase(), + commentIdentifier = type === "block" ? "/*" : "//"; + + context.report({ + node, + fix(fixer) { + const start = node.range[0]; + let end = start + 2; + + if (requireSpace) { + if (match) { + end += match[0].length; + } + return fixer.insertTextAfterRange([start, end], " "); + } + end += match[0].length; + return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : "")); + + }, + messageId, + data: { refChar } + }); + } + + /** + * Reports an ending spacing error with an appropriate message. + * @param {ASTNode} node A comment node to check. + * @param {string} messageId An error message to report. + * @param {string} match An array of the matched whitespace characters. + * @returns {void} + */ + function reportEnd(node, messageId, match) { + context.report({ + node, + fix(fixer) { + if (requireSpace) { + return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " "); + } + const end = node.range[1] - 2, + start = end - match[0].length; + + return fixer.replaceTextRange([start, end], ""); + + }, + messageId + }); + } + + /** + * Reports a given comment if it's invalid. + * @param {ASTNode} node a comment node to check. + * @returns {void} + */ + function checkCommentForSpace(node) { + const type = node.type.toLowerCase(), + rule = styleRules[type], + commentIdentifier = type === "block" ? "/*" : "//"; + + // Ignores empty comments and comments that consist only of a marker. + if (node.value.length === 0 || rule.markers.has(node.value)) { + return; + } + + const beginMatch = rule.beginRegex.exec(node.value); + const endMatch = rule.endRegex.exec(node.value); + + // Checks. + if (requireSpace) { + if (!beginMatch) { + const hasMarker = rule.captureMarker.exec(node.value); + const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier; + + if (rule.hasExceptions) { + reportBegin(node, "expectedExceptionAfter", hasMarker, marker); + } else { + reportBegin(node, "expectedSpaceAfter", hasMarker, marker); + } + } + + if (balanced && type === "block" && !endMatch) { + reportEnd(node, "expectedSpaceBefore"); + } + } else { + if (beginMatch) { + if (!beginMatch[1]) { + reportBegin(node, "unexpectedSpaceAfter", beginMatch, commentIdentifier); + } else { + reportBegin(node, "unexpectedSpaceAfterMarker", beginMatch, beginMatch[1]); + } + } + + if (balanced && type === "block" && endMatch) { + reportEnd(node, "unexpectedSpaceBefore", endMatch); + } + } + } + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments.filter(token => token.type !== "Shebang").forEach(checkCommentForSpace); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/strict.js b/node_modules/eslint/lib/rules/strict.js new file mode 100644 index 0000000..f9dd750 --- /dev/null +++ b/node_modules/eslint/lib/rules/strict.js @@ -0,0 +1,277 @@ +/** + * @fileoverview Rule to control usage of strict mode directives. + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets all of the Use Strict Directives in the Directive Prologue of a group of + * statements. + * @param {ASTNode[]} statements Statements in the program or function body. + * @returns {ASTNode[]} All of the Use Strict Directives. + */ +function getUseStrictDirectives(statements) { + const directives = []; + + for (let i = 0; i < statements.length; i++) { + const statement = statements[i]; + + if ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + statement.expression.value === "use strict" + ) { + directives[i] = statement; + } else { + break; + } + } + + return directives; +} + +/** + * Checks whether a given parameter is a simple parameter. + * @param {ASTNode} node A pattern node to check. + * @returns {boolean} `true` if the node is an Identifier node. + */ +function isSimpleParameter(node) { + return node.type === "Identifier"; +} + +/** + * Checks whether a given parameter list is a simple parameter list. + * @param {ASTNode[]} params A parameter list to check. + * @returns {boolean} `true` if the every parameter is an Identifier node. + */ +function isSimpleParameterList(params) { + return params.every(isSimpleParameter); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require or disallow strict mode directives", + recommended: false, + url: "https://eslint.org/docs/latest/rules/strict" + }, + + schema: [ + { + enum: ["never", "global", "function", "safe"] + } + ], + + fixable: "code", + messages: { + function: "Use the function form of 'use strict'.", + global: "Use the global form of 'use strict'.", + multiple: "Multiple 'use strict' directives.", + never: "Strict mode is not permitted.", + unnecessary: "Unnecessary 'use strict' directive.", + module: "'use strict' is unnecessary inside of modules.", + implied: "'use strict' is unnecessary when implied strict mode is enabled.", + unnecessaryInClasses: "'use strict' is unnecessary inside of classes.", + nonSimpleParameterList: "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.", + wrap: "Wrap {{name}} in a function with 'use strict' directive." + } + }, + + create(context) { + + const ecmaFeatures = context.parserOptions.ecmaFeatures || {}, + scopes = [], + classScopes = []; + let mode = context.options[0] || "safe"; + + if (ecmaFeatures.impliedStrict) { + mode = "implied"; + } else if (mode === "safe") { + mode = ecmaFeatures.globalReturn || context.languageOptions.sourceType === "commonjs" ? "global" : "function"; + } + + /** + * Determines whether a reported error should be fixed, depending on the error type. + * @param {string} errorType The type of error + * @returns {boolean} `true` if the reported error should be fixed + */ + function shouldFix(errorType) { + return errorType === "multiple" || errorType === "unnecessary" || errorType === "module" || errorType === "implied" || errorType === "unnecessaryInClasses"; + } + + /** + * Gets a fixer function to remove a given 'use strict' directive. + * @param {ASTNode} node The directive that should be removed + * @returns {Function} A fixer function + */ + function getFixFunction(node) { + return fixer => fixer.remove(node); + } + + /** + * Report a slice of an array of nodes with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} start Index to start from. + * @param {string} end Index to end before. + * @param {string} messageId Message to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportSlice(nodes, start, end, messageId, fix) { + nodes.slice(start, end).forEach(node => { + context.report({ node, messageId, fix: fix ? getFixFunction(node) : null }); + }); + } + + /** + * Report all nodes in an array with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} messageId Message id to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportAll(nodes, messageId, fix) { + reportSlice(nodes, 0, nodes.length, messageId, fix); + } + + /** + * Report all nodes in an array, except the first, with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} messageId Message id to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportAllExceptFirst(nodes, messageId, fix) { + reportSlice(nodes, 1, nodes.length, messageId, fix); + } + + /** + * Entering a function in 'function' mode pushes a new nested scope onto the + * stack. The new scope is true if the nested function is strict mode code. + * @param {ASTNode} node The function declaration or expression. + * @param {ASTNode[]} useStrictDirectives The Use Strict Directives of the node. + * @returns {void} + */ + function enterFunctionInFunctionMode(node, useStrictDirectives) { + const isInClass = classScopes.length > 0, + isParentGlobal = scopes.length === 0 && classScopes.length === 0, + isParentStrict = scopes.length > 0 && scopes[scopes.length - 1], + isStrict = useStrictDirectives.length > 0; + + if (isStrict) { + if (!isSimpleParameterList(node.params)) { + context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" }); + } else if (isParentStrict) { + context.report({ node: useStrictDirectives[0], messageId: "unnecessary", fix: getFixFunction(useStrictDirectives[0]) }); + } else if (isInClass) { + context.report({ node: useStrictDirectives[0], messageId: "unnecessaryInClasses", fix: getFixFunction(useStrictDirectives[0]) }); + } + + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } else if (isParentGlobal) { + if (isSimpleParameterList(node.params)) { + context.report({ node, messageId: "function" }); + } else { + context.report({ + node, + messageId: "wrap", + data: { name: astUtils.getFunctionNameWithKind(node) } + }); + } + } + + scopes.push(isParentStrict || isStrict); + } + + /** + * Exiting a function in 'function' mode pops its scope off the stack. + * @returns {void} + */ + function exitFunctionInFunctionMode() { + scopes.pop(); + } + + /** + * Enter a function and either: + * - Push a new nested scope onto the stack (in 'function' mode). + * - Report all the Use Strict Directives (in the other modes). + * @param {ASTNode} node The function declaration or expression. + * @returns {void} + */ + function enterFunction(node) { + const isBlock = node.body.type === "BlockStatement", + useStrictDirectives = isBlock + ? getUseStrictDirectives(node.body.body) : []; + + if (mode === "function") { + enterFunctionInFunctionMode(node, useStrictDirectives); + } else if (useStrictDirectives.length > 0) { + if (isSimpleParameterList(node.params)) { + reportAll(useStrictDirectives, mode, shouldFix(mode)); + } else { + context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" }); + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } + } + } + + const rule = { + Program(node) { + const useStrictDirectives = getUseStrictDirectives(node.body); + + if (node.sourceType === "module") { + mode = "module"; + } + + if (mode === "global") { + if (node.body.length > 0 && useStrictDirectives.length === 0) { + context.report({ node, messageId: "global" }); + } + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } else { + reportAll(useStrictDirectives, mode, shouldFix(mode)); + } + }, + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression: enterFunction + }; + + if (mode === "function") { + Object.assign(rule, { + + // Inside of class bodies are always strict mode. + ClassBody() { + classScopes.push(true); + }, + "ClassBody:exit"() { + classScopes.pop(); + }, + + "FunctionDeclaration:exit": exitFunctionInFunctionMode, + "FunctionExpression:exit": exitFunctionInFunctionMode, + "ArrowFunctionExpression:exit": exitFunctionInFunctionMode + }); + } + + return rule; + } +}; diff --git a/node_modules/eslint/lib/rules/switch-colon-spacing.js b/node_modules/eslint/lib/rules/switch-colon-spacing.js new file mode 100644 index 0000000..45e4018 --- /dev/null +++ b/node_modules/eslint/lib/rules/switch-colon-spacing.js @@ -0,0 +1,129 @@ +/** + * @fileoverview Rule to enforce spacing around colons of switch statements. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce spacing around colons of switch statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/switch-colon-spacing" + }, + + schema: [ + { + type: "object", + properties: { + before: { type: "boolean", default: false }, + after: { type: "boolean", default: true } + }, + additionalProperties: false + } + ], + fixable: "whitespace", + messages: { + expectedBefore: "Expected space(s) before this colon.", + expectedAfter: "Expected space(s) after this colon.", + unexpectedBefore: "Unexpected space(s) before this colon.", + unexpectedAfter: "Unexpected space(s) after this colon." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = context.options[0] || {}; + const beforeSpacing = options.before === true; // false by default + const afterSpacing = options.after !== false; // true by default + + /** + * Check whether the spacing between the given 2 tokens is valid or not. + * @param {Token} left The left token to check. + * @param {Token} right The right token to check. + * @param {boolean} expected The expected spacing to check. `true` if there should be a space. + * @returns {boolean} `true` if the spacing between the tokens is valid. + */ + function isValidSpacing(left, right, expected) { + return ( + astUtils.isClosingBraceToken(right) || + !astUtils.isTokenOnSameLine(left, right) || + sourceCode.isSpaceBetweenTokens(left, right) === expected + ); + } + + /** + * Check whether comments exist between the given 2 tokens. + * @param {Token} left The left token to check. + * @param {Token} right The right token to check. + * @returns {boolean} `true` if comments exist between the given 2 tokens. + */ + function commentsExistBetween(left, right) { + return sourceCode.getFirstTokenBetween( + left, + right, + { + includeComments: true, + filter: astUtils.isCommentToken + } + ) !== null; + } + + /** + * Fix the spacing between the given 2 tokens. + * @param {RuleFixer} fixer The fixer to fix. + * @param {Token} left The left token of fix range. + * @param {Token} right The right token of fix range. + * @param {boolean} spacing The spacing style. `true` if there should be a space. + * @returns {Fix|null} The fix object. + */ + function fix(fixer, left, right, spacing) { + if (commentsExistBetween(left, right)) { + return null; + } + if (spacing) { + return fixer.insertTextAfter(left, " "); + } + return fixer.removeRange([left.range[1], right.range[0]]); + } + + return { + SwitchCase(node) { + const colonToken = astUtils.getSwitchCaseColonToken(node, sourceCode); + const beforeToken = sourceCode.getTokenBefore(colonToken); + const afterToken = sourceCode.getTokenAfter(colonToken); + + if (!isValidSpacing(beforeToken, colonToken, beforeSpacing)) { + context.report({ + node, + loc: colonToken.loc, + messageId: beforeSpacing ? "expectedBefore" : "unexpectedBefore", + fix: fixer => fix(fixer, beforeToken, colonToken, beforeSpacing) + }); + } + if (!isValidSpacing(colonToken, afterToken, afterSpacing)) { + context.report({ + node, + loc: colonToken.loc, + messageId: afterSpacing ? "expectedAfter" : "unexpectedAfter", + fix: fixer => fix(fixer, colonToken, afterToken, afterSpacing) + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/symbol-description.js b/node_modules/eslint/lib/rules/symbol-description.js new file mode 100644 index 0000000..4528f09 --- /dev/null +++ b/node_modules/eslint/lib/rules/symbol-description.js @@ -0,0 +1,73 @@ +/** + * @fileoverview Rule to enforce description with the `Symbol` object + * @author Jarek Rencz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require symbol descriptions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/symbol-description" + }, + fixable: null, + schema: [], + messages: { + expected: "Expected Symbol to have a description." + } + }, + + create(context) { + + const sourceCode = context.sourceCode; + + /** + * Reports if node does not conform the rule in case rule is set to + * report missing description + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + function checkArgument(node) { + if (node.arguments.length === 0) { + context.report({ + node, + messageId: "expected" + }); + } + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + const variable = astUtils.getVariableByName(scope, "Symbol"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(reference => { + const idNode = reference.identifier; + + if (astUtils.isCallee(idNode)) { + checkArgument(idNode.parent); + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/template-curly-spacing.js b/node_modules/eslint/lib/rules/template-curly-spacing.js new file mode 100644 index 0000000..cc9bbe3 --- /dev/null +++ b/node_modules/eslint/lib/rules/template-curly-spacing.js @@ -0,0 +1,141 @@ +/** + * @fileoverview Rule to enforce spacing around embedded expressions of template strings + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow spacing around embedded expressions of template strings", + recommended: false, + url: "https://eslint.org/docs/latest/rules/template-curly-spacing" + }, + + fixable: "whitespace", + + schema: [ + { enum: ["always", "never"] } + ], + messages: { + expectedBefore: "Expected space(s) before '}'.", + expectedAfter: "Expected space(s) after '${'.", + unexpectedBefore: "Unexpected space(s) before '}'.", + unexpectedAfter: "Unexpected space(s) after '${'." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + const always = context.options[0] === "always"; + + /** + * Checks spacing before `}` of a given token. + * @param {Token} token A token to check. This is a Template token. + * @returns {void} + */ + function checkSpacingBefore(token) { + if (!token.value.startsWith("}")) { + return; // starts with a backtick, this is the first template element in the template literal + } + + const prevToken = sourceCode.getTokenBefore(token, { includeComments: true }), + hasSpace = sourceCode.isSpaceBetween(prevToken, token); + + if (!astUtils.isTokenOnSameLine(prevToken, token)) { + return; + } + + if (always && !hasSpace) { + context.report({ + loc: { + start: token.loc.start, + end: { + line: token.loc.start.line, + column: token.loc.start.column + 1 + } + }, + messageId: "expectedBefore", + fix: fixer => fixer.insertTextBefore(token, " ") + }); + } + + if (!always && hasSpace) { + context.report({ + loc: { + start: prevToken.loc.end, + end: token.loc.start + }, + messageId: "unexpectedBefore", + fix: fixer => fixer.removeRange([prevToken.range[1], token.range[0]]) + }); + } + } + + /** + * Checks spacing after `${` of a given token. + * @param {Token} token A token to check. This is a Template token. + * @returns {void} + */ + function checkSpacingAfter(token) { + if (!token.value.endsWith("${")) { + return; // ends with a backtick, this is the last template element in the template literal + } + + const nextToken = sourceCode.getTokenAfter(token, { includeComments: true }), + hasSpace = sourceCode.isSpaceBetween(token, nextToken); + + if (!astUtils.isTokenOnSameLine(token, nextToken)) { + return; + } + + if (always && !hasSpace) { + context.report({ + loc: { + start: { + line: token.loc.end.line, + column: token.loc.end.column - 2 + }, + end: token.loc.end + }, + messageId: "expectedAfter", + fix: fixer => fixer.insertTextAfter(token, " ") + }); + } + + if (!always && hasSpace) { + context.report({ + loc: { + start: token.loc.end, + end: nextToken.loc.start + }, + messageId: "unexpectedAfter", + fix: fixer => fixer.removeRange([token.range[1], nextToken.range[0]]) + }); + } + } + + return { + TemplateElement(node) { + const token = sourceCode.getFirstToken(node); + + checkSpacingBefore(token); + checkSpacingAfter(token); + } + }; + } +}; diff --git a/node_modules/eslint/lib/rules/template-tag-spacing.js b/node_modules/eslint/lib/rules/template-tag-spacing.js new file mode 100644 index 0000000..9bfdfc2 --- /dev/null +++ b/node_modules/eslint/lib/rules/template-tag-spacing.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Rule to check spacing between template tags and their literals + * @author Jonathan Wilsson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow spacing between template tags and their literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/template-tag-spacing" + }, + + fixable: "whitespace", + + schema: [ + { enum: ["always", "never"] } + ], + messages: { + unexpected: "Unexpected space between template tag and template literal.", + missing: "Missing space between template tag and template literal." + } + }, + + create(context) { + const never = context.options[0] !== "always"; + const sourceCode = context.sourceCode; + + /** + * Check if a space is present between a template tag and its literal + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkSpacing(node) { + const tagToken = sourceCode.getTokenBefore(node.quasi); + const literalToken = sourceCode.getFirstToken(node.quasi); + const hasWhitespace = sourceCode.isSpaceBetweenTokens(tagToken, literalToken); + + if (never && hasWhitespace) { + context.report({ + node, + loc: { + start: tagToken.loc.end, + end: literalToken.loc.start + }, + messageId: "unexpected", + fix(fixer) { + const comments = sourceCode.getCommentsBefore(node.quasi); + + // Don't fix anything if there's a single line comment after the template tag + if (comments.some(comment => comment.type === "Line")) { + return null; + } + + return fixer.replaceTextRange( + [tagToken.range[1], literalToken.range[0]], + comments.reduce((text, comment) => text + sourceCode.getText(comment), "") + ); + } + }); + } else if (!never && !hasWhitespace) { + context.report({ + node, + loc: { + start: node.loc.start, + end: literalToken.loc.start + }, + messageId: "missing", + fix(fixer) { + return fixer.insertTextAfter(tagToken, " "); + } + }); + } + } + + return { + TaggedTemplateExpression: checkSpacing + }; + } +}; diff --git a/node_modules/eslint/lib/rules/unicode-bom.js b/node_modules/eslint/lib/rules/unicode-bom.js new file mode 100644 index 0000000..09971d2 --- /dev/null +++ b/node_modules/eslint/lib/rules/unicode-bom.js @@ -0,0 +1,73 @@ +/** + * @fileoverview Require or disallow Unicode BOM + * @author Andrew Johnston + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow Unicode byte order mark (BOM)", + recommended: false, + url: "https://eslint.org/docs/latest/rules/unicode-bom" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"] + } + ], + messages: { + expected: "Expected Unicode BOM (Byte Order Mark).", + unexpected: "Unexpected Unicode BOM (Byte Order Mark)." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + Program: function checkUnicodeBOM(node) { + + const sourceCode = context.sourceCode, + location = { column: 0, line: 1 }, + requireBOM = context.options[0] || "never"; + + if (!sourceCode.hasBOM && (requireBOM === "always")) { + context.report({ + node, + loc: location, + messageId: "expected", + fix(fixer) { + return fixer.insertTextBeforeRange([0, 1], "\uFEFF"); + } + }); + } else if (sourceCode.hasBOM && (requireBOM === "never")) { + context.report({ + node, + loc: location, + messageId: "unexpected", + fix(fixer) { + return fixer.removeRange([-1, 0]); + } + }); + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/use-isnan.js b/node_modules/eslint/lib/rules/use-isnan.js new file mode 100644 index 0000000..21dc395 --- /dev/null +++ b/node_modules/eslint/lib/rules/use-isnan.js @@ -0,0 +1,141 @@ +/** + * @fileoverview Rule to flag comparisons to the value NaN + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given node is a NaN `Identifier` node. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is 'NaN' identifier. + */ +function isNaNIdentifier(node) { + return Boolean(node) && ( + astUtils.isSpecificId(node, "NaN") || + astUtils.isSpecificMemberAccess(node, "Number", "NaN") + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Require calls to `isNaN()` when checking for `NaN`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/use-isnan" + }, + + schema: [ + { + type: "object", + properties: { + enforceForSwitchCase: { + type: "boolean", + default: true + }, + enforceForIndexOf: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + messages: { + comparisonWithNaN: "Use the isNaN function to compare with NaN.", + switchNaN: "'switch(NaN)' can never match a case clause. Use Number.isNaN instead of the switch.", + caseNaN: "'case NaN' can never match. Use Number.isNaN before the switch.", + indexOfNaN: "Array prototype method '{{ methodName }}' cannot find NaN." + } + }, + + create(context) { + + const enforceForSwitchCase = !context.options[0] || context.options[0].enforceForSwitchCase; + const enforceForIndexOf = context.options[0] && context.options[0].enforceForIndexOf; + + /** + * Checks the given `BinaryExpression` node for `foo === NaN` and other comparisons. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkBinaryExpression(node) { + if ( + /^(?:[<>]|[!=]=)=?$/u.test(node.operator) && + (isNaNIdentifier(node.left) || isNaNIdentifier(node.right)) + ) { + context.report({ node, messageId: "comparisonWithNaN" }); + } + } + + /** + * Checks the discriminant and all case clauses of the given `SwitchStatement` node for `switch(NaN)` and `case NaN:` + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkSwitchStatement(node) { + if (isNaNIdentifier(node.discriminant)) { + context.report({ node, messageId: "switchNaN" }); + } + + for (const switchCase of node.cases) { + if (isNaNIdentifier(switchCase.test)) { + context.report({ node: switchCase, messageId: "caseNaN" }); + } + } + } + + /** + * Checks the given `CallExpression` node for `.indexOf(NaN)` and `.lastIndexOf(NaN)`. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkCallExpression(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "MemberExpression") { + const methodName = astUtils.getStaticPropertyName(callee); + + if ( + (methodName === "indexOf" || methodName === "lastIndexOf") && + node.arguments.length === 1 && + isNaNIdentifier(node.arguments[0]) + ) { + context.report({ node, messageId: "indexOfNaN", data: { methodName } }); + } + } + } + + const listeners = { + BinaryExpression: checkBinaryExpression + }; + + if (enforceForSwitchCase) { + listeners.SwitchStatement = checkSwitchStatement; + } + + if (enforceForIndexOf) { + listeners.CallExpression = checkCallExpression; + } + + return listeners; + } +}; diff --git a/node_modules/eslint/lib/rules/utils/ast-utils.js b/node_modules/eslint/lib/rules/utils/ast-utils.js new file mode 100644 index 0000000..bebb4d5 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/ast-utils.js @@ -0,0 +1,2172 @@ +/** + * @fileoverview Common utils for AST. + * @author Gyandeep Singh + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { KEYS: eslintVisitorKeys } = require("eslint-visitor-keys"); +const esutils = require("esutils"); +const espree = require("espree"); +const escapeRegExp = require("escape-string-regexp"); +const { + breakableTypePattern, + createGlobalLinebreakMatcher, + lineBreakPattern, + shebangPattern +} = require("../../shared/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u; +const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u; +const arrayMethodWithThisArgPattern = /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|some)$/u; +const arrayOrTypedArrayPattern = /Array$/u; +const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u; +const thisTagPattern = /^[\s*]*@this/mu; + + +const COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u; +const ESLINT_DIRECTIVE_PATTERN = /^(?:eslint[- ]|(?:globals?|exported) )/u; +const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]); + +// A set of node types that can contain a list of statements +const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "StaticBlock", "SwitchCase"]); + +const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u; + +// Tests the presence of at least one LegacyOctalEscapeSequence or NonOctalDecimalEscapeSequence in a raw string +const OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN = /^(?:[^\\]|\\.)*\\(?:[1-9]|0[0-9])/su; + +const LOGICAL_ASSIGNMENT_OPERATORS = new Set(["&&=", "||=", "??="]); + +/** + * Checks reference if is non initializer and writable. + * @param {Reference} reference A reference to check. + * @param {int} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {boolean} Success/Failure + * @private + */ +function isModifyingReference(reference, index, references) { + const identifier = reference.identifier; + + /* + * Destructuring assignments can have multiple default value, so + * possibly there are multiple writeable references for the same + * identifier. + */ + const modifyingDifferentIdentifier = index === 0 || + references[index - 1].identifier !== identifier; + + return (identifier && + reference.init === false && + reference.isWrite() && + modifyingDifferentIdentifier + ); +} + +/** + * Checks whether the given string starts with uppercase or not. + * @param {string} s The string to check. + * @returns {boolean} `true` if the string starts with uppercase. + */ +function startsWithUpperCase(s) { + return s[0] !== s[0].toLocaleLowerCase(); +} + +/** + * Checks whether or not a node is a constructor. + * @param {ASTNode} node A function node to check. + * @returns {boolean} Whether or not a node is a constructor. + */ +function isES5Constructor(node) { + return (node.id && startsWithUpperCase(node.id.name)); +} + +/** + * Finds a function node from ancestors of a node. + * @param {ASTNode} node A start node to find. + * @returns {Node|null} A found function node. + */ +function getUpperFunction(node) { + for (let currentNode = node; currentNode; currentNode = currentNode.parent) { + if (anyFunctionPattern.test(currentNode.type)) { + return currentNode; + } + } + return null; +} + +/** + * Checks whether a given node is a function node or not. + * The following types are function nodes: + * + * - ArrowFunctionExpression + * - FunctionDeclaration + * - FunctionExpression + * @param {ASTNode|null} node A node to check. + * @returns {boolean} `true` if the node is a function node. + */ +function isFunction(node) { + return Boolean(node && anyFunctionPattern.test(node.type)); +} + +/** + * Checks whether a given node is a loop node or not. + * The following types are loop nodes: + * + * - DoWhileStatement + * - ForInStatement + * - ForOfStatement + * - ForStatement + * - WhileStatement + * @param {ASTNode|null} node A node to check. + * @returns {boolean} `true` if the node is a loop node. + */ +function isLoop(node) { + return Boolean(node && anyLoopPattern.test(node.type)); +} + +/** + * Checks whether the given node is in a loop or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is in a loop. + */ +function isInLoop(node) { + for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) { + if (isLoop(currentNode)) { + return true; + } + } + + return false; +} + +/** + * Determines whether the given node is a `null` literal. + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the node is a `null` literal + */ +function isNullLiteral(node) { + + /* + * Checking `node.value === null` does not guarantee that a literal is a null literal. + * When parsing values that cannot be represented in the current environment (e.g. unicode + * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to + * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check + * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020 + */ + return node.type === "Literal" && node.value === null && !node.regex && !node.bigint; +} + +/** + * Checks whether or not a node is `null` or `undefined`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `null` or `undefined`. + * @public + */ +function isNullOrUndefined(node) { + return ( + isNullLiteral(node) || + (node.type === "Identifier" && node.name === "undefined") || + (node.type === "UnaryExpression" && node.operator === "void") + ); +} + +/** + * Checks whether or not a node is callee. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is callee. + */ +function isCallee(node) { + return node.parent.type === "CallExpression" && node.parent.callee === node; +} + +/** + * Returns the result of the string conversion applied to the evaluated value of the given expression node, + * if it can be determined statically. + * + * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only. + * In all other cases, this function returns `null`. + * @param {ASTNode} node Expression node. + * @returns {string|null} String value if it can be determined. Otherwise, `null`. + */ +function getStaticStringValue(node) { + switch (node.type) { + case "Literal": + if (node.value === null) { + if (isNullLiteral(node)) { + return String(node.value); // "null" + } + if (node.regex) { + return `/${node.regex.pattern}/${node.regex.flags}`; + } + if (node.bigint) { + return node.bigint; + } + + // Otherwise, this is an unknown literal. The function will return null. + + } else { + return String(node.value); + } + break; + case "TemplateLiteral": + if (node.expressions.length === 0 && node.quasis.length === 1) { + return node.quasis[0].value.cooked; + } + break; + + // no default + } + + return null; +} + +/** + * Gets the property name of a given node. + * The node can be a MemberExpression, a Property, or a MethodDefinition. + * + * If the name is dynamic, this returns `null`. + * + * For examples: + * + * a.b // => "b" + * a["b"] // => "b" + * a['b'] // => "b" + * a[`b`] // => "b" + * a[100] // => "100" + * a[b] // => null + * a["a" + "b"] // => null + * a[tag`b`] // => null + * a[`${b}`] // => null + * + * let a = {b: 1} // => "b" + * let a = {["b"]: 1} // => "b" + * let a = {['b']: 1} // => "b" + * let a = {[`b`]: 1} // => "b" + * let a = {[100]: 1} // => "100" + * let a = {[b]: 1} // => null + * let a = {["a" + "b"]: 1} // => null + * let a = {[tag`b`]: 1} // => null + * let a = {[`${b}`]: 1} // => null + * @param {ASTNode} node The node to get. + * @returns {string|null} The property name if static. Otherwise, null. + */ +function getStaticPropertyName(node) { + let prop; + + switch (node && node.type) { + case "ChainExpression": + return getStaticPropertyName(node.expression); + + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + prop = node.key; + break; + + case "MemberExpression": + prop = node.property; + break; + + // no default + } + + if (prop) { + if (prop.type === "Identifier" && !node.computed) { + return prop.name; + } + + return getStaticStringValue(prop); + } + + return null; +} + +/** + * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it. + * @param {ASTNode} node The node to address. + * @returns {ASTNode} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node. + */ +function skipChainExpression(node) { + return node && node.type === "ChainExpression" ? node.expression : node; +} + +/** + * Check if the `actual` is an expected value. + * @param {string} actual The string value to check. + * @param {string | RegExp} expected The expected string value or pattern. + * @returns {boolean} `true` if the `actual` is an expected value. + */ +function checkText(actual, expected) { + return typeof expected === "string" + ? actual === expected + : expected.test(actual); +} + +/** + * Check if a given node is an Identifier node with a given name. + * @param {ASTNode} node The node to check. + * @param {string | RegExp} name The expected name or the expected pattern of the object name. + * @returns {boolean} `true` if the node is an Identifier node with the name. + */ +function isSpecificId(node, name) { + return node.type === "Identifier" && checkText(node.name, name); +} + +/** + * Check if a given node is member access with a given object name and property name pair. + * This is regardless of optional or not. + * @param {ASTNode} node The node to check. + * @param {string | RegExp | null} objectName The expected name or the expected pattern of the object name. If this is nullish, this method doesn't check object. + * @param {string | RegExp | null} propertyName The expected name or the expected pattern of the property name. If this is nullish, this method doesn't check property. + * @returns {boolean} `true` if the node is member access with the object name and property name pair. + * The node is a `MemberExpression` or `ChainExpression`. + */ +function isSpecificMemberAccess(node, objectName, propertyName) { + const checkNode = skipChainExpression(node); + + if (checkNode.type !== "MemberExpression") { + return false; + } + + if (objectName && !isSpecificId(checkNode.object, objectName)) { + return false; + } + + if (propertyName) { + const actualPropertyName = getStaticPropertyName(checkNode); + + if (typeof actualPropertyName !== "string" || !checkText(actualPropertyName, propertyName)) { + return false; + } + } + + return true; +} + +/** + * Check if two literal nodes are the same value. + * @param {ASTNode} left The Literal node to compare. + * @param {ASTNode} right The other Literal node to compare. + * @returns {boolean} `true` if the two literal nodes are the same value. + */ +function equalLiteralValue(left, right) { + + // RegExp literal. + if (left.regex || right.regex) { + return Boolean( + left.regex && + right.regex && + left.regex.pattern === right.regex.pattern && + left.regex.flags === right.regex.flags + ); + } + + // BigInt literal. + if (left.bigint || right.bigint) { + return left.bigint === right.bigint; + } + + return left.value === right.value; +} + +/** + * Check if two expressions reference the same value. For example: + * a = a + * a.b = a.b + * a[0] = a[0] + * a['b'] = a['b'] + * @param {ASTNode} left The left side of the comparison. + * @param {ASTNode} right The right side of the comparison. + * @param {boolean} [disableStaticComputedKey] Don't address `a.b` and `a["b"]` are the same if `true`. For backward compatibility. + * @returns {boolean} `true` if both sides match and reference the same value. + */ +function isSameReference(left, right, disableStaticComputedKey = false) { + if (left.type !== right.type) { + + // Handle `a.b` and `a?.b` are samely. + if (left.type === "ChainExpression") { + return isSameReference(left.expression, right, disableStaticComputedKey); + } + if (right.type === "ChainExpression") { + return isSameReference(left, right.expression, disableStaticComputedKey); + } + + return false; + } + + switch (left.type) { + case "Super": + case "ThisExpression": + return true; + + case "Identifier": + case "PrivateIdentifier": + return left.name === right.name; + case "Literal": + return equalLiteralValue(left, right); + + case "ChainExpression": + return isSameReference(left.expression, right.expression, disableStaticComputedKey); + + case "MemberExpression": { + if (!disableStaticComputedKey) { + const nameA = getStaticPropertyName(left); + + // x.y = x["y"] + if (nameA !== null) { + return ( + isSameReference(left.object, right.object, disableStaticComputedKey) && + nameA === getStaticPropertyName(right) + ); + } + } + + /* + * x[0] = x[0] + * x[y] = x[y] + * x.y = x.y + */ + return ( + left.computed === right.computed && + isSameReference(left.object, right.object, disableStaticComputedKey) && + isSameReference(left.property, right.property, disableStaticComputedKey) + ); + } + + default: + return false; + } +} + +/** + * Checks whether or not a node is `Reflect.apply`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `Reflect.apply`. + */ +function isReflectApply(node) { + return isSpecificMemberAccess(node, "Reflect", "apply"); +} + +/** + * Checks whether or not a node is `Array.from`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `Array.from`. + */ +function isArrayFromMethod(node) { + return isSpecificMemberAccess(node, arrayOrTypedArrayPattern, "from"); +} + +/** + * Checks whether or not a node is a method which expects a function as a first argument, and `thisArg` as a second argument. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a method which expects a function as a first argument, and `thisArg` as a second argument. + */ +function isMethodWhichHasThisArg(node) { + return isSpecificMemberAccess(node, null, arrayMethodWithThisArgPattern); +} + +/** + * Creates the negate function of the given function. + * @param {Function} f The function to negate. + * @returns {Function} Negated function. + */ +function negate(f) { + return token => !f(token); +} + +/** + * Checks whether or not a node has a `@this` tag in its comments. + * @param {ASTNode} node A node to check. + * @param {SourceCode} sourceCode A SourceCode instance to get comments. + * @returns {boolean} Whether or not the node has a `@this` tag in its comments. + */ +function hasJSDocThisTag(node, sourceCode) { + const jsdocComment = sourceCode.getJSDocComment(node); + + if (jsdocComment && thisTagPattern.test(jsdocComment.value)) { + return true; + } + + // Checks `@this` in its leading comments for callbacks, + // because callbacks don't have its JSDoc comment. + // e.g. + // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); }); + return sourceCode.getCommentsBefore(node).some(comment => thisTagPattern.test(comment.value)); +} + +/** + * Determines if a node is surrounded by parentheses. + * @param {SourceCode} sourceCode The ESLint source code object + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is parenthesised. + * @private + */ +function isParenthesised(sourceCode, node) { + const previousToken = sourceCode.getTokenBefore(node), + nextToken = sourceCode.getTokenAfter(node); + + return Boolean(previousToken && nextToken) && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; +} + +/** + * Checks if the given token is a `=` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `=` token. + */ +function isEqToken(token) { + return token.value === "=" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an arrow token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an arrow token. + */ +function isArrowToken(token) { + return token.value === "=>" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a comma token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a comma token. + */ +function isCommaToken(token) { + return token.value === "," && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a dot token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a dot token. + */ +function isDotToken(token) { + return token.value === "." && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a `?.` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `?.` token. + */ +function isQuestionDotToken(token) { + return token.value === "?." && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a semicolon token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a semicolon token. + */ +function isSemicolonToken(token) { + return token.value === ";" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a colon token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a colon token. + */ +function isColonToken(token) { + return token.value === ":" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening parenthesis token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening parenthesis token. + */ +function isOpeningParenToken(token) { + return token.value === "(" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing parenthesis token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing parenthesis token. + */ +function isClosingParenToken(token) { + return token.value === ")" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening square bracket token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening square bracket token. + */ +function isOpeningBracketToken(token) { + return token.value === "[" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing square bracket token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing square bracket token. + */ +function isClosingBracketToken(token) { + return token.value === "]" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening brace token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening brace token. + */ +function isOpeningBraceToken(token) { + return token.value === "{" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing brace token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing brace token. + */ +function isClosingBraceToken(token) { + return token.value === "}" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a comment token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a comment token. + */ +function isCommentToken(token) { + return token.type === "Line" || token.type === "Block" || token.type === "Shebang"; +} + +/** + * Checks if the given token is a keyword token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a keyword token. + */ +function isKeywordToken(token) { + return token.type === "Keyword"; +} + +/** + * Gets the `(` token of the given function node. + * @param {ASTNode} node The function node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token} `(` token. + */ +function getOpeningParenOfParams(node, sourceCode) { + + // If the node is an arrow function and doesn't have parens, this returns the identifier of the first param. + if (node.type === "ArrowFunctionExpression" && node.params.length === 1) { + const argToken = sourceCode.getFirstToken(node.params[0]); + const maybeParenToken = sourceCode.getTokenBefore(argToken); + + return isOpeningParenToken(maybeParenToken) ? maybeParenToken : argToken; + } + + // Otherwise, returns paren. + return node.id + ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) + : sourceCode.getFirstToken(node, isOpeningParenToken); +} + +/** + * Checks whether or not the tokens of two given nodes are same. + * @param {ASTNode} left A node 1 to compare. + * @param {ASTNode} right A node 2 to compare. + * @param {SourceCode} sourceCode The ESLint source code object. + * @returns {boolean} the source code for the given node. + */ +function equalTokens(left, right, sourceCode) { + const tokensL = sourceCode.getTokens(left); + const tokensR = sourceCode.getTokens(right); + + if (tokensL.length !== tokensR.length) { + return false; + } + for (let i = 0; i < tokensL.length; ++i) { + if (tokensL[i].type !== tokensR[i].type || + tokensL[i].value !== tokensR[i].value + ) { + return false; + } + } + + return true; +} + +/** + * Check if the given node is a true logical expression or not. + * + * The three binary expressions logical-or (`||`), logical-and (`&&`), and + * coalesce (`??`) are known as `ShortCircuitExpression`. + * But ESTree represents those by `LogicalExpression` node. + * + * This function rejects coalesce expressions of `LogicalExpression` node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `&&` or `||`. + * @see https://tc39.es/ecma262/#prod-ShortCircuitExpression + */ +function isLogicalExpression(node) { + return ( + node.type === "LogicalExpression" && + (node.operator === "&&" || node.operator === "||") + ); +} + +/** + * Check if the given node is a nullish coalescing expression or not. + * + * The three binary expressions logical-or (`||`), logical-and (`&&`), and + * coalesce (`??`) are known as `ShortCircuitExpression`. + * But ESTree represents those by `LogicalExpression` node. + * + * This function finds only coalesce expressions of `LogicalExpression` node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `??`. + */ +function isCoalesceExpression(node) { + return node.type === "LogicalExpression" && node.operator === "??"; +} + +/** + * Check if given two nodes are the pair of a logical expression and a coalesce expression. + * @param {ASTNode} left A node to check. + * @param {ASTNode} right Another node to check. + * @returns {boolean} `true` if the two nodes are the pair of a logical expression and a coalesce expression. + */ +function isMixedLogicalAndCoalesceExpressions(left, right) { + return ( + (isLogicalExpression(left) && isCoalesceExpression(right)) || + (isCoalesceExpression(left) && isLogicalExpression(right)) + ); +} + +/** + * Checks if the given operator is a logical assignment operator. + * @param {string} operator The operator to check. + * @returns {boolean} `true` if the operator is a logical assignment operator. + */ +function isLogicalAssignmentOperator(operator) { + return LOGICAL_ASSIGNMENT_OPERATORS.has(operator); +} + +/** + * Get the colon token of the given SwitchCase node. + * @param {ASTNode} node The SwitchCase node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token} The colon token of the node. + */ +function getSwitchCaseColonToken(node, sourceCode) { + if (node.test) { + return sourceCode.getTokenAfter(node.test, isColonToken); + } + return sourceCode.getFirstToken(node, 1); +} + +/** + * Gets ESM module export name represented by the given node. + * @param {ASTNode} node `Identifier` or string `Literal` node in a position + * that represents a module export name: + * - `ImportSpecifier#imported` + * - `ExportSpecifier#local` (if it is a re-export from another module) + * - `ExportSpecifier#exported` + * - `ExportAllDeclaration#exported` + * @returns {string} The module export name. + */ +function getModuleExportName(node) { + if (node.type === "Identifier") { + return node.name; + } + + // string literal + return node.value; +} + +/** + * Returns literal's value converted to the Boolean type + * @param {ASTNode} node any `Literal` node + * @returns {boolean | null} `true` when node is truthy, `false` when node is falsy, + * `null` when it cannot be determined. + */ +function getBooleanValue(node) { + if (node.value === null) { + + /* + * it might be a null literal or bigint/regex literal in unsupported environments . + * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es5.md#regexpliteral + * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es2020.md#bigintliteral + */ + + if (node.raw === "null") { + return false; + } + + // regex is always truthy + if (typeof node.regex === "object") { + return true; + } + + return null; + } + + return !!node.value; +} + +/** + * Checks if a branch node of LogicalExpression short circuits the whole condition + * @param {ASTNode} node The branch of main condition which needs to be checked + * @param {string} operator The operator of the main LogicalExpression. + * @returns {boolean} true when condition short circuits whole condition + */ +function isLogicalIdentity(node, operator) { + switch (node.type) { + case "Literal": + return (operator === "||" && getBooleanValue(node) === true) || + (operator === "&&" && getBooleanValue(node) === false); + + case "UnaryExpression": + return (operator === "&&" && node.operator === "void"); + + case "LogicalExpression": + + /* + * handles `a && false || b` + * `false` is an identity element of `&&` but not `||` + */ + return operator === node.operator && + ( + isLogicalIdentity(node.left, operator) || + isLogicalIdentity(node.right, operator) + ); + + case "AssignmentExpression": + return ["||=", "&&="].includes(node.operator) && + operator === node.operator.slice(0, -1) && + isLogicalIdentity(node.right, operator); + + // no default + } + return false; +} + +/** + * Checks if an identifier is a reference to a global variable. + * @param {Scope} scope The scope in which the identifier is referenced. + * @param {ASTNode} node An identifier node to check. + * @returns {boolean} `true` if the identifier is a reference to a global variable. + */ +function isReferenceToGlobalVariable(scope, node) { + const reference = scope.references.find(ref => ref.identifier === node); + + return Boolean( + reference && + reference.resolved && + reference.resolved.scope.type === "global" && + reference.resolved.defs.length === 0 + ); +} + + +/** + * Checks if a node has a constant truthiness value. + * @param {Scope} scope Scope in which the node appears. + * @param {ASTNode} node The AST node to check. + * @param {boolean} inBooleanPosition `true` if checking the test of a + * condition. `false` in all other cases. When `false`, checks if -- for + * both string and number -- if coerced to that type, the value will + * be constant. + * @returns {boolean} true when node's truthiness is constant + * @private + */ +function isConstant(scope, node, inBooleanPosition) { + + // node.elements can return null values in the case of sparse arrays ex. [,] + if (!node) { + return true; + } + switch (node.type) { + case "Literal": + case "ArrowFunctionExpression": + case "FunctionExpression": + return true; + case "ClassExpression": + case "ObjectExpression": + + /** + * In theory objects like: + * + * `{toString: () => a}` + * `{valueOf: () => a}` + * + * Or a classes like: + * + * `class { static toString() { return a } }` + * `class { static valueOf() { return a } }` + * + * Are not constant verifiably when `inBooleanPosition` is + * false, but it's an edge case we've opted not to handle. + */ + return true; + case "TemplateLiteral": + return (inBooleanPosition && node.quasis.some(quasi => quasi.value.cooked.length)) || + node.expressions.every(exp => isConstant(scope, exp, false)); + + case "ArrayExpression": { + if (!inBooleanPosition) { + return node.elements.every(element => isConstant(scope, element, false)); + } + return true; + } + + case "UnaryExpression": + if ( + node.operator === "void" || + node.operator === "typeof" && inBooleanPosition + ) { + return true; + } + + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + return isConstant(scope, node.argument, false); + + case "BinaryExpression": + return isConstant(scope, node.left, false) && + isConstant(scope, node.right, false) && + node.operator !== "in"; + + case "LogicalExpression": { + const isLeftConstant = isConstant(scope, node.left, inBooleanPosition); + const isRightConstant = isConstant(scope, node.right, inBooleanPosition); + const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator)); + const isRightShortCircuit = (inBooleanPosition && isRightConstant && isLogicalIdentity(node.right, node.operator)); + + return (isLeftConstant && isRightConstant) || + isLeftShortCircuit || + isRightShortCircuit; + } + case "NewExpression": + return inBooleanPosition; + case "AssignmentExpression": + if (node.operator === "=") { + return isConstant(scope, node.right, inBooleanPosition); + } + + if (["||=", "&&="].includes(node.operator) && inBooleanPosition) { + return isLogicalIdentity(node.right, node.operator.slice(0, -1)); + } + + return false; + + case "SequenceExpression": + return isConstant(scope, node.expressions[node.expressions.length - 1], inBooleanPosition); + case "SpreadElement": + return isConstant(scope, node.argument, inBooleanPosition); + case "CallExpression": + if (node.callee.type === "Identifier" && node.callee.name === "Boolean") { + if (node.arguments.length === 0 || isConstant(scope, node.arguments[0], true)) { + return isReferenceToGlobalVariable(scope, node.callee); + } + } + return false; + case "Identifier": + return node.name === "undefined" && isReferenceToGlobalVariable(scope, node); + + // no default + } + return false; +} + +/** + * Checks whether a node is an ExpressionStatement at the top level of a file or function body. + * A top-level ExpressionStatement node is a directive if it contains a single unparenthesized + * string literal and if it occurs either as the first sibling or immediately after another + * directive. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an ExpressionStatement at the top level of a + * file or function body. + */ +function isTopLevelExpressionStatement(node) { + if (node.type !== "ExpressionStatement") { + return false; + } + const parent = node.parent; + + return parent.type === "Program" || (parent.type === "BlockStatement" && isFunction(parent.parent)); + +} + +/** + * Check whether the given node is a part of a directive prologue or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a part of directive prologue. + */ +function isDirective(node) { + return node.type === "ExpressionStatement" && typeof node.directive === "string"; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + COMMENTS_IGNORE_PATTERN, + LINEBREAKS, + LINEBREAK_MATCHER: lineBreakPattern, + SHEBANG_MATCHER: shebangPattern, + STATEMENT_LIST_PARENTS, + + /** + * Determines whether two adjacent tokens are on the same line. + * @param {Object} left The left token object. + * @param {Object} right The right token object. + * @returns {boolean} Whether or not the tokens are on the same line. + * @public + */ + isTokenOnSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; + }, + + isNullOrUndefined, + isCallee, + isES5Constructor, + getUpperFunction, + isFunction, + isLoop, + isInLoop, + isArrayFromMethod, + isParenthesised, + createGlobalLinebreakMatcher, + equalTokens, + + isArrowToken, + isClosingBraceToken, + isClosingBracketToken, + isClosingParenToken, + isColonToken, + isCommaToken, + isCommentToken, + isDotToken, + isQuestionDotToken, + isKeywordToken, + isNotClosingBraceToken: negate(isClosingBraceToken), + isNotClosingBracketToken: negate(isClosingBracketToken), + isNotClosingParenToken: negate(isClosingParenToken), + isNotColonToken: negate(isColonToken), + isNotCommaToken: negate(isCommaToken), + isNotDotToken: negate(isDotToken), + isNotQuestionDotToken: negate(isQuestionDotToken), + isNotOpeningBraceToken: negate(isOpeningBraceToken), + isNotOpeningBracketToken: negate(isOpeningBracketToken), + isNotOpeningParenToken: negate(isOpeningParenToken), + isNotSemicolonToken: negate(isSemicolonToken), + isOpeningBraceToken, + isOpeningBracketToken, + isOpeningParenToken, + isSemicolonToken, + isEqToken, + + /** + * Checks whether or not a given node is a string literal. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a string literal. + */ + isStringLiteral(node) { + return ( + (node.type === "Literal" && typeof node.value === "string") || + node.type === "TemplateLiteral" + ); + }, + + /** + * Checks whether a given node is a breakable statement or not. + * The node is breakable if the node is one of the following type: + * + * - DoWhileStatement + * - ForInStatement + * - ForOfStatement + * - ForStatement + * - SwitchStatement + * - WhileStatement + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is breakable. + */ + isBreakableStatement(node) { + return breakableTypePattern.test(node.type); + }, + + /** + * Gets references which are non initializer and writable. + * @param {Reference[]} references An array of references. + * @returns {Reference[]} An array of only references which are non initializer and writable. + * @public + */ + getModifyingReferences(references) { + return references.filter(isModifyingReference); + }, + + /** + * Validate that a string passed in is surrounded by the specified character + * @param {string} val The text to check. + * @param {string} character The character to see if it's surrounded by. + * @returns {boolean} True if the text is surrounded by the character, false if not. + * @private + */ + isSurroundedBy(val, character) { + return val[0] === character && val[val.length - 1] === character; + }, + + /** + * Returns whether the provided node is an ESLint directive comment or not + * @param {Line|Block} node The comment token to be checked + * @returns {boolean} `true` if the node is an ESLint directive comment + */ + isDirectiveComment(node) { + const comment = node.value.trim(); + + return ( + node.type === "Line" && comment.startsWith("eslint-") || + node.type === "Block" && ESLINT_DIRECTIVE_PATTERN.test(comment) + ); + }, + + /** + * Gets the trailing statement of a given node. + * + * if (code) + * consequent; + * + * When taking this `IfStatement`, returns `consequent;` statement. + * @param {ASTNode} A node to get. + * @returns {ASTNode|null} The trailing statement's node. + */ + getTrailingStatement: esutils.ast.trailingStatement, + + /** + * Finds the variable by a given name in a given scope and its upper scopes. + * @param {eslint-scope.Scope} initScope A scope to start find. + * @param {string} name A variable name to find. + * @returns {eslint-scope.Variable|null} A found variable or `null`. + */ + getVariableByName(initScope, name) { + let scope = initScope; + + while (scope) { + const variable = scope.set.get(name); + + if (variable) { + return variable; + } + + scope = scope.upper; + } + + return null; + }, + + /** + * Checks whether or not a given function node is the default `this` binding. + * + * First, this checks the node: + * + * - The given node is not in `PropertyDefinition#value` position. + * - The given node is not `StaticBlock`. + * - The function name does not start with uppercase. It's a convention to capitalize the names + * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`. + * - The function does not have a JSDoc comment that has a @this tag. + * + * Next, this checks the location of the node. + * If the location is below, this judges `this` is valid. + * + * - The location is not on an object literal. + * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous + * functions only, as the name of the variable is considered to be the name of the function in this case. + * This check is not performed if `capIsConstructor` is set to `false`. + * - The location is not on an ES2015 class. + * - Its `bind`/`call`/`apply` method is not called directly. + * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given. + * @param {ASTNode} node A function node to check. It also can be an implicit function, like `StaticBlock` + * or any expression that is `PropertyDefinition#value` node. + * @param {SourceCode} sourceCode A SourceCode instance to get comments. + * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts + * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors. + * @returns {boolean} The function node is the default `this` binding. + */ + isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) { + + /* + * Class field initializers are implicit functions, but ESTree doesn't have the AST node of field initializers. + * Therefore, A expression node at `PropertyDefinition#value` is a function. + * In this case, `this` is always not default binding. + */ + if (node.parent.type === "PropertyDefinition" && node.parent.value === node) { + return false; + } + + // Class static blocks are implicit functions. In this case, `this` is always not default binding. + if (node.type === "StaticBlock") { + return false; + } + + if ( + (capIsConstructor && isES5Constructor(node)) || + hasJSDocThisTag(node, sourceCode) + ) { + return false; + } + const isAnonymous = node.id === null; + let currentNode = node; + + while (currentNode) { + const parent = currentNode.parent; + + switch (parent.type) { + + /* + * Looks up the destination. + * e.g., obj.foo = nativeFoo || function foo() { ... }; + */ + case "LogicalExpression": + case "ConditionalExpression": + case "ChainExpression": + currentNode = parent; + break; + + /* + * If the upper function is IIFE, checks the destination of the return value. + * e.g. + * obj.foo = (function() { + * // setup... + * return function foo() { ... }; + * })(); + * obj.foo = (() => + * function foo() { ... } + * )(); + */ + case "ReturnStatement": { + const func = getUpperFunction(parent); + + if (func === null || !isCallee(func)) { + return true; + } + currentNode = func.parent; + break; + } + case "ArrowFunctionExpression": + if (currentNode !== parent.body || !isCallee(parent)) { + return true; + } + currentNode = parent.parent; + break; + + /* + * e.g. + * var obj = { foo() { ... } }; + * var obj = { foo: function() { ... } }; + * class A { constructor() { ... } } + * class A { foo() { ... } } + * class A { get foo() { ... } } + * class A { set foo() { ... } } + * class A { static foo() { ... } } + * class A { foo = function() { ... } } + */ + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return parent.value !== currentNode; + + /* + * e.g. + * obj.foo = function foo() { ... }; + * Foo = function() { ... }; + * [obj.foo = function foo() { ... }] = a; + * [Foo = function() { ... }] = a; + */ + case "AssignmentExpression": + case "AssignmentPattern": + if (parent.left.type === "MemberExpression") { + return false; + } + if ( + capIsConstructor && + isAnonymous && + parent.left.type === "Identifier" && + startsWithUpperCase(parent.left.name) + ) { + return false; + } + return true; + + /* + * e.g. + * var Foo = function() { ... }; + */ + case "VariableDeclarator": + return !( + capIsConstructor && + isAnonymous && + parent.init === currentNode && + parent.id.type === "Identifier" && + startsWithUpperCase(parent.id.name) + ); + + /* + * e.g. + * var foo = function foo() { ... }.bind(obj); + * (function foo() { ... }).call(obj); + * (function foo() { ... }).apply(obj, []); + */ + case "MemberExpression": + if ( + parent.object === currentNode && + isSpecificMemberAccess(parent, null, bindOrCallOrApplyPattern) + ) { + const maybeCalleeNode = parent.parent.type === "ChainExpression" + ? parent.parent + : parent; + + return !( + isCallee(maybeCalleeNode) && + maybeCalleeNode.parent.arguments.length >= 1 && + !isNullOrUndefined(maybeCalleeNode.parent.arguments[0]) + ); + } + return true; + + /* + * e.g. + * Reflect.apply(function() {}, obj, []); + * Array.from([], function() {}, obj); + * list.forEach(function() {}, obj); + */ + case "CallExpression": + if (isReflectApply(parent.callee)) { + return ( + parent.arguments.length !== 3 || + parent.arguments[0] !== currentNode || + isNullOrUndefined(parent.arguments[1]) + ); + } + if (isArrayFromMethod(parent.callee)) { + return ( + parent.arguments.length !== 3 || + parent.arguments[1] !== currentNode || + isNullOrUndefined(parent.arguments[2]) + ); + } + if (isMethodWhichHasThisArg(parent.callee)) { + return ( + parent.arguments.length !== 2 || + parent.arguments[0] !== currentNode || + isNullOrUndefined(parent.arguments[1]) + ); + } + return true; + + // Otherwise `this` is default. + default: + return true; + } + } + + /* c8 ignore next */ + return true; + }, + + /** + * Get the precedence level based on the node type + * @param {ASTNode} node node to evaluate + * @returns {int} precedence level + * @private + */ + getPrecedence(node) { + switch (node.type) { + case "SequenceExpression": + return 0; + + case "AssignmentExpression": + case "ArrowFunctionExpression": + case "YieldExpression": + return 1; + + case "ConditionalExpression": + return 3; + + case "LogicalExpression": + switch (node.operator) { + case "||": + case "??": + return 4; + case "&&": + return 5; + + // no default + } + + /* falls through */ + + case "BinaryExpression": + + switch (node.operator) { + case "|": + return 6; + case "^": + return 7; + case "&": + return 8; + case "==": + case "!=": + case "===": + case "!==": + return 9; + case "<": + case "<=": + case ">": + case ">=": + case "in": + case "instanceof": + return 10; + case "<<": + case ">>": + case ">>>": + return 11; + case "+": + case "-": + return 12; + case "*": + case "/": + case "%": + return 13; + case "**": + return 15; + + // no default + } + + /* falls through */ + + case "UnaryExpression": + case "AwaitExpression": + return 16; + + case "UpdateExpression": + return 17; + + case "CallExpression": + case "ChainExpression": + case "ImportExpression": + return 18; + + case "NewExpression": + return 19; + + default: + if (node.type in eslintVisitorKeys) { + return 20; + } + + /* + * if the node is not a standard node that we know about, then assume it has the lowest precedence + * this will mean that rules will wrap unknown nodes in parentheses where applicable instead of + * unwrapping them and potentially changing the meaning of the code or introducing a syntax error. + */ + return -1; + } + }, + + /** + * Checks whether the given node is an empty block node or not. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is an empty block. + */ + isEmptyBlock(node) { + return Boolean(node && node.type === "BlockStatement" && node.body.length === 0); + }, + + /** + * Checks whether the given node is an empty function node or not. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is an empty function. + */ + isEmptyFunction(node) { + return isFunction(node) && module.exports.isEmptyBlock(node.body); + }, + + /** + * Get directives from directive prologue of a Program or Function node. + * @param {ASTNode} node The node to check. + * @returns {ASTNode[]} The directives found in the directive prologue. + */ + getDirectivePrologue(node) { + const directives = []; + + // Directive prologues only occur at the top of files or functions. + if ( + node.type === "Program" || + node.type === "FunctionDeclaration" || + node.type === "FunctionExpression" || + + /* + * Do not check arrow functions with implicit return. + * `() => "use strict";` returns the string `"use strict"`. + */ + (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement") + ) { + const statements = node.type === "Program" ? node.body : node.body.body; + + for (const statement of statements) { + if ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" + ) { + directives.push(statement); + } else { + break; + } + } + } + + return directives; + }, + + /** + * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added + * after the node will be parsed as a decimal point, rather than a property-access dot. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if this node is a decimal integer. + * @example + * + * 0 // true + * 5 // true + * 50 // true + * 5_000 // true + * 1_234_56 // true + * 08 // true + * 0192 // true + * 5. // false + * .5 // false + * 5.0 // false + * 5.00_00 // false + * 05 // false + * 0x5 // false + * 0b101 // false + * 0b11_01 // false + * 0o5 // false + * 5e0 // false + * 5e1_000 // false + * 5n // false + * 1_000n // false + * "5" // false + * + */ + isDecimalInteger(node) { + return node.type === "Literal" && typeof node.value === "number" && + DECIMAL_INTEGER_PATTERN.test(node.raw); + }, + + /** + * Determines whether this token is a decimal integer numeric token. + * This is similar to isDecimalInteger(), but for tokens. + * @param {Token} token The token to check. + * @returns {boolean} `true` if this token is a decimal integer. + */ + isDecimalIntegerNumericToken(token) { + return token.type === "Numeric" && DECIMAL_INTEGER_PATTERN.test(token.value); + }, + + /** + * Gets the name and kind of the given function node. + * + * - `function foo() {}` .................... `function 'foo'` + * - `(function foo() {})` .................. `function 'foo'` + * - `(function() {})` ...................... `function` + * - `function* foo() {}` ................... `generator function 'foo'` + * - `(function* foo() {})` ................. `generator function 'foo'` + * - `(function*() {})` ..................... `generator function` + * - `() => {}` ............................. `arrow function` + * - `async () => {}` ....................... `async arrow function` + * - `({ foo: function foo() {} })` ......... `method 'foo'` + * - `({ foo: function() {} })` ............. `method 'foo'` + * - `({ ['foo']: function() {} })` ......... `method 'foo'` + * - `({ [foo]: function() {} })` ........... `method` + * - `({ foo() {} })` ....................... `method 'foo'` + * - `({ foo: function* foo() {} })` ........ `generator method 'foo'` + * - `({ foo: function*() {} })` ............ `generator method 'foo'` + * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'` + * - `({ [foo]: function*() {} })` .......... `generator method` + * - `({ *foo() {} })` ...................... `generator method 'foo'` + * - `({ foo: async function foo() {} })` ... `async method 'foo'` + * - `({ foo: async function() {} })` ....... `async method 'foo'` + * - `({ ['foo']: async function() {} })` ... `async method 'foo'` + * - `({ [foo]: async function() {} })` ..... `async method` + * - `({ async foo() {} })` ................. `async method 'foo'` + * - `({ get foo() {} })` ................... `getter 'foo'` + * - `({ set foo(a) {} })` .................. `setter 'foo'` + * - `class A { constructor() {} }` ......... `constructor` + * - `class A { foo() {} }` ................. `method 'foo'` + * - `class A { *foo() {} }` ................ `generator method 'foo'` + * - `class A { async foo() {} }` ........... `async method 'foo'` + * - `class A { ['foo']() {} }` ............. `method 'foo'` + * - `class A { *['foo']() {} }` ............ `generator method 'foo'` + * - `class A { async ['foo']() {} }` ....... `async method 'foo'` + * - `class A { [foo]() {} }` ............... `method` + * - `class A { *[foo]() {} }` .............. `generator method` + * - `class A { async [foo]() {} }` ......... `async method` + * - `class A { get foo() {} }` ............. `getter 'foo'` + * - `class A { set foo(a) {} }` ............ `setter 'foo'` + * - `class A { static foo() {} }` .......... `static method 'foo'` + * - `class A { static *foo() {} }` ......... `static generator method 'foo'` + * - `class A { static async foo() {} }` .... `static async method 'foo'` + * - `class A { static get foo() {} }` ...... `static getter 'foo'` + * - `class A { static set foo(a) {} }` ..... `static setter 'foo'` + * - `class A { foo = () => {}; }` .......... `method 'foo'` + * - `class A { foo = function() {}; }` ..... `method 'foo'` + * - `class A { foo = function bar() {}; }` . `method 'foo'` + * - `class A { static foo = () => {}; }` ... `static method 'foo'` + * - `class A { '#foo' = () => {}; }` ....... `method '#foo'` + * - `class A { #foo = () => {}; }` ......... `private method #foo` + * - `class A { static #foo = () => {}; }` .. `static private method #foo` + * - `class A { '#foo'() {} }` .............. `method '#foo'` + * - `class A { #foo() {} }` ................ `private method #foo` + * - `class A { static #foo() {} }` ......... `static private method #foo` + * @param {ASTNode} node The function node to get. + * @returns {string} The name and kind of the function node. + */ + getFunctionNameWithKind(node) { + const parent = node.parent; + const tokens = []; + + if (parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") { + + // The proposal uses `static` word consistently before visibility words: https://github.com/tc39/proposal-static-class-features + if (parent.static) { + tokens.push("static"); + } + if (!parent.computed && parent.key.type === "PrivateIdentifier") { + tokens.push("private"); + } + } + if (node.async) { + tokens.push("async"); + } + if (node.generator) { + tokens.push("generator"); + } + + if (parent.type === "Property" || parent.type === "MethodDefinition") { + if (parent.kind === "constructor") { + return "constructor"; + } + if (parent.kind === "get") { + tokens.push("getter"); + } else if (parent.kind === "set") { + tokens.push("setter"); + } else { + tokens.push("method"); + } + } else if (parent.type === "PropertyDefinition") { + tokens.push("method"); + } else { + if (node.type === "ArrowFunctionExpression") { + tokens.push("arrow"); + } + tokens.push("function"); + } + + if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") { + if (!parent.computed && parent.key.type === "PrivateIdentifier") { + tokens.push(`#${parent.key.name}`); + } else { + const name = getStaticPropertyName(parent); + + if (name !== null) { + tokens.push(`'${name}'`); + } else if (node.id) { + tokens.push(`'${node.id.name}'`); + } + } + } else if (node.id) { + tokens.push(`'${node.id.name}'`); + } + + return tokens.join(" "); + }, + + /** + * Gets the location of the given function node for reporting. + * + * - `function foo() {}` + * ^^^^^^^^^^^^ + * - `(function foo() {})` + * ^^^^^^^^^^^^ + * - `(function() {})` + * ^^^^^^^^ + * - `function* foo() {}` + * ^^^^^^^^^^^^^ + * - `(function* foo() {})` + * ^^^^^^^^^^^^^ + * - `(function*() {})` + * ^^^^^^^^^ + * - `() => {}` + * ^^ + * - `async () => {}` + * ^^ + * - `({ foo: function foo() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ foo: function() {} })` + * ^^^^^^^^^^^^^ + * - `({ ['foo']: function() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function() {} })` + * ^^^^^^^^^^^^^^^ + * - `({ foo() {} })` + * ^^^ + * - `({ foo: function* foo() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ foo: function*() {} })` + * ^^^^^^^^^^^^^^ + * - `({ ['foo']: function*() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function*() {} })` + * ^^^^^^^^^^^^^^^^ + * - `({ *foo() {} })` + * ^^^^ + * - `({ foo: async function foo() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ foo: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^ + * - `({ ['foo']: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `({ async foo() {} })` + * ^^^^^^^^^ + * - `({ get foo() {} })` + * ^^^^^^^ + * - `({ set foo(a) {} })` + * ^^^^^^^ + * - `class A { constructor() {} }` + * ^^^^^^^^^^^ + * - `class A { foo() {} }` + * ^^^ + * - `class A { *foo() {} }` + * ^^^^ + * - `class A { async foo() {} }` + * ^^^^^^^^^ + * - `class A { ['foo']() {} }` + * ^^^^^^^ + * - `class A { *['foo']() {} }` + * ^^^^^^^^ + * - `class A { async ['foo']() {} }` + * ^^^^^^^^^^^^^ + * - `class A { [foo]() {} }` + * ^^^^^ + * - `class A { *[foo]() {} }` + * ^^^^^^ + * - `class A { async [foo]() {} }` + * ^^^^^^^^^^^ + * - `class A { get foo() {} }` + * ^^^^^^^ + * - `class A { set foo(a) {} }` + * ^^^^^^^ + * - `class A { static foo() {} }` + * ^^^^^^^^^^ + * - `class A { static *foo() {} }` + * ^^^^^^^^^^^ + * - `class A { static async foo() {} }` + * ^^^^^^^^^^^^^^^^ + * - `class A { static get foo() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static set foo(a) {} }` + * ^^^^^^^^^^^^^^ + * - `class A { foo = function() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static foo = function() {} }` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `class A { foo = (a, b) => {} }` + * ^^^^^^ + * @param {ASTNode} node The function node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {string} The location of the function node for reporting. + */ + getFunctionHeadLoc(node, sourceCode) { + const parent = node.parent; + let start = null; + let end = null; + + if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") { + start = parent.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } else if (node.type === "ArrowFunctionExpression") { + const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken); + + start = arrowToken.loc.start; + end = arrowToken.loc.end; + } else { + start = node.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + + return { + start: Object.assign({}, start), + end: Object.assign({}, end) + }; + }, + + /** + * Gets next location when the result is not out of bound, otherwise returns null. + * + * Assumptions: + * + * - The given location represents a valid location in the given source code. + * - Columns are 0-based. + * - Lines are 1-based. + * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location. + * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end. + * The start (column 0) of that extra line is considered to be a valid location. + * + * Examples of successive locations (line, column): + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null + * + * code: a + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null + * + * code: + * locations: (1, 0) -> (2, 0) -> null + * + * code: + * locations: (1, 0) -> null + * @param {SourceCode} sourceCode The sourceCode + * @param {{line: number, column: number}} location The location + * @returns {{line: number, column: number} | null} Next location + */ + getNextLocation(sourceCode, { line, column }) { + if (column < sourceCode.lines[line - 1].length) { + return { + line, + column: column + 1 + }; + } + + if (line < sourceCode.lines.length) { + return { + line: line + 1, + column: 0 + }; + } + + return null; + }, + + /** + * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses + * surrounding the node. + * @param {SourceCode} sourceCode The source code object + * @param {ASTNode} node An expression node + * @returns {string} The text representing the node, with all surrounding parentheses included + */ + getParenthesisedText(sourceCode, node) { + let leftToken = sourceCode.getFirstToken(node); + let rightToken = sourceCode.getLastToken(node); + + while ( + sourceCode.getTokenBefore(leftToken) && + sourceCode.getTokenBefore(leftToken).type === "Punctuator" && + sourceCode.getTokenBefore(leftToken).value === "(" && + sourceCode.getTokenAfter(rightToken) && + sourceCode.getTokenAfter(rightToken).type === "Punctuator" && + sourceCode.getTokenAfter(rightToken).value === ")" + ) { + leftToken = sourceCode.getTokenBefore(leftToken); + rightToken = sourceCode.getTokenAfter(rightToken); + } + + return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]); + }, + + /** + * Determine if a node has a possibility to be an Error object + * @param {ASTNode} node ASTNode to check + * @returns {boolean} True if there is a chance it contains an Error obj + */ + couldBeError(node) { + switch (node.type) { + case "Identifier": + case "CallExpression": + case "NewExpression": + case "MemberExpression": + case "TaggedTemplateExpression": + case "YieldExpression": + case "AwaitExpression": + case "ChainExpression": + return true; // possibly an error object. + + case "AssignmentExpression": + if (["=", "&&="].includes(node.operator)) { + return module.exports.couldBeError(node.right); + } + + if (["||=", "??="].includes(node.operator)) { + return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right); + } + + /** + * All other assignment operators are mathematical assignment operators (arithmetic or bitwise). + * An assignment expression with a mathematical operator can either evaluate to a primitive value, + * or throw, depending on the operands. Thus, it cannot evaluate to an `Error` object. + */ + return false; + + case "SequenceExpression": { + const exprs = node.expressions; + + return exprs.length !== 0 && module.exports.couldBeError(exprs[exprs.length - 1]); + } + + case "LogicalExpression": + + /* + * If the && operator short-circuits, the left side was falsy and therefore not an error, and if it + * doesn't short-circuit, it takes the value from the right side, so the right side must always be + * a plausible error. A future improvement could verify that the left side could be truthy by + * excluding falsy literals. + */ + if (node.operator === "&&") { + return module.exports.couldBeError(node.right); + } + + return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right); + + case "ConditionalExpression": + return module.exports.couldBeError(node.consequent) || module.exports.couldBeError(node.alternate); + + default: + return false; + } + }, + + /** + * Check if a given node is a numeric literal or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a number or bigint literal. + */ + isNumericLiteral(node) { + return ( + node.type === "Literal" && + (typeof node.value === "number" || Boolean(node.bigint)) + ); + }, + + /** + * Determines whether two tokens can safely be placed next to each other without merging into a single token + * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used. + * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used. + * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed + * next to each other, behavior is undefined (although it should return `true` in most cases). + */ + canTokensBeAdjacent(leftValue, rightValue) { + const espreeOptions = { + ecmaVersion: espree.latestEcmaVersion, + comment: true, + range: true + }; + + let leftToken; + + if (typeof leftValue === "string") { + let tokens; + + try { + tokens = espree.tokenize(leftValue, espreeOptions); + } catch { + return false; + } + + const comments = tokens.comments; + + leftToken = tokens[tokens.length - 1]; + if (comments.length) { + const lastComment = comments[comments.length - 1]; + + if (!leftToken || lastComment.range[0] > leftToken.range[0]) { + leftToken = lastComment; + } + } + } else { + leftToken = leftValue; + } + + /* + * If a hashbang comment was passed as a token object from SourceCode, + * its type will be "Shebang" because of the way ESLint itself handles hashbangs. + * If a hashbang comment was passed in a string and then tokenized in this function, + * its type will be "Hashbang" because of the way Espree tokenizes hashbangs. + */ + if (leftToken.type === "Shebang" || leftToken.type === "Hashbang") { + return false; + } + + let rightToken; + + if (typeof rightValue === "string") { + let tokens; + + try { + tokens = espree.tokenize(rightValue, espreeOptions); + } catch { + return false; + } + + const comments = tokens.comments; + + rightToken = tokens[0]; + if (comments.length) { + const firstComment = comments[0]; + + if (!rightToken || firstComment.range[0] < rightToken.range[0]) { + rightToken = firstComment; + } + } + } else { + rightToken = rightValue; + } + + if (leftToken.type === "Punctuator" || rightToken.type === "Punctuator") { + if (leftToken.type === "Punctuator" && rightToken.type === "Punctuator") { + const PLUS_TOKENS = new Set(["+", "++"]); + const MINUS_TOKENS = new Set(["-", "--"]); + + return !( + PLUS_TOKENS.has(leftToken.value) && PLUS_TOKENS.has(rightToken.value) || + MINUS_TOKENS.has(leftToken.value) && MINUS_TOKENS.has(rightToken.value) + ); + } + if (leftToken.type === "Punctuator" && leftToken.value === "/") { + return !["Block", "Line", "RegularExpression"].includes(rightToken.type); + } + return true; + } + + if ( + leftToken.type === "String" || rightToken.type === "String" || + leftToken.type === "Template" || rightToken.type === "Template" + ) { + return true; + } + + if (leftToken.type !== "Numeric" && rightToken.type === "Numeric" && rightToken.value.startsWith(".")) { + return true; + } + + if (leftToken.type === "Block" || rightToken.type === "Block" || rightToken.type === "Line") { + return true; + } + + if (rightToken.type === "PrivateIdentifier") { + return true; + } + + return false; + }, + + /** + * Get the `loc` object of a given name in a `/*globals` directive comment. + * @param {SourceCode} sourceCode The source code to convert index to loc. + * @param {Comment} comment The `/*globals` directive comment which include the name. + * @param {string} name The name to find. + * @returns {SourceLocation} The `loc` object. + */ + getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) { + const namePattern = new RegExp(`[\\s,]${escapeRegExp(name)}(?:$|[\\s,:])`, "gu"); + + // To ignore the first text "global". + namePattern.lastIndex = comment.value.indexOf("global") + 6; + + // Search a given variable name. + const match = namePattern.exec(comment.value); + + // Convert the index to loc. + const start = sourceCode.getLocFromIndex( + comment.range[0] + + "/*".length + + (match ? match.index + 1 : 0) + ); + const end = { + line: start.line, + column: start.column + (match ? name.length : 1) + }; + + return { start, end }; + }, + + /** + * Determines whether the given raw string contains an octal escape sequence + * or a non-octal decimal escape sequence ("\8", "\9"). + * + * "\1", "\2" ... "\7", "\8", "\9" + * "\00", "\01" ... "\07", "\08", "\09" + * + * "\0", when not followed by a digit, is not an octal escape sequence. + * @param {string} rawString A string in its raw representation. + * @returns {boolean} `true` if the string contains at least one octal escape sequence + * or at least one non-octal decimal escape sequence. + */ + hasOctalOrNonOctalDecimalEscapeSequence(rawString) { + return OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN.test(rawString); + }, + + /** + * Determines whether the given node is a template literal without expressions. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a template literal without expressions. + */ + isStaticTemplateLiteral(node) { + return node.type === "TemplateLiteral" && node.expressions.length === 0; + }, + + isReferenceToGlobalVariable, + isLogicalExpression, + isCoalesceExpression, + isMixedLogicalAndCoalesceExpressions, + isNullLiteral, + getStaticStringValue, + getStaticPropertyName, + skipChainExpression, + isSpecificId, + isSpecificMemberAccess, + equalLiteralValue, + isSameReference, + isLogicalAssignmentOperator, + getSwitchCaseColonToken, + getModuleExportName, + isConstant, + isTopLevelExpressionStatement, + isDirective +}; diff --git a/node_modules/eslint/lib/rules/utils/fix-tracker.js b/node_modules/eslint/lib/rules/utils/fix-tracker.js new file mode 100644 index 0000000..589870b --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/fix-tracker.js @@ -0,0 +1,114 @@ +/** + * @fileoverview Helper class to aid in constructing fix commands. + * @author Alan Pierce + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./ast-utils"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A helper class to combine fix options into a fix command. Currently, it + * exposes some "retain" methods that extend the range of the text being + * replaced so that other fixes won't touch that region in the same pass. + */ +class FixTracker { + + /** + * Create a new FixTracker. + * @param {ruleFixer} fixer A ruleFixer instance. + * @param {SourceCode} sourceCode A SourceCode object for the current code. + */ + constructor(fixer, sourceCode) { + this.fixer = fixer; + this.sourceCode = sourceCode; + this.retainedRange = null; + } + + /** + * Mark the given range as "retained", meaning that other fixes may not + * may not modify this region in the same pass. + * @param {int[]} range The range to retain. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainRange(range) { + this.retainedRange = range; + return this; + } + + /** + * Given a node, find the function containing it (or the entire program) and + * mark it as retained, meaning that other fixes may not modify it in this + * pass. This is useful for avoiding conflicts in fixes that modify control + * flow. + * @param {ASTNode} node The node to use as a starting point. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainEnclosingFunction(node) { + const functionNode = astUtils.getUpperFunction(node); + + return this.retainRange(functionNode ? functionNode.range : this.sourceCode.ast.range); + } + + /** + * Given a node or token, find the token before and afterward, and mark that + * range as retained, meaning that other fixes may not modify it in this + * pass. This is useful for avoiding conflicts in fixes that make a small + * change to the code where the AST should not be changed. + * @param {ASTNode|Token} nodeOrToken The node or token to use as a starting + * point. The token to the left and right are use in the range. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainSurroundingTokens(nodeOrToken) { + const tokenBefore = this.sourceCode.getTokenBefore(nodeOrToken) || nodeOrToken; + const tokenAfter = this.sourceCode.getTokenAfter(nodeOrToken) || nodeOrToken; + + return this.retainRange([tokenBefore.range[0], tokenAfter.range[1]]); + } + + /** + * Create a fix command that replaces the given range with the given text, + * accounting for any retained ranges. + * @param {int[]} range The range to remove in the fix. + * @param {string} text The text to insert in place of the range. + * @returns {Object} The fix command. + */ + replaceTextRange(range, text) { + let actualRange; + + if (this.retainedRange) { + actualRange = [ + Math.min(this.retainedRange[0], range[0]), + Math.max(this.retainedRange[1], range[1]) + ]; + } else { + actualRange = range; + } + + return this.fixer.replaceTextRange( + actualRange, + this.sourceCode.text.slice(actualRange[0], range[0]) + + text + + this.sourceCode.text.slice(range[1], actualRange[1]) + ); + } + + /** + * Create a fix command that removes the given node or token, accounting for + * any retained ranges. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @returns {Object} The fix command. + */ + remove(nodeOrToken) { + return this.replaceTextRange(nodeOrToken.range, ""); + } +} + +module.exports = FixTracker; diff --git a/node_modules/eslint/lib/rules/utils/keywords.js b/node_modules/eslint/lib/rules/utils/keywords.js new file mode 100644 index 0000000..3fbb777 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/keywords.js @@ -0,0 +1,67 @@ +/** + * @fileoverview A shared list of ES3 keywords. + * @author Josh Perez + */ +"use strict"; + +module.exports = [ + "abstract", + "boolean", + "break", + "byte", + "case", + "catch", + "char", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "double", + "else", + "enum", + "export", + "extends", + "false", + "final", + "finally", + "float", + "for", + "function", + "goto", + "if", + "implements", + "import", + "in", + "instanceof", + "int", + "interface", + "long", + "native", + "new", + "null", + "package", + "private", + "protected", + "public", + "return", + "short", + "static", + "super", + "switch", + "synchronized", + "this", + "throw", + "throws", + "transient", + "true", + "try", + "typeof", + "var", + "void", + "volatile", + "while", + "with" +]; diff --git a/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js b/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js new file mode 100644 index 0000000..7f116a2 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js @@ -0,0 +1,115 @@ +/** + * @fileoverview `Map` to load rules lazily. + * @author Toru Nagashima + */ +"use strict"; + +const debug = require("debug")("eslint:rules"); + +/** @typedef {import("./types").Rule} Rule */ + +/** + * The `Map` object that loads each rule when it's accessed. + * @example + * const rules = new LazyLoadingRuleMap([ + * ["eqeqeq", () => require("eqeqeq")], + * ["semi", () => require("semi")], + * ["no-unused-vars", () => require("no-unused-vars")] + * ]); + * + * rules.get("semi"); // call `() => require("semi")` here. + * + * @extends {Map Rule>} + */ +class LazyLoadingRuleMap extends Map { + + /** + * Initialize this map. + * @param {Array<[string, function(): Rule]>} loaders The rule loaders. + */ + constructor(loaders) { + let remaining = loaders.length; + + super( + debug.enabled + ? loaders.map(([ruleId, load]) => { + let cache = null; + + return [ + ruleId, + () => { + if (!cache) { + debug("Loading rule %o (remaining=%d)", ruleId, --remaining); + cache = load(); + } + return cache; + } + ]; + }) + : loaders + ); + + // `super(...iterable)` uses `this.set()`, so disable it here. + Object.defineProperty(LazyLoadingRuleMap.prototype, "set", { + configurable: true, + value: void 0 + }); + } + + /** + * Get a rule. + * Each rule will be loaded on the first access. + * @param {string} ruleId The rule ID to get. + * @returns {Rule|undefined} The rule. + */ + get(ruleId) { + const load = super.get(ruleId); + + return load && load(); + } + + /** + * Iterate rules. + * @returns {IterableIterator} Rules. + */ + *values() { + for (const load of super.values()) { + yield load(); + } + } + + /** + * Iterate rules. + * @returns {IterableIterator<[string, Rule]>} Rules. + */ + *entries() { + for (const [ruleId, load] of super.entries()) { + yield [ruleId, load()]; + } + } + + /** + * Call a function with each rule. + * @param {Function} callbackFn The callback function. + * @param {any} [thisArg] The object to pass to `this` of the callback function. + * @returns {void} + */ + forEach(callbackFn, thisArg) { + for (const [ruleId, load] of super.entries()) { + callbackFn.call(thisArg, load(), ruleId, this); + } + } +} + +// Forbid mutation. +Object.defineProperties(LazyLoadingRuleMap.prototype, { + clear: { configurable: true, value: void 0 }, + delete: { configurable: true, value: void 0 }, + [Symbol.iterator]: { + configurable: true, + writable: true, + value: LazyLoadingRuleMap.prototype.entries + } +}); + +module.exports = { LazyLoadingRuleMap }; diff --git a/node_modules/eslint/lib/rules/utils/patterns/letters.js b/node_modules/eslint/lib/rules/utils/patterns/letters.js new file mode 100644 index 0000000..9bb2de3 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/patterns/letters.js @@ -0,0 +1,36 @@ +/** + * @fileoverview Pattern for detecting any letter (even letters outside of ASCII). + * NOTE: This file was generated using this script in JSCS based on the Unicode 7.0.0 standard: https://github.com/jscs-dev/node-jscs/blob/f5ed14427deb7e7aac84f3056a5aab2d9f3e563e/publish/helpers/generate-patterns.js + * Do not edit this file by hand-- please use https://github.com/mathiasbynens/regenerate to regenerate the regular expression exported from this file. + * @author Kevin Partington + * @license MIT License (from JSCS). See below. + */ + +/* + * The MIT License (MIT) + * + * Copyright 2013-2016 Dulin Marat and other contributors + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +"use strict"; + +module.exports = /[A-Za-z\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-\u08B2\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\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\u0C59\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\u0D60\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-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\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\u19C1-\u19C7\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\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\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]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\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]|\uD87E[\uDC00-\uDE1D]/u; diff --git a/node_modules/eslint/lib/rules/utils/regular-expressions.js b/node_modules/eslint/lib/rules/utils/regular-expressions.js new file mode 100644 index 0000000..12e544e --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/regular-expressions.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Common utils for regular expressions. + * @author Josh Goldberg + * @author Toru Nagashima + */ + +"use strict"; + +const { RegExpValidator } = require("@eslint-community/regexpp"); + +const REGEXPP_LATEST_ECMA_VERSION = 2024; + +/** + * Checks if the given regular expression pattern would be valid with the `u` flag. + * @param {number} ecmaVersion ECMAScript version to parse in. + * @param {string} pattern The regular expression pattern to verify. + * @returns {boolean} `true` if the pattern would be valid with the `u` flag. + * `false` if the pattern would be invalid with the `u` flag or the configured + * ecmaVersion doesn't support the `u` flag. + */ +function isValidWithUnicodeFlag(ecmaVersion, pattern) { + if (ecmaVersion <= 5) { // ecmaVersion <= 5 doesn't support the 'u' flag + return false; + } + + const validator = new RegExpValidator({ + ecmaVersion: Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION) + }); + + try { + validator.validatePattern(pattern, void 0, void 0, { unicode: /* uFlag = */ true }); + } catch { + return false; + } + + return true; +} + +module.exports = { + isValidWithUnicodeFlag, + REGEXPP_LATEST_ECMA_VERSION +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/index.js b/node_modules/eslint/lib/rules/utils/unicode/index.js new file mode 100644 index 0000000..02eea50 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/index.js @@ -0,0 +1,11 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +module.exports = { + isCombiningCharacter: require("./is-combining-character"), + isEmojiModifier: require("./is-emoji-modifier"), + isRegionalIndicatorSymbol: require("./is-regional-indicator-symbol"), + isSurrogatePair: require("./is-surrogate-pair") +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js b/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js new file mode 100644 index 0000000..0498b99 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is a combining mark or not. + * @param {number} codePoint The character code to check. + * @returns {boolean} `true` if the character belongs to the category, any of `Mc`, `Me`, and `Mn`. + */ +module.exports = function isCombiningCharacter(codePoint) { + return /^[\p{Mc}\p{Me}\p{Mn}]$/u.test(String.fromCodePoint(codePoint)); +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js b/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js new file mode 100644 index 0000000..1bd5f55 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is an emoji modifier. + * @param {number} code The character code to check. + * @returns {boolean} `true` if the character is an emoji modifier. + */ +module.exports = function isEmojiModifier(code) { + return code >= 0x1F3FB && code <= 0x1F3FF; +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js b/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js new file mode 100644 index 0000000..c48ed46 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is a regional indicator symbol. + * @param {number} code The character code to check. + * @returns {boolean} `true` if the character is a regional indicator symbol. + */ +module.exports = function isRegionalIndicatorSymbol(code) { + return code >= 0x1F1E6 && code <= 0x1F1FF; +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js b/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js new file mode 100644 index 0000000..b8e5c1c --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js @@ -0,0 +1,14 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether given two characters are a surrogate pair. + * @param {number} lead The code of the lead character. + * @param {number} tail The code of the tail character. + * @returns {boolean} `true` if the character pair is a surrogate pair. + */ +module.exports = function isSurrogatePair(lead, tail) { + return lead >= 0xD800 && lead < 0xDC00 && tail >= 0xDC00 && tail < 0xE000; +}; diff --git a/node_modules/eslint/lib/rules/valid-jsdoc.js b/node_modules/eslint/lib/rules/valid-jsdoc.js new file mode 100644 index 0000000..919975f --- /dev/null +++ b/node_modules/eslint/lib/rules/valid-jsdoc.js @@ -0,0 +1,516 @@ +/** + * @fileoverview Validates JSDoc comments are syntactically correct + * @author Nicholas C. Zakas + * @deprecated in ESLint v5.10.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const doctrine = require("doctrine"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce valid JSDoc comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/valid-jsdoc" + }, + + schema: [ + { + type: "object", + properties: { + prefer: { + type: "object", + additionalProperties: { + type: "string" + } + }, + preferType: { + type: "object", + additionalProperties: { + type: "string" + } + }, + requireReturn: { + type: "boolean", + default: true + }, + requireParamDescription: { + type: "boolean", + default: true + }, + requireReturnDescription: { + type: "boolean", + default: true + }, + matchDescription: { + type: "string" + }, + requireReturnType: { + type: "boolean", + default: true + }, + requireParamType: { + type: "boolean", + default: true + } + }, + additionalProperties: false + } + ], + + fixable: "code", + messages: { + unexpectedTag: "Unexpected @{{title}} tag; function has no return statement.", + expected: "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", + use: "Use @{{name}} instead.", + useType: "Use '{{expectedTypeName}}' instead of '{{currentTypeName}}'.", + syntaxError: "JSDoc syntax error.", + missingBrace: "JSDoc type missing brace.", + missingParamDesc: "Missing JSDoc parameter description for '{{name}}'.", + missingParamType: "Missing JSDoc parameter type for '{{name}}'.", + missingReturnType: "Missing JSDoc return type.", + missingReturnDesc: "Missing JSDoc return description.", + missingReturn: "Missing JSDoc @{{returns}} for function.", + missingParam: "Missing JSDoc for parameter '{{name}}'.", + duplicateParam: "Duplicate JSDoc parameter '{{name}}'.", + unsatisfiedDesc: "JSDoc description does not satisfy the regex pattern." + }, + + deprecated: true, + replacedBy: [] + }, + + create(context) { + + const options = context.options[0] || {}, + prefer = options.prefer || {}, + sourceCode = context.sourceCode, + + // these both default to true, so you have to explicitly make them false + requireReturn = options.requireReturn !== false, + requireParamDescription = options.requireParamDescription !== false, + requireReturnDescription = options.requireReturnDescription !== false, + requireReturnType = options.requireReturnType !== false, + requireParamType = options.requireParamType !== false, + preferType = options.preferType || {}, + checkPreferType = Object.keys(preferType).length !== 0; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // Using a stack to store if a function returns or not (handling nested functions) + const fns = []; + + /** + * Check if node type is a Class + * @param {ASTNode} node node to check. + * @returns {boolean} True is its a class + * @private + */ + function isTypeClass(node) { + return node.type === "ClassExpression" || node.type === "ClassDeclaration"; + } + + /** + * When parsing a new function, store it in our function stack. + * @param {ASTNode} node A function node to check. + * @returns {void} + * @private + */ + function startFunction(node) { + fns.push({ + returnPresent: (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") || + isTypeClass(node) || node.async + }); + } + + /** + * Indicate that return has been found in the current function. + * @param {ASTNode} node The return node. + * @returns {void} + * @private + */ + function addReturn(node) { + const functionState = fns[fns.length - 1]; + + if (functionState && node.argument !== null) { + functionState.returnPresent = true; + } + } + + /** + * Check if return tag type is void or undefined + * @param {Object} tag JSDoc tag + * @returns {boolean} True if its of type void or undefined + * @private + */ + function isValidReturnType(tag) { + return tag.type === null || tag.type.name === "void" || tag.type.type === "UndefinedLiteral"; + } + + /** + * Check if type should be validated based on some exceptions + * @param {Object} type JSDoc tag + * @returns {boolean} True if it can be validated + * @private + */ + function canTypeBeValidated(type) { + return type !== "UndefinedLiteral" && // {undefined} as there is no name property available. + type !== "NullLiteral" && // {null} + type !== "NullableLiteral" && // {?} + type !== "FunctionType" && // {function(a)} + type !== "AllLiteral"; // {*} + } + + /** + * Extract the current and expected type based on the input type object + * @param {Object} type JSDoc tag + * @returns {{currentType: Doctrine.Type, expectedTypeName: string}} The current type annotation and + * the expected name of the annotation + * @private + */ + function getCurrentExpectedTypes(type) { + let currentType; + + if (type.name) { + currentType = type; + } else if (type.expression) { + currentType = type.expression; + } + + return { + currentType, + expectedTypeName: currentType && preferType[currentType.name] + }; + } + + /** + * Gets the location of a JSDoc node in a file + * @param {Token} jsdocComment The comment that this node is parsed from + * @param {{range: number[]}} parsedJsdocNode A tag or other node which was parsed from this comment + * @returns {{start: SourceLocation, end: SourceLocation}} The 0-based source location for the tag + */ + function getAbsoluteRange(jsdocComment, parsedJsdocNode) { + return { + start: sourceCode.getLocFromIndex(jsdocComment.range[0] + 2 + parsedJsdocNode.range[0]), + end: sourceCode.getLocFromIndex(jsdocComment.range[0] + 2 + parsedJsdocNode.range[1]) + }; + } + + /** + * Validate type for a given JSDoc node + * @param {Object} jsdocNode JSDoc node + * @param {Object} type JSDoc tag + * @returns {void} + * @private + */ + function validateType(jsdocNode, type) { + if (!type || !canTypeBeValidated(type.type)) { + return; + } + + const typesToCheck = []; + let elements = []; + + switch (type.type) { + case "TypeApplication": // {Array.} + elements = type.applications[0].type === "UnionType" ? type.applications[0].elements : type.applications; + typesToCheck.push(getCurrentExpectedTypes(type)); + break; + case "RecordType": // {{20:String}} + elements = type.fields; + break; + case "UnionType": // {String|number|Test} + case "ArrayType": // {[String, number, Test]} + elements = type.elements; + break; + case "FieldType": // Array.<{count: number, votes: number}> + if (type.value) { + typesToCheck.push(getCurrentExpectedTypes(type.value)); + } + break; + default: + typesToCheck.push(getCurrentExpectedTypes(type)); + } + + elements.forEach(validateType.bind(null, jsdocNode)); + + typesToCheck.forEach(typeToCheck => { + if (typeToCheck.expectedTypeName && + typeToCheck.expectedTypeName !== typeToCheck.currentType.name) { + context.report({ + node: jsdocNode, + messageId: "useType", + loc: getAbsoluteRange(jsdocNode, typeToCheck.currentType), + data: { + currentTypeName: typeToCheck.currentType.name, + expectedTypeName: typeToCheck.expectedTypeName + }, + fix(fixer) { + return fixer.replaceTextRange( + typeToCheck.currentType.range.map(indexInComment => jsdocNode.range[0] + 2 + indexInComment), + typeToCheck.expectedTypeName + ); + } + }); + } + }); + } + + /** + * Validate the JSDoc node and output warnings if anything is wrong. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkJSDoc(node) { + const jsdocNode = sourceCode.getJSDocComment(node), + functionData = fns.pop(), + paramTagsByName = Object.create(null), + paramTags = []; + let hasReturns = false, + returnsTag, + hasConstructor = false, + isInterface = false, + isOverride = false, + isAbstract = false; + + // make sure only to validate JSDoc comments + if (jsdocNode) { + let jsdoc; + + try { + jsdoc = doctrine.parse(jsdocNode.value, { + strict: true, + unwrap: true, + sloppy: true, + range: true + }); + } catch (ex) { + + if (/braces/iu.test(ex.message)) { + context.report({ node: jsdocNode, messageId: "missingBrace" }); + } else { + context.report({ node: jsdocNode, messageId: "syntaxError" }); + } + + return; + } + + jsdoc.tags.forEach(tag => { + + switch (tag.title.toLowerCase()) { + + case "param": + case "arg": + case "argument": + paramTags.push(tag); + break; + + case "return": + case "returns": + hasReturns = true; + returnsTag = tag; + break; + + case "constructor": + case "class": + hasConstructor = true; + break; + + case "override": + case "inheritdoc": + isOverride = true; + break; + + case "abstract": + case "virtual": + isAbstract = true; + break; + + case "interface": + isInterface = true; + break; + + // no default + } + + // check tag preferences + if (Object.prototype.hasOwnProperty.call(prefer, tag.title) && tag.title !== prefer[tag.title]) { + const entireTagRange = getAbsoluteRange(jsdocNode, tag); + + context.report({ + node: jsdocNode, + messageId: "use", + loc: { + start: entireTagRange.start, + end: { + line: entireTagRange.start.line, + column: entireTagRange.start.column + `@${tag.title}`.length + } + }, + data: { name: prefer[tag.title] }, + fix(fixer) { + return fixer.replaceTextRange( + [ + jsdocNode.range[0] + tag.range[0] + 3, + jsdocNode.range[0] + tag.range[0] + tag.title.length + 3 + ], + prefer[tag.title] + ); + } + }); + } + + // validate the types + if (checkPreferType && tag.type) { + validateType(jsdocNode, tag.type); + } + }); + + paramTags.forEach(param => { + if (requireParamType && !param.type) { + context.report({ + node: jsdocNode, + messageId: "missingParamType", + loc: getAbsoluteRange(jsdocNode, param), + data: { name: param.name } + }); + } + if (!param.description && requireParamDescription) { + context.report({ + node: jsdocNode, + messageId: "missingParamDesc", + loc: getAbsoluteRange(jsdocNode, param), + data: { name: param.name } + }); + } + if (paramTagsByName[param.name]) { + context.report({ + node: jsdocNode, + messageId: "duplicateParam", + loc: getAbsoluteRange(jsdocNode, param), + data: { name: param.name } + }); + } else if (!param.name.includes(".")) { + paramTagsByName[param.name] = param; + } + }); + + if (hasReturns) { + if (!requireReturn && !functionData.returnPresent && (returnsTag.type === null || !isValidReturnType(returnsTag)) && !isAbstract) { + context.report({ + node: jsdocNode, + messageId: "unexpectedTag", + loc: getAbsoluteRange(jsdocNode, returnsTag), + data: { + title: returnsTag.title + } + }); + } else { + if (requireReturnType && !returnsTag.type) { + context.report({ node: jsdocNode, messageId: "missingReturnType" }); + } + + if (!isValidReturnType(returnsTag) && !returnsTag.description && requireReturnDescription) { + context.report({ node: jsdocNode, messageId: "missingReturnDesc" }); + } + } + } + + // check for functions missing @returns + if (!isOverride && !hasReturns && !hasConstructor && !isInterface && + node.parent.kind !== "get" && node.parent.kind !== "constructor" && + node.parent.kind !== "set" && !isTypeClass(node)) { + if (requireReturn || (functionData.returnPresent && !node.async)) { + context.report({ + node: jsdocNode, + messageId: "missingReturn", + data: { + returns: prefer.returns || "returns" + } + }); + } + } + + // check the parameters + const jsdocParamNames = Object.keys(paramTagsByName); + + if (node.params) { + node.params.forEach((param, paramsIndex) => { + const bindingParam = param.type === "AssignmentPattern" + ? param.left + : param; + + // TODO(nzakas): Figure out logical things to do with destructured, default, rest params + if (bindingParam.type === "Identifier") { + const name = bindingParam.name; + + if (jsdocParamNames[paramsIndex] && (name !== jsdocParamNames[paramsIndex])) { + context.report({ + node: jsdocNode, + messageId: "expected", + loc: getAbsoluteRange(jsdocNode, paramTagsByName[jsdocParamNames[paramsIndex]]), + data: { + name, + jsdocName: jsdocParamNames[paramsIndex] + } + }); + } else if (!paramTagsByName[name] && !isOverride) { + context.report({ + node: jsdocNode, + messageId: "missingParam", + data: { + name + } + }); + } + } + }); + } + + if (options.matchDescription) { + const regex = new RegExp(options.matchDescription, "u"); + + if (!regex.test(jsdoc.description)) { + context.report({ node: jsdocNode, messageId: "unsatisfiedDesc" }); + } + } + + } + + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ArrowFunctionExpression: startFunction, + FunctionExpression: startFunction, + FunctionDeclaration: startFunction, + ClassExpression: startFunction, + ClassDeclaration: startFunction, + "ArrowFunctionExpression:exit": checkJSDoc, + "FunctionExpression:exit": checkJSDoc, + "FunctionDeclaration:exit": checkJSDoc, + "ClassExpression:exit": checkJSDoc, + "ClassDeclaration:exit": checkJSDoc, + ReturnStatement: addReturn + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/valid-typeof.js b/node_modules/eslint/lib/rules/valid-typeof.js new file mode 100644 index 0000000..3818daf --- /dev/null +++ b/node_modules/eslint/lib/rules/valid-typeof.js @@ -0,0 +1,127 @@ +/** + * @fileoverview Ensures that the results of typeof are compared against a valid string + * @author Ian Christian Myers + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Enforce comparing `typeof` expressions against valid strings", + recommended: true, + url: "https://eslint.org/docs/latest/rules/valid-typeof" + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + requireStringLiterals: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + messages: { + invalidValue: "Invalid typeof comparison value.", + notString: "Typeof comparisons should be to string literals.", + suggestString: 'Use `"{{type}}"` instead of `{{type}}`.' + } + }, + + create(context) { + + const VALID_TYPES = new Set(["symbol", "undefined", "object", "boolean", "number", "string", "function", "bigint"]), + OPERATORS = new Set(["==", "===", "!=", "!=="]); + const sourceCode = context.sourceCode; + const requireStringLiterals = context.options[0] && context.options[0].requireStringLiterals; + + let globalScope; + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return variable && variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node); + } + + /** + * Determines whether a node is a typeof expression. + * @param {ASTNode} node The node + * @returns {boolean} `true` if the node is a typeof expression + */ + function isTypeofExpression(node) { + return node.type === "UnaryExpression" && node.operator === "typeof"; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + UnaryExpression(node) { + if (isTypeofExpression(node)) { + const { parent } = node; + + if (parent.type === "BinaryExpression" && OPERATORS.has(parent.operator)) { + const sibling = parent.left === node ? parent.right : parent.left; + + if (sibling.type === "Literal" || astUtils.isStaticTemplateLiteral(sibling)) { + const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked; + + if (!VALID_TYPES.has(value)) { + context.report({ node: sibling, messageId: "invalidValue" }); + } + } else if (sibling.type === "Identifier" && sibling.name === "undefined" && isReferenceToGlobalVariable(sibling)) { + context.report({ + node: sibling, + messageId: requireStringLiterals ? "notString" : "invalidValue", + suggest: [ + { + messageId: "suggestString", + data: { type: "undefined" }, + fix(fixer) { + return fixer.replaceText(sibling, '"undefined"'); + } + } + ] + }); + } else if (requireStringLiterals && !isTypeofExpression(sibling)) { + context.report({ node: sibling, messageId: "notString" }); + } + } + } + } + + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/vars-on-top.js b/node_modules/eslint/lib/rules/vars-on-top.js new file mode 100644 index 0000000..81f5d62 --- /dev/null +++ b/node_modules/eslint/lib/rules/vars-on-top.js @@ -0,0 +1,157 @@ +/** + * @fileoverview Rule to enforce var declarations are only at the top of a function. + * @author Danny Fritz + * @author Gyandeep Singh + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `var` declarations be placed at the top of their containing scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/vars-on-top" + }, + + schema: [], + messages: { + top: "All 'var' declarations must be at the top of the function scope." + } + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Has AST suggesting a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return node.type === "ExpressionStatement" && + node.expression.type === "Literal" && typeof node.expression.value === "string"; + } + + /** + * Check to see if its a ES6 import declaration + * @param {ASTNode} node any node + * @returns {boolean} whether the given node represents a import declaration + */ + function looksLikeImport(node) { + return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" || + node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier"; + } + + /** + * Checks whether a given node is a variable declaration or not. + * @param {ASTNode} node any node + * @returns {boolean} `true` if the node is a variable declaration. + */ + function isVariableDeclaration(node) { + return ( + node.type === "VariableDeclaration" || + ( + node.type === "ExportNamedDeclaration" && + node.declaration && + node.declaration.type === "VariableDeclaration" + ) + ); + } + + /** + * Checks whether this variable is on top of the block body + * @param {ASTNode} node The node to check + * @param {ASTNode[]} statements collection of ASTNodes for the parent node block + * @returns {boolean} True if var is on top otherwise false + */ + function isVarOnTop(node, statements) { + const l = statements.length; + let i = 0; + + // Skip over directives and imports. Static blocks don't have either. + if (node.parent.type !== "StaticBlock") { + for (; i < l; ++i) { + if (!looksLikeDirective(statements[i]) && !looksLikeImport(statements[i])) { + break; + } + } + } + + for (; i < l; ++i) { + if (!isVariableDeclaration(statements[i])) { + return false; + } + if (statements[i] === node) { + return true; + } + } + + return false; + } + + /** + * Checks whether variable is on top at the global level + * @param {ASTNode} node The node to check + * @param {ASTNode} parent Parent of the node + * @returns {void} + */ + function globalVarCheck(node, parent) { + if (!isVarOnTop(node, parent.body)) { + context.report({ node, messageId: "top" }); + } + } + + /** + * Checks whether variable is on top at functional block scope level + * @param {ASTNode} node The node to check + * @returns {void} + */ + function blockScopeVarCheck(node) { + const { parent } = node; + + if ( + parent.type === "BlockStatement" && + /Function/u.test(parent.parent.type) && + isVarOnTop(node, parent.body) + ) { + return; + } + + if ( + parent.type === "StaticBlock" && + isVarOnTop(node, parent.body) + ) { + return; + } + + context.report({ node, messageId: "top" }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration[kind='var']"(node) { + if (node.parent.type === "ExportNamedDeclaration") { + globalVarCheck(node.parent, node.parent.parent); + } else if (node.parent.type === "Program") { + globalVarCheck(node, node.parent); + } else { + blockScopeVarCheck(node); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/wrap-iife.js b/node_modules/eslint/lib/rules/wrap-iife.js new file mode 100644 index 0000000..4c448fa --- /dev/null +++ b/node_modules/eslint/lib/rules/wrap-iife.js @@ -0,0 +1,204 @@ +/** + * @fileoverview Rule to flag when IIFE is not wrapped in parens + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const eslintUtils = require("@eslint-community/eslint-utils"); + +//---------------------------------------------------------------------- +// Helpers +//---------------------------------------------------------------------- + +/** + * Check if the given node is callee of a `NewExpression` node + * @param {ASTNode} node node to check + * @returns {boolean} True if the node is callee of a `NewExpression` node + * @private + */ +function isCalleeOfNewExpression(node) { + const maybeCallee = node.parent.type === "ChainExpression" + ? node.parent + : node; + + return ( + maybeCallee.parent.type === "NewExpression" && + maybeCallee.parent.callee === maybeCallee + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require parentheses around immediate `function` invocations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/wrap-iife" + }, + + schema: [ + { + enum: ["outside", "inside", "any"] + }, + { + type: "object", + properties: { + functionPrototypeMethods: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + fixable: "code", + messages: { + wrapInvocation: "Wrap an immediate function invocation in parentheses.", + wrapExpression: "Wrap only the function expression in parens.", + moveInvocation: "Move the invocation into the parens that contain the function." + } + }, + + create(context) { + + const style = context.options[0] || "outside"; + const includeFunctionPrototypeMethods = context.options[1] && context.options[1].functionPrototypeMethods; + + const sourceCode = context.sourceCode; + + /** + * Check if the node is wrapped in any (). All parens count: grouping parens and parens for constructs such as if() + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if it is wrapped in any parens + * @private + */ + function isWrappedInAnyParens(node) { + return astUtils.isParenthesised(sourceCode, node); + } + + /** + * Check if the node is wrapped in grouping (). Parens for constructs such as if() don't count + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if it is wrapped in grouping parens + * @private + */ + function isWrappedInGroupingParens(node) { + return eslintUtils.isParenthesized(1, node, sourceCode); + } + + /** + * Get the function node from an IIFE + * @param {ASTNode} node node to evaluate + * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist + */ + function getFunctionNodeFromIIFE(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "FunctionExpression") { + return callee; + } + + if (includeFunctionPrototypeMethods && + callee.type === "MemberExpression" && + callee.object.type === "FunctionExpression" && + (astUtils.getStaticPropertyName(callee) === "call" || astUtils.getStaticPropertyName(callee) === "apply") + ) { + return callee.object; + } + + return null; + } + + + return { + CallExpression(node) { + const innerNode = getFunctionNodeFromIIFE(node); + + if (!innerNode) { + return; + } + + const isCallExpressionWrapped = isWrappedInAnyParens(node), + isFunctionExpressionWrapped = isWrappedInAnyParens(innerNode); + + if (!isCallExpressionWrapped && !isFunctionExpressionWrapped) { + context.report({ + node, + messageId: "wrapInvocation", + fix(fixer) { + const nodeToSurround = style === "inside" ? innerNode : node; + + return fixer.replaceText(nodeToSurround, `(${sourceCode.getText(nodeToSurround)})`); + } + }); + } else if (style === "inside" && !isFunctionExpressionWrapped) { + context.report({ + node, + messageId: "wrapExpression", + fix(fixer) { + + // The outer call expression will always be wrapped at this point. + + if (isWrappedInGroupingParens(node) && !isCalleeOfNewExpression(node)) { + + /* + * Parenthesize the function expression and remove unnecessary grouping parens around the call expression. + * Replace the range between the end of the function expression and the end of the call expression. + * for example, in `(function(foo) {}(bar))`, the range `(bar))` should get replaced with `)(bar)`. + */ + + const parenAfter = sourceCode.getTokenAfter(node); + + return fixer.replaceTextRange( + [innerNode.range[1], parenAfter.range[1]], + `)${sourceCode.getText().slice(innerNode.range[1], parenAfter.range[0])}` + ); + } + + /* + * Call expression is wrapped in mandatory parens such as if(), or in necessary grouping parens. + * These parens cannot be removed, so just parenthesize the function expression. + */ + + return fixer.replaceText(innerNode, `(${sourceCode.getText(innerNode)})`); + } + }); + } else if (style === "outside" && !isCallExpressionWrapped) { + context.report({ + node, + messageId: "moveInvocation", + fix(fixer) { + + /* + * The inner function expression will always be wrapped at this point. + * It's only necessary to replace the range between the end of the function expression + * and the call expression. For example, in `(function(foo) {})(bar)`, the range `)(bar)` + * should get replaced with `(bar))`. + */ + const parenAfter = sourceCode.getTokenAfter(innerNode); + + return fixer.replaceTextRange( + [parenAfter.range[0], node.range[1]], + `${sourceCode.getText().slice(parenAfter.range[1], node.range[1])})` + ); + } + }); + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/wrap-regex.js b/node_modules/eslint/lib/rules/wrap-regex.js new file mode 100644 index 0000000..8166c25 --- /dev/null +++ b/node_modules/eslint/lib/rules/wrap-regex.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Rule to flag when regex literals are not wrapped in parens + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require parenthesis around regex literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/wrap-regex" + }, + + schema: [], + fixable: "code", + + messages: { + requireParens: "Wrap the regexp literal in parens to disambiguate the slash." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + + Literal(node) { + const token = sourceCode.getFirstToken(node), + nodeType = token.type; + + if (nodeType === "RegularExpression") { + const beforeToken = sourceCode.getTokenBefore(node); + const afterToken = sourceCode.getTokenAfter(node); + const { parent } = node; + + if (parent.type === "MemberExpression" && parent.object === node && + !(beforeToken && beforeToken.value === "(" && afterToken && afterToken.value === ")")) { + context.report({ + node, + messageId: "requireParens", + fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`) + }); + } + } + } + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/yield-star-spacing.js b/node_modules/eslint/lib/rules/yield-star-spacing.js new file mode 100644 index 0000000..9f9d918 --- /dev/null +++ b/node_modules/eslint/lib/rules/yield-star-spacing.js @@ -0,0 +1,127 @@ +/** + * @fileoverview Rule to check the spacing around the * in yield* expressions. + * @author Bryan Smith + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow spacing around the `*` in `yield*` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/yield-star-spacing" + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["before", "after", "both", "neither"] + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" } + }, + additionalProperties: false + } + ] + } + ], + messages: { + missingBefore: "Missing space before *.", + missingAfter: "Missing space after *.", + unexpectedBefore: "Unexpected space before *.", + unexpectedAfter: "Unexpected space after *." + } + }, + + create(context) { + const sourceCode = context.sourceCode; + + const mode = (function(option) { + if (!option || typeof option === "string") { + return { + before: { before: true, after: false }, + after: { before: false, after: true }, + both: { before: true, after: true }, + neither: { before: false, after: false } + }[option || "after"]; + } + return option; + }(context.options[0])); + + /** + * Checks the spacing between two tokens before or after the star token. + * @param {string} side Either "before" or "after". + * @param {Token} leftToken `function` keyword token if side is "before", or + * star token if side is "after". + * @param {Token} rightToken Star token if side is "before", or identifier + * token if side is "after". + * @returns {void} + */ + function checkSpacing(side, leftToken, rightToken) { + if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken) !== mode[side]) { + const after = leftToken.value === "*"; + const spaceRequired = mode[side]; + const node = after ? leftToken : rightToken; + let messageId = ""; + + if (spaceRequired) { + messageId = side === "before" ? "missingBefore" : "missingAfter"; + } else { + messageId = side === "before" ? "unexpectedBefore" : "unexpectedAfter"; + } + + context.report({ + node, + messageId, + fix(fixer) { + if (spaceRequired) { + if (after) { + return fixer.insertTextAfter(node, " "); + } + return fixer.insertTextBefore(node, " "); + } + return fixer.removeRange([leftToken.range[1], rightToken.range[0]]); + } + }); + } + } + + /** + * Enforces the spacing around the star if node is a yield* expression. + * @param {ASTNode} node A yield expression node. + * @returns {void} + */ + function checkExpression(node) { + if (!node.delegate) { + return; + } + + const tokens = sourceCode.getFirstTokens(node, 3); + const yieldToken = tokens[0]; + const starToken = tokens[1]; + const nextToken = tokens[2]; + + checkSpacing("before", yieldToken, starToken); + checkSpacing("after", starToken, nextToken); + } + + return { + YieldExpression: checkExpression + }; + + } +}; diff --git a/node_modules/eslint/lib/rules/yoda.js b/node_modules/eslint/lib/rules/yoda.js new file mode 100644 index 0000000..af8f525 --- /dev/null +++ b/node_modules/eslint/lib/rules/yoda.js @@ -0,0 +1,353 @@ +/** + * @fileoverview Rule to require or disallow yoda comparisons + * @author Nicholas C. Zakas + */ +"use strict"; + +//-------------------------------------------------------------------------- +// Requirements +//-------------------------------------------------------------------------- + +const astUtils = require("./utils/ast-utils"); + +//-------------------------------------------------------------------------- +// Helpers +//-------------------------------------------------------------------------- + +/** + * Determines whether an operator is a comparison operator. + * @param {string} operator The operator to check. + * @returns {boolean} Whether or not it is a comparison operator. + */ +function isComparisonOperator(operator) { + return /^(==|===|!=|!==|<|>|<=|>=)$/u.test(operator); +} + +/** + * Determines whether an operator is an equality operator. + * @param {string} operator The operator to check. + * @returns {boolean} Whether or not it is an equality operator. + */ +function isEqualityOperator(operator) { + return /^(==|===)$/u.test(operator); +} + +/** + * Determines whether an operator is one used in a range test. + * Allowed operators are `<` and `<=`. + * @param {string} operator The operator to check. + * @returns {boolean} Whether the operator is used in range tests. + */ +function isRangeTestOperator(operator) { + return ["<", "<="].includes(operator); +} + +/** + * Determines whether a non-Literal node is a negative number that should be + * treated as if it were a single Literal node. + * @param {ASTNode} node Node to test. + * @returns {boolean} True if the node is a negative number that looks like a + * real literal and should be treated as such. + */ +function isNegativeNumericLiteral(node) { + return ( + node.type === "UnaryExpression" && + node.operator === "-" && + node.prefix && + astUtils.isNumericLiteral(node.argument) + ); +} + +/** + * Determines whether a non-Literal node should be treated as a single Literal node. + * @param {ASTNode} node Node to test + * @returns {boolean} True if the node should be treated as a single Literal node. + */ +function looksLikeLiteral(node) { + return isNegativeNumericLiteral(node) || astUtils.isStaticTemplateLiteral(node); +} + +/** + * Attempts to derive a Literal node from nodes that are treated like literals. + * @param {ASTNode} node Node to normalize. + * @returns {ASTNode} One of the following options. + * 1. The original node if the node is already a Literal + * 2. A normalized Literal node with the negative number as the value if the + * node represents a negative number literal. + * 3. A normalized Literal node with the string as the value if the node is + * a Template Literal without expression. + * 4. Otherwise `null`. + */ +function getNormalizedLiteral(node) { + if (node.type === "Literal") { + return node; + } + + if (isNegativeNumericLiteral(node)) { + return { + type: "Literal", + value: -node.argument.value, + raw: `-${node.argument.value}` + }; + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return { + type: "Literal", + value: node.quasis[0].value.cooked, + raw: node.quasis[0].value.raw + }; + } + + return null; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: 'Require or disallow "Yoda" conditions', + recommended: false, + url: "https://eslint.org/docs/latest/rules/yoda" + }, + + schema: [ + { + enum: ["always", "never"] + }, + { + type: "object", + properties: { + exceptRange: { + type: "boolean", + default: false + }, + onlyEquality: { + type: "boolean", + default: false + } + }, + additionalProperties: false + } + ], + + fixable: "code", + messages: { + expected: + "Expected literal to be on the {{expectedSide}} side of {{operator}}." + } + }, + + create(context) { + + // Default to "never" (!always) if no option + const always = context.options[0] === "always"; + const exceptRange = + context.options[1] && context.options[1].exceptRange; + const onlyEquality = + context.options[1] && context.options[1].onlyEquality; + + const sourceCode = context.sourceCode; + + /** + * Determines whether node represents a range test. + * A range test is a "between" test like `(0 <= x && x < 1)` or an "outside" + * test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and + * both operators must be `<` or `<=`. Finally, the literal on the left side + * must be less than or equal to the literal on the right side so that the + * test makes any sense. + * @param {ASTNode} node LogicalExpression node to test. + * @returns {boolean} Whether node is a range test. + */ + function isRangeTest(node) { + const left = node.left, + right = node.right; + + /** + * Determines whether node is of the form `0 <= x && x < 1`. + * @returns {boolean} Whether node is a "between" range test. + */ + function isBetweenTest() { + if (node.operator === "&&" && astUtils.isSameReference(left.right, right.left)) { + const leftLiteral = getNormalizedLiteral(left.left); + const rightLiteral = getNormalizedLiteral(right.right); + + if (leftLiteral === null && rightLiteral === null) { + return false; + } + + if (rightLiteral === null || leftLiteral === null) { + return true; + } + + if (leftLiteral.value <= rightLiteral.value) { + return true; + } + } + return false; + } + + /** + * Determines whether node is of the form `x < 0 || 1 <= x`. + * @returns {boolean} Whether node is an "outside" range test. + */ + function isOutsideTest() { + if (node.operator === "||" && astUtils.isSameReference(left.left, right.right)) { + const leftLiteral = getNormalizedLiteral(left.right); + const rightLiteral = getNormalizedLiteral(right.left); + + if (leftLiteral === null && rightLiteral === null) { + return false; + } + + if (rightLiteral === null || leftLiteral === null) { + return true; + } + + if (leftLiteral.value <= rightLiteral.value) { + return true; + } + } + + return false; + } + + /** + * Determines whether node is wrapped in parentheses. + * @returns {boolean} Whether node is preceded immediately by an open + * paren token and followed immediately by a close + * paren token. + */ + function isParenWrapped() { + return astUtils.isParenthesised(sourceCode, node); + } + + return ( + node.type === "LogicalExpression" && + left.type === "BinaryExpression" && + right.type === "BinaryExpression" && + isRangeTestOperator(left.operator) && + isRangeTestOperator(right.operator) && + (isBetweenTest() || isOutsideTest()) && + isParenWrapped() + ); + } + + const OPERATOR_FLIP_MAP = { + "===": "===", + "!==": "!==", + "==": "==", + "!=": "!=", + "<": ">", + ">": "<", + "<=": ">=", + ">=": "<=" + }; + + /** + * Returns a string representation of a BinaryExpression node with its sides/operator flipped around. + * @param {ASTNode} node The BinaryExpression node + * @returns {string} A string representation of the node with the sides and operator flipped + */ + function getFlippedString(node) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator + ); + const lastLeftToken = sourceCode.getTokenBefore(operatorToken); + const firstRightToken = sourceCode.getTokenAfter(operatorToken); + + const source = sourceCode.getText(); + + const leftText = source.slice( + node.range[0], + lastLeftToken.range[1] + ); + const textBeforeOperator = source.slice( + lastLeftToken.range[1], + operatorToken.range[0] + ); + const textAfterOperator = source.slice( + operatorToken.range[1], + firstRightToken.range[0] + ); + const rightText = source.slice( + firstRightToken.range[0], + node.range[1] + ); + + const tokenBefore = sourceCode.getTokenBefore(node); + const tokenAfter = sourceCode.getTokenAfter(node); + let prefix = ""; + let suffix = ""; + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, firstRightToken) + ) { + prefix = " "; + } + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent(lastLeftToken, tokenAfter) + ) { + suffix = " "; + } + + return ( + prefix + + rightText + + textBeforeOperator + + OPERATOR_FLIP_MAP[operatorToken.value] + + textAfterOperator + + leftText + + suffix + ); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + BinaryExpression(node) { + const expectedLiteral = always ? node.left : node.right; + const expectedNonLiteral = always ? node.right : node.left; + + // If `expectedLiteral` is not a literal, and `expectedNonLiteral` is a literal, raise an error. + if ( + (expectedNonLiteral.type === "Literal" || + looksLikeLiteral(expectedNonLiteral)) && + !( + expectedLiteral.type === "Literal" || + looksLikeLiteral(expectedLiteral) + ) && + !(!isEqualityOperator(node.operator) && onlyEquality) && + isComparisonOperator(node.operator) && + !(exceptRange && isRangeTest(node.parent)) + ) { + context.report({ + node, + messageId: "expected", + data: { + operator: node.operator, + expectedSide: always ? "left" : "right" + }, + fix: fixer => + fixer.replaceText(node, getFlippedString(node)) + }); + } + } + }; + } +}; diff --git a/node_modules/eslint/lib/shared/ajv.js b/node_modules/eslint/lib/shared/ajv.js new file mode 100644 index 0000000..f4f6a62 --- /dev/null +++ b/node_modules/eslint/lib/shared/ajv.js @@ -0,0 +1,34 @@ +/** + * @fileoverview The instance of Ajv validator. + * @author Evgeny Poberezkin + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Ajv = require("ajv"), + metaSchema = require("ajv/lib/refs/json-schema-draft-04.json"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = (additionalOptions = {}) => { + const ajv = new Ajv({ + meta: false, + useDefaults: true, + validateSchema: false, + missingRefs: "ignore", + verbose: true, + schemaId: "auto", + ...additionalOptions + }); + + ajv.addMetaSchema(metaSchema); + // eslint-disable-next-line no-underscore-dangle -- Ajv's API + ajv._opts.defaultMeta = metaSchema.id; + + return ajv; +}; diff --git a/node_modules/eslint/lib/shared/ast-utils.js b/node_modules/eslint/lib/shared/ast-utils.js new file mode 100644 index 0000000..4ebd49c --- /dev/null +++ b/node_modules/eslint/lib/shared/ast-utils.js @@ -0,0 +1,29 @@ +/** + * @fileoverview Common utils for AST. + * + * This file contains only shared items for core and rules. + * If you make a utility for rules, please see `../rules/utils/ast-utils.js`. + * + * @author Toru Nagashima + */ +"use strict"; + +const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u; +const lineBreakPattern = /\r\n|[\r\n\u2028\u2029]/u; +const shebangPattern = /^#!([^\r\n]+)/u; + +/** + * Creates a version of the `lineBreakPattern` regex with the global flag. + * Global regexes are mutable, so this needs to be a function instead of a constant. + * @returns {RegExp} A global regular expression that matches line terminators + */ +function createGlobalLinebreakMatcher() { + return new RegExp(lineBreakPattern.source, "gu"); +} + +module.exports = { + breakableTypePattern, + lineBreakPattern, + createGlobalLinebreakMatcher, + shebangPattern +}; diff --git a/node_modules/eslint/lib/shared/config-validator.js b/node_modules/eslint/lib/shared/config-validator.js new file mode 100644 index 0000000..47353ac --- /dev/null +++ b/node_modules/eslint/lib/shared/config-validator.js @@ -0,0 +1,347 @@ +/* + * STOP!!! DO NOT MODIFY. + * + * This file is part of the ongoing work to move the eslintrc-style config + * system into the @eslint/eslintrc package. This file needs to remain + * unchanged in order for this work to proceed. + * + * If you think you need to change this file, please contact @nzakas first. + * + * Thanks in advance for your cooperation. + */ + +/** + * @fileoverview Validates configs. + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const + util = require("util"), + configSchema = require("../../conf/config-schema"), + BuiltInRules = require("../rules"), + { + Legacy: { + ConfigOps, + environments: BuiltInEnvironments + } + } = require("@eslint/eslintrc"), + { emitDeprecationWarning } = require("./deprecation-warnings"); + +const ajv = require("./ajv")(); +const ruleValidators = new WeakMap(); +const noop = Function.prototype; + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ +let validateSchema; +const severityMap = { + error: 2, + warn: 1, + off: 0 +}; + +/** + * Gets a complete options schema for a rule. + * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object + * @returns {Object} JSON Schema for the rule's options. + */ +function getRuleOptionsSchema(rule) { + if (!rule) { + return null; + } + + const schema = rule.schema || rule.meta && rule.meta.schema; + + // Given a tuple of schemas, insert warning level at the beginning + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length + }; + } + return { + type: "array", + minItems: 0, + maxItems: 0 + }; + + } + + // Given a full schema, leave it alone + return schema || null; +} + +/** + * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. + * @param {options} options The given options for the rule. + * @throws {Error} Wrong severity value. + * @returns {number|string} The rule's severity value + */ +function validateRuleSeverity(options) { + const severity = Array.isArray(options) ? options[0] : options; + const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity; + + if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) { + return normSeverity; + } + + throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`); + +} + +/** + * Validates the non-severity options passed to a rule, based on its schema. + * @param {{create: Function}} rule The rule to validate + * @param {Array} localOptions The options for the rule, excluding severity + * @throws {Error} Any rule validation errors. + * @returns {void} + */ +function validateRuleSchema(rule, localOptions) { + if (!ruleValidators.has(rule)) { + const schema = getRuleOptionsSchema(rule); + + if (schema) { + ruleValidators.set(rule, ajv.compile(schema)); + } + } + + const validateRule = ruleValidators.get(rule); + + if (validateRule) { + validateRule(localOptions); + if (validateRule.errors) { + throw new Error(validateRule.errors.map( + error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` + ).join("")); + } + } +} + +/** + * Validates a rule's options against its schema. + * @param {{create: Function}|null} rule The rule that the config is being validated for + * @param {string} ruleId The rule's unique name. + * @param {Array|number} options The given options for the rule. + * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined, + * no source is prepended to the message. + * @throws {Error} Upon any bad rule configuration. + * @returns {void} + */ +function validateRuleOptions(rule, ruleId, options, source = null) { + try { + const severity = validateRuleSeverity(options); + + if (severity !== 0) { + validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []); + } + } catch (err) { + const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`; + + if (typeof source === "string") { + throw new Error(`${source}:\n\t${enhancedMessage}`); + } else { + throw new Error(enhancedMessage); + } + } +} + +/** + * Validates an environment object + * @param {Object} environment The environment config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded environments. + * @returns {void} + */ +function validateEnvironment( + environment, + source, + getAdditionalEnv = noop +) { + + // not having an environment is ok + if (!environment) { + return; + } + + Object.keys(environment).forEach(id => { + const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null; + + if (!env) { + const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`; + + throw new Error(message); + } + }); +} + +/** + * Validates a rules config object + * @param {Object} rulesConfig The rules config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(ruleId:string) => Object} getAdditionalRule A map from strings to loaded rules + * @returns {void} + */ +function validateRules( + rulesConfig, + source, + getAdditionalRule = noop +) { + if (!rulesConfig) { + return; + } + + Object.keys(rulesConfig).forEach(id => { + const rule = getAdditionalRule(id) || BuiltInRules.get(id) || null; + + validateRuleOptions(rule, id, rulesConfig[id], source); + }); +} + +/** + * Validates a `globals` section of a config file + * @param {Object} globalsConfig The `globals` section + * @param {string|null} source The name of the configuration source to report in the event of an error. + * @returns {void} + */ +function validateGlobals(globalsConfig, source = null) { + if (!globalsConfig) { + return; + } + + Object.entries(globalsConfig) + .forEach(([configuredGlobal, configuredValue]) => { + try { + ConfigOps.normalizeConfigGlobal(configuredValue); + } catch (err) { + throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`); + } + }); +} + +/** + * Validate `processor` configuration. + * @param {string|undefined} processorName The processor name. + * @param {string} source The name of config file. + * @param {(id:string) => Processor} getProcessor The getter of defined processors. + * @throws {Error} For invalid processor configuration. + * @returns {void} + */ +function validateProcessor(processorName, source, getProcessor) { + if (processorName && !getProcessor(processorName)) { + throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`); + } +} + +/** + * Formats an array of schema validation errors. + * @param {Array} errors An array of error messages to format. + * @returns {string} Formatted error message + */ +function formatErrors(errors) { + return errors.map(error => { + if (error.keyword === "additionalProperties") { + const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty; + + return `Unexpected top-level property "${formattedPropertyPath}"`; + } + if (error.keyword === "type") { + const formattedField = error.dataPath.slice(1); + const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema; + const formattedValue = JSON.stringify(error.data); + + return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`; + } + + const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; + + return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`; + }).map(message => `\t- ${message}.\n`).join(""); +} + +/** + * Validates the top level properties of the config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @throws {Error} For any config invalid per the schema. + * @returns {void} + */ +function validateConfigSchema(config, source = null) { + validateSchema = validateSchema || ajv.compile(configSchema); + + if (!validateSchema(config)) { + throw new Error(`ESLint configuration in ${source} is invalid:\n${formatErrors(validateSchema.errors)}`); + } + + if (Object.hasOwnProperty.call(config, "ecmaFeatures")) { + emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES"); + } +} + +/** + * Validates an entire config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(ruleId:string) => Object} [getAdditionalRule] A map from strings to loaded rules. + * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded envs. + * @returns {void} + */ +function validate(config, source, getAdditionalRule, getAdditionalEnv) { + validateConfigSchema(config, source); + validateRules(config.rules, source, getAdditionalRule); + validateEnvironment(config.env, source, getAdditionalEnv); + validateGlobals(config.globals, source); + + for (const override of config.overrides || []) { + validateRules(override.rules, source, getAdditionalRule); + validateEnvironment(override.env, source, getAdditionalEnv); + validateGlobals(config.globals, source); + } +} + +const validated = new WeakSet(); + +/** + * Validate config array object. + * @param {ConfigArray} configArray The config array to validate. + * @returns {void} + */ +function validateConfigArray(configArray) { + const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments); + const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors); + const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); + + // Validate. + for (const element of configArray) { + if (validated.has(element)) { + continue; + } + validated.add(element); + + validateEnvironment(element.env, element.name, getPluginEnv); + validateGlobals(element.globals, element.name); + validateProcessor(element.processor, element.name, getPluginProcessor); + validateRules(element.rules, element.name, getPluginRule); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + getRuleOptionsSchema, + validate, + validateConfigArray, + validateConfigSchema, + validateRuleOptions +}; diff --git a/node_modules/eslint/lib/shared/deprecation-warnings.js b/node_modules/eslint/lib/shared/deprecation-warnings.js new file mode 100644 index 0000000..d09cafb --- /dev/null +++ b/node_modules/eslint/lib/shared/deprecation-warnings.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Provide the function that emits deprecation warnings. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("path"); + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +// Definitions for deprecation warnings. +const deprecationWarningMessages = { + ESLINT_LEGACY_ECMAFEATURES: + "The 'ecmaFeatures' config file property is deprecated and has no effect." +}; + +const sourceFileErrorCache = new Set(); + +/** + * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted + * for each unique file path, but repeated invocations with the same file path have no effect. + * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active. + * @param {string} source The name of the configuration source to report the warning for. + * @param {string} errorCode The warning message to show. + * @returns {void} + */ +function emitDeprecationWarning(source, errorCode) { + const cacheKey = JSON.stringify({ source, errorCode }); + + if (sourceFileErrorCache.has(cacheKey)) { + return; + } + + sourceFileErrorCache.add(cacheKey); + + const rel = path.relative(process.cwd(), source); + const message = deprecationWarningMessages[errorCode]; + + process.emitWarning( + `${message} (found in "${rel}")`, + "DeprecationWarning", + errorCode + ); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + emitDeprecationWarning +}; diff --git a/node_modules/eslint/lib/shared/directives.js b/node_modules/eslint/lib/shared/directives.js new file mode 100644 index 0000000..ff67b00 --- /dev/null +++ b/node_modules/eslint/lib/shared/directives.js @@ -0,0 +1,15 @@ +/** + * @fileoverview Common utils for directives. + * + * This file contains only shared items for directives. + * If you make a utility for rules, please see `../rules/utils/ast-utils.js`. + * + * @author gfyoung + */ +"use strict"; + +const directivesPattern = /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u; + +module.exports = { + directivesPattern +}; diff --git a/node_modules/eslint/lib/shared/logging.js b/node_modules/eslint/lib/shared/logging.js new file mode 100644 index 0000000..fd5e8a6 --- /dev/null +++ b/node_modules/eslint/lib/shared/logging.js @@ -0,0 +1,30 @@ +/** + * @fileoverview Handle logging for ESLint + * @author Gyandeep Singh + */ + +"use strict"; + +/* eslint no-console: "off" -- Logging util */ + +/* c8 ignore next */ +module.exports = { + + /** + * Cover for console.log + * @param {...any} args The elements to log. + * @returns {void} + */ + info(...args) { + console.log(...args); + }, + + /** + * Cover for console.error + * @param {...any} args The elements to log. + * @returns {void} + */ + error(...args) { + console.error(...args); + } +}; diff --git a/node_modules/eslint/lib/shared/relative-module-resolver.js b/node_modules/eslint/lib/shared/relative-module-resolver.js new file mode 100644 index 0000000..18a6949 --- /dev/null +++ b/node_modules/eslint/lib/shared/relative-module-resolver.js @@ -0,0 +1,50 @@ +/* + * STOP!!! DO NOT MODIFY. + * + * This file is part of the ongoing work to move the eslintrc-style config + * system into the @eslint/eslintrc package. This file needs to remain + * unchanged in order for this work to proceed. + * + * If you think you need to change this file, please contact @nzakas first. + * + * Thanks in advance for your cooperation. + */ + +/** + * Utility for resolving a module relative to another module + * @author Teddy Katz + */ + +"use strict"; + +const { createRequire } = require("module"); + +module.exports = { + + /** + * Resolves a Node module relative to another module + * @param {string} moduleName The name of a Node module, or a path to a Node module. + * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be + * a file rather than a directory, but the file need not actually exist. + * @throws {Error} Any error from `module.createRequire` or its `resolve`. + * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath` + */ + resolve(moduleName, relativeToPath) { + try { + return createRequire(relativeToPath).resolve(moduleName); + } catch (error) { + + // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future. + if ( + typeof error === "object" && + error !== null && + error.code === "MODULE_NOT_FOUND" && + !error.requireStack && + error.message.includes(moduleName) + ) { + error.message += `\nRequire stack:\n- ${relativeToPath}`; + } + throw error; + } + } +}; diff --git a/node_modules/eslint/lib/shared/runtime-info.js b/node_modules/eslint/lib/shared/runtime-info.js new file mode 100644 index 0000000..b99ad10 --- /dev/null +++ b/node_modules/eslint/lib/shared/runtime-info.js @@ -0,0 +1,167 @@ +/** + * @fileoverview Utility to get information about the execution environment. + * @author Kai Cataldo + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("path"); +const spawn = require("cross-spawn"); +const os = require("os"); +const log = require("../shared/logging"); +const packageJson = require("../../package.json"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Generates and returns execution environment information. + * @returns {string} A string that contains execution environment information. + */ +function environment() { + const cache = new Map(); + + /** + * Checks if a path is a child of a directory. + * @param {string} parentPath The parent path to check. + * @param {string} childPath The path to check. + * @returns {boolean} Whether or not the given path is a child of a directory. + */ + function isChildOfDirectory(parentPath, childPath) { + return !path.relative(parentPath, childPath).startsWith(".."); + } + + /** + * Synchronously executes a shell command and formats the result. + * @param {string} cmd The command to execute. + * @param {Array} args The arguments to be executed with the command. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The version returned by the command. + */ + function execCommand(cmd, args) { + const key = [cmd, ...args].join(" "); + + if (cache.has(key)) { + return cache.get(key); + } + + const process = spawn.sync(cmd, args, { encoding: "utf8" }); + + if (process.error) { + throw process.error; + } + + const result = process.stdout.trim(); + + cache.set(key, result); + return result; + } + + /** + * Normalizes a version number. + * @param {string} versionStr The string to normalize. + * @returns {string} The normalized version number. + */ + function normalizeVersionStr(versionStr) { + return versionStr.startsWith("v") ? versionStr : `v${versionStr}`; + } + + /** + * Gets bin version. + * @param {string} bin The bin to check. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The normalized version returned by the command. + */ + function getBinVersion(bin) { + const binArgs = ["--version"]; + + try { + return normalizeVersionStr(execCommand(bin, binArgs)); + } catch (e) { + log.error(`Error finding ${bin} version running the command \`${bin} ${binArgs.join(" ")}\``); + throw e; + } + } + + /** + * Gets installed npm package version. + * @param {string} pkg The package to check. + * @param {boolean} global Whether to check globally or not. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The normalized version returned by the command. + */ + function getNpmPackageVersion(pkg, { global = false } = {}) { + const npmBinArgs = ["bin", "-g"]; + const npmLsArgs = ["ls", "--depth=0", "--json", pkg]; + + if (global) { + npmLsArgs.push("-g"); + } + + try { + const parsedStdout = JSON.parse(execCommand("npm", npmLsArgs)); + + /* + * Checking globally returns an empty JSON object, while local checks + * include the name and version of the local project. + */ + if (Object.keys(parsedStdout).length === 0 || !(parsedStdout.dependencies && parsedStdout.dependencies.eslint)) { + return "Not found"; + } + + const [, processBinPath] = process.argv; + let npmBinPath; + + try { + npmBinPath = execCommand("npm", npmBinArgs); + } catch (e) { + log.error(`Error finding npm binary path when running command \`npm ${npmBinArgs.join(" ")}\``); + throw e; + } + + const isGlobal = isChildOfDirectory(npmBinPath, processBinPath); + let pkgVersion = parsedStdout.dependencies.eslint.version; + + if ((global && isGlobal) || (!global && !isGlobal)) { + pkgVersion += " (Currently used)"; + } + + return normalizeVersionStr(pkgVersion); + } catch (e) { + log.error(`Error finding ${pkg} version running the command \`npm ${npmLsArgs.join(" ")}\``); + throw e; + } + } + + return [ + "Environment Info:", + "", + `Node version: ${getBinVersion("node")}`, + `npm version: ${getBinVersion("npm")}`, + `Local ESLint version: ${getNpmPackageVersion("eslint", { global: false })}`, + `Global ESLint version: ${getNpmPackageVersion("eslint", { global: true })}`, + `Operating System: ${os.platform()} ${os.release()}` + ].join("\n"); +} + +/** + * Returns version of currently executing ESLint. + * @returns {string} The version from the currently executing ESLint's package.json. + */ +function version() { + return `v${packageJson.version}`; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + environment, + version +}; diff --git a/node_modules/eslint/lib/shared/string-utils.js b/node_modules/eslint/lib/shared/string-utils.js new file mode 100644 index 0000000..ed0781e --- /dev/null +++ b/node_modules/eslint/lib/shared/string-utils.js @@ -0,0 +1,60 @@ +/** + * @fileoverview Utilities to operate on strings. + * @author Stephen Wade + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Graphemer = require("graphemer").default; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// eslint-disable-next-line no-control-regex -- intentionally including control characters +const ASCII_REGEX = /^[\u0000-\u007f]*$/u; + +/** @type {Graphemer | undefined} */ +let splitter; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Converts the first letter of a string to uppercase. + * @param {string} string The string to operate on + * @returns {string} The converted string + */ +function upperCaseFirst(string) { + if (string.length <= 1) { + return string.toUpperCase(); + } + return string[0].toUpperCase() + string.slice(1); +} + +/** + * Counts graphemes in a given string. + * @param {string} value A string to count graphemes. + * @returns {number} The number of graphemes in `value`. + */ +function getGraphemeCount(value) { + if (ASCII_REGEX.test(value)) { + return value.length; + } + + if (!splitter) { + splitter = new Graphemer(); + } + + return splitter.countGraphemes(value); +} + +module.exports = { + upperCaseFirst, + getGraphemeCount +}; diff --git a/node_modules/eslint/lib/shared/traverser.js b/node_modules/eslint/lib/shared/traverser.js new file mode 100644 index 0000000..38b4e21 --- /dev/null +++ b/node_modules/eslint/lib/shared/traverser.js @@ -0,0 +1,195 @@ +/** + * @fileoverview Traverser to traverse AST trees. + * @author Nicholas C. Zakas + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const vk = require("eslint-visitor-keys"); +const debug = require("debug")("eslint:traverser"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Do nothing. + * @returns {void} + */ +function noop() { + + // do nothing. +} + +/** + * Check whether the given value is an ASTNode or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an ASTNode. + */ +function isNode(x) { + return x !== null && typeof x === "object" && typeof x.type === "string"; +} + +/** + * Get the visitor keys of a given node. + * @param {Object} visitorKeys The map of visitor keys. + * @param {ASTNode} node The node to get their visitor keys. + * @returns {string[]} The visitor keys of the node. + */ +function getVisitorKeys(visitorKeys, node) { + let keys = visitorKeys[node.type]; + + if (!keys) { + keys = vk.getKeys(node); + debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys); + } + + return keys; +} + +/** + * The traverser class to traverse AST trees. + */ +class Traverser { + constructor() { + this._current = null; + this._parents = []; + this._skipped = false; + this._broken = false; + this._visitorKeys = null; + this._enter = null; + this._leave = null; + } + + /** + * Gives current node. + * @returns {ASTNode} The current node. + */ + current() { + return this._current; + } + + /** + * Gives a copy of the ancestor nodes. + * @returns {ASTNode[]} The ancestor nodes. + */ + parents() { + return this._parents.slice(0); + } + + /** + * Break the current traversal. + * @returns {void} + */ + break() { + this._broken = true; + } + + /** + * Skip child nodes for the current traversal. + * @returns {void} + */ + skip() { + this._skipped = true; + } + + /** + * Traverse the given AST tree. + * @param {ASTNode} node The root node to traverse. + * @param {Object} options The option object. + * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. + * @param {Function} [options.enter=noop] The callback function which is called on entering each node. + * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. + * @returns {void} + */ + traverse(node, options) { + this._current = null; + this._parents = []; + this._skipped = false; + this._broken = false; + this._visitorKeys = options.visitorKeys || vk.KEYS; + this._enter = options.enter || noop; + this._leave = options.leave || noop; + this._traverse(node, null); + } + + /** + * Traverse the given AST tree recursively. + * @param {ASTNode} node The current node. + * @param {ASTNode|null} parent The parent node. + * @returns {void} + * @private + */ + _traverse(node, parent) { + if (!isNode(node)) { + return; + } + + this._current = node; + this._skipped = false; + this._enter(node, parent); + + if (!this._skipped && !this._broken) { + const keys = getVisitorKeys(this._visitorKeys, node); + + if (keys.length >= 1) { + this._parents.push(node); + for (let i = 0; i < keys.length && !this._broken; ++i) { + const child = node[keys[i]]; + + if (Array.isArray(child)) { + for (let j = 0; j < child.length && !this._broken; ++j) { + this._traverse(child[j], node); + } + } else { + this._traverse(child, node); + } + } + this._parents.pop(); + } + } + + if (!this._broken) { + this._leave(node, parent); + } + + this._current = parent; + } + + /** + * Calculates the keys to use for traversal. + * @param {ASTNode} node The node to read keys from. + * @returns {string[]} An array of keys to visit on the node. + * @private + */ + static getKeys(node) { + return vk.getKeys(node); + } + + /** + * Traverse the given AST tree. + * @param {ASTNode} node The root node to traverse. + * @param {Object} options The option object. + * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. + * @param {Function} [options.enter=noop] The callback function which is called on entering each node. + * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. + * @returns {void} + */ + static traverse(node, options) { + new Traverser().traverse(node, options); + } + + /** + * The default visitor keys. + * @type {Object} + */ + static get DEFAULT_VISITOR_KEYS() { + return vk.KEYS; + } +} + +module.exports = Traverser; diff --git a/node_modules/eslint/lib/shared/types.js b/node_modules/eslint/lib/shared/types.js new file mode 100644 index 0000000..e3a40bc --- /dev/null +++ b/node_modules/eslint/lib/shared/types.js @@ -0,0 +1,216 @@ +/** + * @fileoverview Define common types for input completion. + * @author Toru Nagashima + */ +"use strict"; + +/** @type {any} */ +module.exports = {}; + +/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */ +/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */ +/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */ + +/** + * @typedef {Object} EcmaFeatures + * @property {boolean} [globalReturn] Enabling `return` statements at the top-level. + * @property {boolean} [jsx] Enabling JSX syntax. + * @property {boolean} [impliedStrict] Enabling strict mode always. + */ + +/** + * @typedef {Object} ParserOptions + * @property {EcmaFeatures} [ecmaFeatures] The optional features. + * @property {3|5|6|7|8|9|10|11|12|13|14|15|2015|2016|2017|2018|2019|2020|2021|2022|2023|2024} [ecmaVersion] The ECMAScript version (or revision number). + * @property {"script"|"module"} [sourceType] The source code type. + * @property {boolean} [allowReserved] Allowing the use of reserved words as identifiers in ES3. + */ + +/** + * @typedef {Object} LanguageOptions + * @property {number|"latest"} [ecmaVersion] The ECMAScript version (or revision number). + * @property {Record} [globals] The global variable settings. + * @property {"script"|"module"|"commonjs"} [sourceType] The source code type. + * @property {string|Object} [parser] The parser to use. + * @property {Object} [parserOptions] The parser options to use. + */ + +/** + * @typedef {Object} ConfigData + * @property {Record} [env] The environment settings. + * @property {string | string[]} [extends] The path to other config files or the package name of shareable configs. + * @property {Record} [globals] The global variable settings. + * @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint. + * @property {boolean} [noInlineConfig] The flag that disables directive comments. + * @property {OverrideConfigData[]} [overrides] The override settings per kind of files. + * @property {string} [parser] The path to a parser or the package name of a parser. + * @property {ParserOptions} [parserOptions] The parser options. + * @property {string[]} [plugins] The plugin specifiers. + * @property {string} [processor] The processor specifier. + * @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments. + * @property {boolean} [root] The root flag. + * @property {Record} [rules] The rule settings. + * @property {Object} [settings] The shared settings. + */ + +/** + * @typedef {Object} OverrideConfigData + * @property {Record} [env] The environment settings. + * @property {string | string[]} [excludedFiles] The glob patterns for excluded files. + * @property {string | string[]} [extends] The path to other config files or the package name of shareable configs. + * @property {string | string[]} files The glob patterns for target files. + * @property {Record} [globals] The global variable settings. + * @property {boolean} [noInlineConfig] The flag that disables directive comments. + * @property {OverrideConfigData[]} [overrides] The override settings per kind of files. + * @property {string} [parser] The path to a parser or the package name of a parser. + * @property {ParserOptions} [parserOptions] The parser options. + * @property {string[]} [plugins] The plugin specifiers. + * @property {string} [processor] The processor specifier. + * @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments. + * @property {Record} [rules] The rule settings. + * @property {Object} [settings] The shared settings. + */ + +/** + * @typedef {Object} ParseResult + * @property {Object} ast The AST. + * @property {ScopeManager} [scopeManager] The scope manager of the AST. + * @property {Record} [services] The services that the parser provides. + * @property {Record} [visitorKeys] The visitor keys of the AST. + */ + +/** + * @typedef {Object} Parser + * @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables. + * @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment. + */ + +/** + * @typedef {Object} Environment + * @property {Record} [globals] The definition of global variables. + * @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment. + */ + +/** + * @typedef {Object} LintMessage + * @property {number|undefined} column The 1-based column number. + * @property {number} [endColumn] The 1-based column number of the end location. + * @property {number} [endLine] The 1-based line number of the end location. + * @property {boolean} [fatal] If `true` then this is a fatal error. + * @property {{range:[number,number], text:string}} [fix] Information for autofix. + * @property {number|undefined} line The 1-based line number. + * @property {string} message The error message. + * @property {string} [messageId] The ID of the message in the rule's meta. + * @property {(string|null)} nodeType Type of node + * @property {string|null} ruleId The ID of the rule which makes this message. + * @property {0|1|2} severity The severity of this message. + * @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions. + */ + +/** + * @typedef {Object} SuppressedLintMessage + * @property {number|undefined} column The 1-based column number. + * @property {number} [endColumn] The 1-based column number of the end location. + * @property {number} [endLine] The 1-based line number of the end location. + * @property {boolean} [fatal] If `true` then this is a fatal error. + * @property {{range:[number,number], text:string}} [fix] Information for autofix. + * @property {number|undefined} line The 1-based line number. + * @property {string} message The error message. + * @property {string} [messageId] The ID of the message in the rule's meta. + * @property {(string|null)} nodeType Type of node + * @property {string|null} ruleId The ID of the rule which makes this message. + * @property {0|1|2} severity The severity of this message. + * @property {Array<{kind: string, justification: string}>} suppressions The suppression info. + * @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions. + */ + +/** + * @typedef {Object} SuggestionResult + * @property {string} desc A short description. + * @property {string} [messageId] Id referencing a message for the description. + * @property {{ text: string, range: number[] }} fix fix result info + */ + +/** + * @typedef {Object} Processor + * @property {(text:string, filename:string) => Array} [preprocess] The function to extract code blocks. + * @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages. + * @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix. + */ + +/** + * @typedef {Object} RuleMetaDocs + * @property {string} description The description of the rule. + * @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset. + * @property {string} url The URL of the rule documentation. + */ + +/** + * @typedef {Object} RuleMeta + * @property {boolean} [deprecated] If `true` then the rule has been deprecated. + * @property {RuleMetaDocs} docs The document information of the rule. + * @property {"code"|"whitespace"} [fixable] The autofix type. + * @property {boolean} [hasSuggestions] If `true` then the rule provides suggestions. + * @property {Record} [messages] The messages the rule reports. + * @property {string[]} [replacedBy] The IDs of the alternative rules. + * @property {Array|Object} schema The option schema of the rule. + * @property {"problem"|"suggestion"|"layout"} type The rule type. + */ + +/** + * @typedef {Object} Rule + * @property {Function} create The factory of the rule. + * @property {RuleMeta} meta The meta data of the rule. + */ + +/** + * @typedef {Object} Plugin + * @property {Record} [configs] The definition of plugin configs. + * @property {Record} [environments] The definition of plugin environments. + * @property {Record} [processors] The definition of plugin processors. + * @property {Record} [rules] The definition of plugin rules. + */ + +/** + * Information of deprecated rules. + * @typedef {Object} DeprecatedRuleInfo + * @property {string} ruleId The rule ID. + * @property {string[]} replacedBy The rule IDs that replace this deprecated rule. + */ + +/** + * A linting result. + * @typedef {Object} LintResult + * @property {string} filePath The path to the file that was linted. + * @property {LintMessage[]} messages All of the messages for the result. + * @property {SuppressedLintMessage[]} suppressedMessages All of the suppressed messages for the result. + * @property {number} errorCount Number of errors for the result. + * @property {number} fatalErrorCount Number of fatal errors for the result. + * @property {number} warningCount Number of warnings for the result. + * @property {number} fixableErrorCount Number of fixable errors for the result. + * @property {number} fixableWarningCount Number of fixable warnings for the result. + * @property {string} [source] The source code of the file that was linted. + * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible. + * @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules. + */ + +/** + * Information provided when the maximum warning threshold is exceeded. + * @typedef {Object} MaxWarningsExceeded + * @property {number} maxWarnings Number of warnings to trigger nonzero exit code. + * @property {number} foundWarnings Number of warnings found while linting. + */ + +/** + * Metadata about results for formatters. + * @typedef {Object} ResultsMeta + * @property {MaxWarningsExceeded} [maxWarningsExceeded] Present if the maxWarnings threshold was exceeded. + */ + +/** + * A formatter function. + * @callback FormatterFunction + * @param {LintResult[]} results The list of linting results. + * @param {{cwd: string, maxWarningsExceeded?: MaxWarningsExceeded, rulesMeta: Record}} [context] A context object. + * @returns {string | Promise} Formatted text. + */ diff --git a/node_modules/eslint/lib/source-code/index.js b/node_modules/eslint/lib/source-code/index.js new file mode 100644 index 0000000..76e2786 --- /dev/null +++ b/node_modules/eslint/lib/source-code/index.js @@ -0,0 +1,5 @@ +"use strict"; + +module.exports = { + SourceCode: require("./source-code") +}; diff --git a/node_modules/eslint/lib/source-code/source-code.js b/node_modules/eslint/lib/source-code/source-code.js new file mode 100644 index 0000000..07c0d29 --- /dev/null +++ b/node_modules/eslint/lib/source-code/source-code.js @@ -0,0 +1,729 @@ +/** + * @fileoverview Abstraction of JavaScript source code. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const + { isCommentToken } = require("@eslint-community/eslint-utils"), + TokenStore = require("./token-store"), + astUtils = require("../shared/ast-utils"), + Traverser = require("../shared/traverser"); + +//------------------------------------------------------------------------------ +// Type Definitions +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Variable} Variable */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +/** + * Validates that the given AST has the required information. + * @param {ASTNode} ast The Program node of the AST to check. + * @throws {Error} If the AST doesn't contain the correct information. + * @returns {void} + * @private + */ +function validate(ast) { + if (!ast.tokens) { + throw new Error("AST is missing the tokens array."); + } + + if (!ast.comments) { + throw new Error("AST is missing the comments array."); + } + + if (!ast.loc) { + throw new Error("AST is missing location information."); + } + + if (!ast.range) { + throw new Error("AST is missing range information"); + } +} + +/** + * Check to see if its a ES6 export declaration. + * @param {ASTNode} astNode An AST node. + * @returns {boolean} whether the given node represents an export declaration. + * @private + */ +function looksLikeExport(astNode) { + return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" || + astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier"; +} + +/** + * Merges two sorted lists into a larger sorted list in O(n) time. + * @param {Token[]} tokens The list of tokens. + * @param {Token[]} comments The list of comments. + * @returns {Token[]} A sorted list of tokens and comments. + * @private + */ +function sortedMerge(tokens, comments) { + const result = []; + let tokenIndex = 0; + let commentIndex = 0; + + while (tokenIndex < tokens.length || commentIndex < comments.length) { + if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) { + result.push(tokens[tokenIndex++]); + } else { + result.push(comments[commentIndex++]); + } + } + + return result; +} + +/** + * Determines if two nodes or tokens overlap. + * @param {ASTNode|Token} first The first node or token to check. + * @param {ASTNode|Token} second The second node or token to check. + * @returns {boolean} True if the two nodes or tokens overlap. + * @private + */ +function nodesOrTokensOverlap(first, second) { + return (first.range[0] <= second.range[0] && first.range[1] >= second.range[0]) || + (second.range[0] <= first.range[0] && second.range[1] >= first.range[0]); +} + +/** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * @param {SourceCode} sourceCode The source code object. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @param {boolean} checkInsideOfJSXText If `true` is present, check inside of JSXText tokens for backward compatibility. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @public + */ +function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) { + if (nodesOrTokensOverlap(first, second)) { + return false; + } + + const [startingNodeOrToken, endingNodeOrToken] = first.range[1] <= second.range[0] + ? [first, second] + : [second, first]; + const firstToken = sourceCode.getLastToken(startingNodeOrToken) || startingNodeOrToken; + const finalToken = sourceCode.getFirstToken(endingNodeOrToken) || endingNodeOrToken; + let currentToken = firstToken; + + while (currentToken !== finalToken) { + const nextToken = sourceCode.getTokenAfter(currentToken, { includeComments: true }); + + if ( + currentToken.range[1] !== nextToken.range[0] || + + /* + * For backward compatibility, check spaces in JSXText. + * https://github.com/eslint/eslint/issues/12614 + */ + ( + checkInsideOfJSXText && + nextToken !== finalToken && + nextToken.type === "JSXText" && + /\s/u.test(nextToken.value) + ) + ) { + return true; + } + + currentToken = nextToken; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +const caches = Symbol("caches"); + +/** + * Represents parsed source code. + */ +class SourceCode extends TokenStore { + + /** + * @param {string|Object} textOrConfig The source code text or config object. + * @param {string} textOrConfig.text The source code text. + * @param {ASTNode} textOrConfig.ast The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. + * @param {Object|null} textOrConfig.parserServices The parser services. + * @param {ScopeManager|null} textOrConfig.scopeManager The scope of this source code. + * @param {Object|null} textOrConfig.visitorKeys The visitor keys to traverse AST. + * @param {ASTNode} [astIfNoConfig] The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. + */ + constructor(textOrConfig, astIfNoConfig) { + let text, ast, parserServices, scopeManager, visitorKeys; + + // Process overloading. + if (typeof textOrConfig === "string") { + text = textOrConfig; + ast = astIfNoConfig; + } else if (typeof textOrConfig === "object" && textOrConfig !== null) { + text = textOrConfig.text; + ast = textOrConfig.ast; + parserServices = textOrConfig.parserServices; + scopeManager = textOrConfig.scopeManager; + visitorKeys = textOrConfig.visitorKeys; + } + + validate(ast); + super(ast.tokens, ast.comments); + + /** + * General purpose caching for the class. + */ + this[caches] = new Map([ + ["scopes", new WeakMap()] + ]); + + /** + * The flag to indicate that the source code has Unicode BOM. + * @type {boolean} + */ + this.hasBOM = (text.charCodeAt(0) === 0xFEFF); + + /** + * The original text source code. + * BOM was stripped from this text. + * @type {string} + */ + this.text = (this.hasBOM ? text.slice(1) : text); + + /** + * The parsed AST for the source code. + * @type {ASTNode} + */ + this.ast = ast; + + /** + * The parser services of this source code. + * @type {Object} + */ + this.parserServices = parserServices || {}; + + /** + * The scope of this source code. + * @type {ScopeManager|null} + */ + this.scopeManager = scopeManager || null; + + /** + * The visitor keys to traverse AST. + * @type {Object} + */ + this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS; + + // Check the source text for the presence of a shebang since it is parsed as a standard line comment. + const shebangMatched = this.text.match(astUtils.shebangPattern); + const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1]; + + if (hasShebang) { + ast.comments[0].type = "Shebang"; + } + + this.tokensAndComments = sortedMerge(ast.tokens, ast.comments); + + /** + * The source code split into lines according to ECMA-262 specification. + * This is done to avoid each rule needing to do so separately. + * @type {string[]} + */ + this.lines = []; + this.lineStartIndices = [0]; + + const lineEndingPattern = astUtils.createGlobalLinebreakMatcher(); + let match; + + /* + * Previously, this was implemented using a regex that + * matched a sequence of non-linebreak characters followed by a + * linebreak, then adding the lengths of the matches. However, + * this caused a catastrophic backtracking issue when the end + * of a file contained a large number of non-newline characters. + * To avoid this, the current implementation just matches newlines + * and uses match.index to get the correct line start indices. + */ + while ((match = lineEndingPattern.exec(this.text))) { + this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index)); + this.lineStartIndices.push(match.index + match[0].length); + } + this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1])); + + // Cache for comments found using getComments(). + this._commentCache = new WeakMap(); + + // don't allow modification of this object + Object.freeze(this); + Object.freeze(this.lines); + } + + /** + * Split the source code into multiple lines based on the line delimiters. + * @param {string} text Source code as a string. + * @returns {string[]} Array of source code lines. + * @public + */ + static splitLines(text) { + return text.split(astUtils.createGlobalLinebreakMatcher()); + } + + /** + * Gets the source code for the given node. + * @param {ASTNode} [node] The AST node to get the text for. + * @param {int} [beforeCount] The number of characters before the node to retrieve. + * @param {int} [afterCount] The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + * @public + */ + getText(node, beforeCount, afterCount) { + if (node) { + return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0), + node.range[1] + (afterCount || 0)); + } + return this.text; + } + + /** + * Gets the entire source text split into an array of lines. + * @returns {Array} The source text as an array of lines. + * @public + */ + getLines() { + return this.lines; + } + + /** + * Retrieves an array containing all comments in the source code. + * @returns {ASTNode[]} An array of comment nodes. + * @public + */ + getAllComments() { + return this.ast.comments; + } + + /** + * Gets all comments for the given node. + * @param {ASTNode} node The AST node to get the comments for. + * @returns {Object} An object containing a leading and trailing array + * of comments indexed by their position. + * @public + * @deprecated replaced by getCommentsBefore(), getCommentsAfter(), and getCommentsInside(). + */ + getComments(node) { + if (this._commentCache.has(node)) { + return this._commentCache.get(node); + } + + const comments = { + leading: [], + trailing: [] + }; + + /* + * Return all comments as leading comments of the Program node when + * there is no executable code. + */ + if (node.type === "Program") { + if (node.body.length === 0) { + comments.leading = node.comments; + } + } else { + + /* + * Return comments as trailing comments of nodes that only contain + * comments (to mimic the comment attachment behavior present in Espree). + */ + if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 || + node.type === "ObjectExpression" && node.properties.length === 0 || + node.type === "ArrayExpression" && node.elements.length === 0 || + node.type === "SwitchStatement" && node.cases.length === 0 + ) { + comments.trailing = this.getTokens(node, { + includeComments: true, + filter: isCommentToken + }); + } + + /* + * Iterate over tokens before and after node and collect comment tokens. + * Do not include comments that exist outside of the parent node + * to avoid duplication. + */ + let currentToken = this.getTokenBefore(node, { includeComments: true }); + + while (currentToken && isCommentToken(currentToken)) { + if (node.parent && node.parent.type !== "Program" && (currentToken.start < node.parent.start)) { + break; + } + comments.leading.push(currentToken); + currentToken = this.getTokenBefore(currentToken, { includeComments: true }); + } + + comments.leading.reverse(); + + currentToken = this.getTokenAfter(node, { includeComments: true }); + + while (currentToken && isCommentToken(currentToken)) { + if (node.parent && node.parent.type !== "Program" && (currentToken.end > node.parent.end)) { + break; + } + comments.trailing.push(currentToken); + currentToken = this.getTokenAfter(currentToken, { includeComments: true }); + } + } + + this._commentCache.set(node, comments); + return comments; + } + + /** + * Retrieves the JSDoc comment for a given node. + * @param {ASTNode} node The AST node to get the comment for. + * @returns {Token|null} The Block comment token containing the JSDoc comment + * for the given node or null if not found. + * @public + * @deprecated + */ + getJSDocComment(node) { + + /** + * Checks for the presence of a JSDoc comment for the given node and returns it. + * @param {ASTNode} astNode The AST node to get the comment for. + * @returns {Token|null} The Block comment token containing the JSDoc comment + * for the given node or null if not found. + * @private + */ + const findJSDocComment = astNode => { + const tokenBefore = this.getTokenBefore(astNode, { includeComments: true }); + + if ( + tokenBefore && + isCommentToken(tokenBefore) && + tokenBefore.type === "Block" && + tokenBefore.value.charAt(0) === "*" && + astNode.loc.start.line - tokenBefore.loc.end.line <= 1 + ) { + return tokenBefore; + } + + return null; + }; + let parent = node.parent; + + switch (node.type) { + case "ClassDeclaration": + case "FunctionDeclaration": + return findJSDocComment(looksLikeExport(parent) ? parent : node); + + case "ClassExpression": + return findJSDocComment(parent.parent); + + case "ArrowFunctionExpression": + case "FunctionExpression": + if (parent.type !== "CallExpression" && parent.type !== "NewExpression") { + while ( + !this.getCommentsBefore(parent).length && + !/Function/u.test(parent.type) && + parent.type !== "MethodDefinition" && + parent.type !== "Property" + ) { + parent = parent.parent; + + if (!parent) { + break; + } + } + + if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") { + return findJSDocComment(parent); + } + } + + return findJSDocComment(node); + + // falls through + default: + return null; + } + } + + /** + * Gets the deepest node containing a range index. + * @param {int} index Range index of the desired node. + * @returns {ASTNode} The node if found or null if not found. + * @public + */ + getNodeByRangeIndex(index) { + let result = null; + + Traverser.traverse(this.ast, { + visitorKeys: this.visitorKeys, + enter(node) { + if (node.range[0] <= index && index < node.range[1]) { + result = node; + } else { + this.skip(); + } + }, + leave(node) { + if (node === result) { + this.break(); + } + } + }); + + return result; + } + + /** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @public + */ + isSpaceBetween(first, second) { + return isSpaceBetween(this, first, second, false); + } + + /** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * For backward compatibility, this method returns true if there are + * `JSXText` tokens that contain whitespaces between the two. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @deprecated in favor of isSpaceBetween(). + * @public + */ + isSpaceBetweenTokens(first, second) { + return isSpaceBetween(this, first, second, true); + } + + /** + * Converts a source text index into a (line, column) pair. + * @param {number} index The index of a character in a file + * @throws {TypeError} If non-numeric index or index out of range. + * @returns {Object} A {line, column} location object with a 0-indexed column + * @public + */ + getLocFromIndex(index) { + if (typeof index !== "number") { + throw new TypeError("Expected `index` to be a number."); + } + + if (index < 0 || index > this.text.length) { + throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`); + } + + /* + * For an argument of this.text.length, return the location one "spot" past the last character + * of the file. If the last character is a linebreak, the location will be column 0 of the next + * line; otherwise, the location will be in the next column on the same line. + * + * See getIndexFromLoc for the motivation for this special case. + */ + if (index === this.text.length) { + return { line: this.lines.length, column: this.lines[this.lines.length - 1].length }; + } + + /* + * To figure out which line index is on, determine the last place at which index could + * be inserted into lineStartIndices to keep the list sorted. + */ + const lineNumber = index >= this.lineStartIndices[this.lineStartIndices.length - 1] + ? this.lineStartIndices.length + : this.lineStartIndices.findIndex(el => index < el); + + return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] }; + } + + /** + * Converts a (line, column) pair into a range index. + * @param {Object} loc A line/column location + * @param {number} loc.line The line number of the location (1-indexed) + * @param {number} loc.column The column number of the location (0-indexed) + * @throws {TypeError|RangeError} If `loc` is not an object with a numeric + * `line` and `column`, if the `line` is less than or equal to zero or + * the line or column is out of the expected range. + * @returns {number} The range index of the location in the file. + * @public + */ + getIndexFromLoc(loc) { + if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") { + throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties."); + } + + if (loc.line <= 0) { + throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`); + } + + if (loc.line > this.lineStartIndices.length) { + throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`); + } + + const lineStartIndex = this.lineStartIndices[loc.line - 1]; + const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line]; + const positionIndex = lineStartIndex + loc.column; + + /* + * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of + * the given line, provided that the line number is valid element of this.lines. Since the + * last element of this.lines is an empty string for files with trailing newlines, add a + * special case where getting the index for the first location after the end of the file + * will return the length of the file, rather than throwing an error. This allows rules to + * use getIndexFromLoc consistently without worrying about edge cases at the end of a file. + */ + if ( + loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex || + loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex + ) { + throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`); + } + + return positionIndex; + } + + /** + * Gets the scope for the given node + * @param {ASTNode} currentNode The node to get the scope of + * @returns {eslint-scope.Scope} The scope information for this node + * @throws {TypeError} If the `currentNode` argument is missing. + */ + getScope(currentNode) { + + if (!currentNode) { + throw new TypeError("Missing required argument: node."); + } + + // check cache first + const cache = this[caches].get("scopes"); + const cachedScope = cache.get(currentNode); + + if (cachedScope) { + return cachedScope; + } + + // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope. + const inner = currentNode.type !== "Program"; + + for (let node = currentNode; node; node = node.parent) { + const scope = this.scopeManager.acquire(node, inner); + + if (scope) { + if (scope.type === "function-expression-name") { + cache.set(currentNode, scope.childScopes[0]); + return scope.childScopes[0]; + } + + cache.set(currentNode, scope); + return scope; + } + } + + cache.set(currentNode, this.scopeManager.scopes[0]); + return this.scopeManager.scopes[0]; + } + + /** + * Get the variables that `node` defines. + * This is a convenience method that passes through + * to the same method on the `scopeManager`. + * @param {ASTNode} node The node for which the variables are obtained. + * @returns {Array} An array of variable nodes representing + * the variables that `node` defines. + */ + getDeclaredVariables(node) { + return this.scopeManager.getDeclaredVariables(node); + } + + /* eslint-disable class-methods-use-this -- node is owned by SourceCode */ + /** + * Gets all the ancestors of a given node + * @param {ASTNode} node The node + * @returns {Array} All the ancestor nodes in the AST, not including the provided node, starting + * from the root node at index 0 and going inwards to the parent node. + * @throws {TypeError} When `node` is missing. + */ + getAncestors(node) { + + if (!node) { + throw new TypeError("Missing required argument: node."); + } + + const ancestorsStartingAtParent = []; + + for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { + ancestorsStartingAtParent.push(ancestor); + } + + return ancestorsStartingAtParent.reverse(); + } + /* eslint-enable class-methods-use-this -- node is owned by SourceCode */ + + /** + * Marks a variable as used in the current scope + * @param {string} name The name of the variable to mark as used. + * @param {ASTNode} [refNode] The closest node to the variable reference. + * @returns {boolean} True if the variable was found and marked as used, false if not. + */ + markVariableAsUsed(name, refNode = this.ast) { + + const currentScope = this.getScope(refNode); + let initialScope = currentScope; + + /* + * When we are in an ESM or CommonJS module, we need to start searching + * from the top-level scope, not the global scope. For ESM the top-level + * scope is the module scope; for CommonJS the top-level scope is the + * outer function scope. + * + * Without this check, we might miss a variable declared with `var` at + * the top-level because it won't exist in the global scope. + */ + if ( + currentScope.type === "global" && + currentScope.childScopes.length > 0 && + + // top-level scopes refer to a `Program` node + currentScope.childScopes[0].block === this.ast + ) { + initialScope = currentScope.childScopes[0]; + } + + for (let scope = initialScope; scope; scope = scope.upper) { + const variable = scope.variables.find(scopeVar => scopeVar.name === name); + + if (variable) { + variable.eslintUsed = true; + return true; + } + } + + return false; + } + + +} + +module.exports = SourceCode; diff --git a/node_modules/eslint/lib/source-code/token-store/backward-token-comment-cursor.js b/node_modules/eslint/lib/source-code/token-store/backward-token-comment-cursor.js new file mode 100644 index 0000000..7255a62 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/backward-token-comment-cursor.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Define the cursor which iterates tokens and comments in reverse. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens and comments in reverse. + */ +module.exports = class BackwardTokenCommentCursor extends Cursor { + + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.comments = comments; + this.tokenIndex = utils.getLastIndex(tokens, indexMap, endLoc); + this.commentIndex = utils.search(comments, endLoc) - 1; + this.border = startLoc; + } + + /** @inheritdoc */ + moveNext() { + const token = (this.tokenIndex >= 0) ? this.tokens[this.tokenIndex] : null; + const comment = (this.commentIndex >= 0) ? this.comments[this.commentIndex] : null; + + if (token && (!comment || token.range[1] > comment.range[1])) { + this.current = token; + this.tokenIndex -= 1; + } else if (comment) { + this.current = comment; + this.commentIndex -= 1; + } else { + this.current = null; + } + + return Boolean(this.current) && (this.border === -1 || this.current.range[0] >= this.border); + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/backward-token-cursor.js b/node_modules/eslint/lib/source-code/token-store/backward-token-cursor.js new file mode 100644 index 0000000..454a244 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/backward-token-cursor.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Define the cursor which iterates tokens only in reverse. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only in reverse. + */ +module.exports = class BackwardTokenCursor extends Cursor { + + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.index = utils.getLastIndex(tokens, indexMap, endLoc); + this.indexEnd = utils.getFirstIndex(tokens, indexMap, startLoc); + } + + /** @inheritdoc */ + moveNext() { + if (this.index >= this.indexEnd) { + this.current = this.tokens[this.index]; + this.index -= 1; + return true; + } + return false; + } + + /* + * + * Shorthand for performance. + * + */ + + /** @inheritdoc */ + getOneToken() { + return (this.index >= this.indexEnd) ? this.tokens[this.index] : null; + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/cursor.js b/node_modules/eslint/lib/source-code/token-store/cursor.js new file mode 100644 index 0000000..0b72600 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/cursor.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Define the abstract class about cursors which iterate tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The abstract class about cursors which iterate tokens. + * + * This class has 2 abstract methods. + * + * - `current: Token | Comment | null` ... The current token. + * - `moveNext(): boolean` ... Moves this cursor to the next token. If the next token didn't exist, it returns `false`. + * + * This is similar to ES2015 Iterators. + * However, Iterators were slow (at 2017-01), so I created this class as similar to C# IEnumerable. + * + * There are the following known sub classes. + * + * - ForwardTokenCursor .......... The cursor which iterates tokens only. + * - BackwardTokenCursor ......... The cursor which iterates tokens only in reverse. + * - ForwardTokenCommentCursor ... The cursor which iterates tokens and comments. + * - BackwardTokenCommentCursor .. The cursor which iterates tokens and comments in reverse. + * - DecorativeCursor + * - FilterCursor ............ The cursor which ignores the specified tokens. + * - SkipCursor .............. The cursor which ignores the first few tokens. + * - LimitCursor ............. The cursor which limits the count of tokens. + * + */ +module.exports = class Cursor { + + /** + * Initializes this cursor. + */ + constructor() { + this.current = null; + } + + /** + * Gets the first token. + * This consumes this cursor. + * @returns {Token|Comment} The first token or null. + */ + getOneToken() { + return this.moveNext() ? this.current : null; + } + + /** + * Gets the first tokens. + * This consumes this cursor. + * @returns {(Token|Comment)[]} All tokens. + */ + getAllTokens() { + const tokens = []; + + while (this.moveNext()) { + tokens.push(this.current); + } + + return tokens; + } + + /** + * Moves this cursor to the next token. + * @returns {boolean} `true` if the next token exists. + * @abstract + */ + /* c8 ignore next */ + moveNext() { // eslint-disable-line class-methods-use-this -- Unused + throw new Error("Not implemented."); + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/cursors.js b/node_modules/eslint/lib/source-code/token-store/cursors.js new file mode 100644 index 0000000..30c72b6 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/cursors.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Define 2 token factories; forward and backward. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const BackwardTokenCommentCursor = require("./backward-token-comment-cursor"); +const BackwardTokenCursor = require("./backward-token-cursor"); +const FilterCursor = require("./filter-cursor"); +const ForwardTokenCommentCursor = require("./forward-token-comment-cursor"); +const ForwardTokenCursor = require("./forward-token-cursor"); +const LimitCursor = require("./limit-cursor"); +const SkipCursor = require("./skip-cursor"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * The cursor factory. + * @private + */ +class CursorFactory { + + /** + * Initializes this cursor. + * @param {Function} TokenCursor The class of the cursor which iterates tokens only. + * @param {Function} TokenCommentCursor The class of the cursor which iterates the mix of tokens and comments. + */ + constructor(TokenCursor, TokenCommentCursor) { + this.TokenCursor = TokenCursor; + this.TokenCommentCursor = TokenCommentCursor; + } + + /** + * Creates a base cursor instance that can be decorated by createCursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {boolean} includeComments The flag to iterate comments as well. + * @returns {Cursor} The created base cursor. + */ + createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments) { + const Cursor = includeComments ? this.TokenCommentCursor : this.TokenCursor; + + return new Cursor(tokens, comments, indexMap, startLoc, endLoc); + } + + /** + * Creates a cursor that iterates tokens with normalized options. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {boolean} includeComments The flag to iterate comments as well. + * @param {Function|null} filter The predicate function to choose tokens. + * @param {number} skip The count of tokens the cursor skips. + * @param {number} count The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + */ + createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, count) { + let cursor = this.createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments); + + if (filter) { + cursor = new FilterCursor(cursor, filter); + } + if (skip >= 1) { + cursor = new SkipCursor(cursor, skip); + } + if (count >= 0) { + cursor = new LimitCursor(cursor, count); + } + + return cursor; + } +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +exports.forward = new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor); +exports.backward = new CursorFactory(BackwardTokenCursor, BackwardTokenCommentCursor); diff --git a/node_modules/eslint/lib/source-code/token-store/decorative-cursor.js b/node_modules/eslint/lib/source-code/token-store/decorative-cursor.js new file mode 100644 index 0000000..3ee7b0b --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/decorative-cursor.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Define the abstract class about cursors which manipulate another cursor. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The abstract class about cursors which manipulate another cursor. + */ +module.exports = class DecorativeCursor extends Cursor { + + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + */ + constructor(cursor) { + super(); + this.cursor = cursor; + } + + /** @inheritdoc */ + moveNext() { + const retv = this.cursor.moveNext(); + + this.current = this.cursor.current; + + return retv; + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/filter-cursor.js b/node_modules/eslint/lib/source-code/token-store/filter-cursor.js new file mode 100644 index 0000000..08c4f22 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/filter-cursor.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Define the cursor which ignores specified tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which ignores specified tokens. + */ +module.exports = class FilterCursor extends DecorativeCursor { + + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {Function} predicate The predicate function to decide tokens this cursor iterates. + */ + constructor(cursor, predicate) { + super(cursor); + this.predicate = predicate; + } + + /** @inheritdoc */ + moveNext() { + const predicate = this.predicate; + + while (super.moveNext()) { + if (predicate(this.current)) { + return true; + } + } + return false; + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/forward-token-comment-cursor.js b/node_modules/eslint/lib/source-code/token-store/forward-token-comment-cursor.js new file mode 100644 index 0000000..50c7a39 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/forward-token-comment-cursor.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Define the cursor which iterates tokens and comments. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens and comments. + */ +module.exports = class ForwardTokenCommentCursor extends Cursor { + + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.comments = comments; + this.tokenIndex = utils.getFirstIndex(tokens, indexMap, startLoc); + this.commentIndex = utils.search(comments, startLoc); + this.border = endLoc; + } + + /** @inheritdoc */ + moveNext() { + const token = (this.tokenIndex < this.tokens.length) ? this.tokens[this.tokenIndex] : null; + const comment = (this.commentIndex < this.comments.length) ? this.comments[this.commentIndex] : null; + + if (token && (!comment || token.range[0] < comment.range[0])) { + this.current = token; + this.tokenIndex += 1; + } else if (comment) { + this.current = comment; + this.commentIndex += 1; + } else { + this.current = null; + } + + return Boolean(this.current) && (this.border === -1 || this.current.range[1] <= this.border); + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/forward-token-cursor.js b/node_modules/eslint/lib/source-code/token-store/forward-token-cursor.js new file mode 100644 index 0000000..e8c1860 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/forward-token-cursor.js @@ -0,0 +1,63 @@ +/** + * @fileoverview Define the cursor which iterates tokens only. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only. + */ +module.exports = class ForwardTokenCursor extends Cursor { + + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.index = utils.getFirstIndex(tokens, indexMap, startLoc); + this.indexEnd = utils.getLastIndex(tokens, indexMap, endLoc); + } + + /** @inheritdoc */ + moveNext() { + if (this.index <= this.indexEnd) { + this.current = this.tokens[this.index]; + this.index += 1; + return true; + } + return false; + } + + /* + * + * Shorthand for performance. + * + */ + + /** @inheritdoc */ + getOneToken() { + return (this.index <= this.indexEnd) ? this.tokens[this.index] : null; + } + + /** @inheritdoc */ + getAllTokens() { + return this.tokens.slice(this.index, this.indexEnd + 1); + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/index.js b/node_modules/eslint/lib/source-code/token-store/index.js new file mode 100644 index 0000000..46a96b2 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/index.js @@ -0,0 +1,627 @@ +/** + * @fileoverview Object to handle access and retrieval of tokens. + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("assert"); +const { isCommentToken } = require("@eslint-community/eslint-utils"); +const cursors = require("./cursors"); +const ForwardTokenCursor = require("./forward-token-cursor"); +const PaddedTokenCursor = require("./padded-token-cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TOKENS = Symbol("tokens"); +const COMMENTS = Symbol("comments"); +const INDEX_MAP = Symbol("indexMap"); + +/** + * Creates the map from locations to indices in `tokens`. + * + * The first/last location of tokens is mapped to the index of the token. + * The first/last location of comments is mapped to the index of the next token of each comment. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @returns {Object} The map from locations to indices in `tokens`. + * @private + */ +function createIndexMap(tokens, comments) { + const map = Object.create(null); + let tokenIndex = 0; + let commentIndex = 0; + let nextStart = 0; + let range = null; + + while (tokenIndex < tokens.length || commentIndex < comments.length) { + nextStart = (commentIndex < comments.length) ? comments[commentIndex].range[0] : Number.MAX_SAFE_INTEGER; + while (tokenIndex < tokens.length && (range = tokens[tokenIndex].range)[0] < nextStart) { + map[range[0]] = tokenIndex; + map[range[1] - 1] = tokenIndex; + tokenIndex += 1; + } + + nextStart = (tokenIndex < tokens.length) ? tokens[tokenIndex].range[0] : Number.MAX_SAFE_INTEGER; + while (commentIndex < comments.length && (range = comments[commentIndex].range)[0] < nextStart) { + map[range[0]] = tokenIndex; + map[range[1] - 1] = tokenIndex; + commentIndex += 1; + } + } + + return map; +} + +/** + * Creates the cursor iterates tokens with options. + * @param {CursorFactory} factory The cursor factory to initialize cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.skip`. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.skip=0] The count of tokens the cursor skips. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithSkip(factory, tokens, comments, indexMap, startLoc, endLoc, opts) { + let includeComments = false; + let skip = 0; + let filter = null; + + if (typeof opts === "number") { + skip = opts | 0; + } else if (typeof opts === "function") { + filter = opts; + } else if (opts) { + includeComments = !!opts.includeComments; + skip = opts.skip | 0; + filter = opts.filter || null; + } + assert(skip >= 0, "options.skip should be zero or a positive integer."); + assert(!filter || typeof filter === "function", "options.filter should be a function."); + + return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, -1); +} + +/** + * Creates the cursor iterates tokens with options. + * @param {CursorFactory} factory The cursor factory to initialize cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.count`. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithCount(factory, tokens, comments, indexMap, startLoc, endLoc, opts) { + let includeComments = false; + let count = 0; + let countExists = false; + let filter = null; + + if (typeof opts === "number") { + count = opts | 0; + countExists = true; + } else if (typeof opts === "function") { + filter = opts; + } else if (opts) { + includeComments = !!opts.includeComments; + count = opts.count | 0; + countExists = typeof opts.count === "number"; + filter = opts.filter || null; + } + assert(count >= 0, "options.count should be zero or a positive integer."); + assert(!filter || typeof filter === "function", "options.filter should be a function."); + + return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, 0, countExists ? count : -1); +} + +/** + * Creates the cursor iterates tokens with options. + * This is overload function of the below. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {Function|Object} opts The option object. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + * @private + */ +/** + * Creates the cursor iterates tokens with options. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number} [beforeCount=0] The number of tokens before the node to retrieve. + * @param {boolean} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithPadding(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) { + if (typeof beforeCount === "undefined" && typeof afterCount === "undefined") { + return new ForwardTokenCursor(tokens, comments, indexMap, startLoc, endLoc); + } + if (typeof beforeCount === "number" || typeof beforeCount === "undefined") { + return new PaddedTokenCursor(tokens, comments, indexMap, startLoc, endLoc, beforeCount | 0, afterCount | 0); + } + return createCursorWithCount(cursors.forward, tokens, comments, indexMap, startLoc, endLoc, beforeCount); +} + +/** + * Gets comment tokens that are adjacent to the current cursor position. + * @param {Cursor} cursor A cursor instance. + * @returns {Array} An array of comment tokens adjacent to the current cursor position. + * @private + */ +function getAdjacentCommentTokensFromCursor(cursor) { + const tokens = []; + let currentToken = cursor.getOneToken(); + + while (currentToken && isCommentToken(currentToken)) { + tokens.push(currentToken); + currentToken = cursor.getOneToken(); + } + + return tokens; +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The token store. + * + * This class provides methods to get tokens by locations as fast as possible. + * The methods are a part of public API, so we should be careful if it changes this class. + * + * People can get tokens in O(1) by the hash map which is mapping from the location of tokens/comments to tokens. + * Also people can get a mix of tokens and comments in O(log k), the k is the number of comments. + * Assuming that comments to be much fewer than tokens, this does not make hash map from token's locations to comments to reduce memory cost. + * This uses binary-searching instead for comments. + */ +module.exports = class TokenStore { + + /** + * Initializes this token store. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + */ + constructor(tokens, comments) { + this[TOKENS] = tokens; + this[COMMENTS] = comments; + this[INDEX_MAP] = createIndexMap(tokens, comments); + } + + //-------------------------------------------------------------------------- + // Gets single token. + //-------------------------------------------------------------------------- + + /** + * Gets the token starting at the specified index. + * @param {number} offset Index of the start of the token's range. + * @param {Object} [options=0] The option object. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @returns {Token|null} The token starting at index, or null if no such token. + */ + getTokenByRangeStart(offset, options) { + const includeComments = options && options.includeComments; + const token = cursors.forward.createBaseCursor( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + offset, + -1, + includeComments + ).getOneToken(); + + if (token && token.range[0] === offset) { + return token; + } + return null; + } + + /** + * Gets the first token of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.skip=0] The count of tokens the cursor skips. + * @returns {Token|null} An object representing the token. + */ + getFirstToken(node, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options + ).getOneToken(); + } + + /** + * Gets the last token of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getLastToken(node, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options + ).getOneToken(); + } + + /** + * Gets the token that precedes a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getTokenBefore(node, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + node.range[0], + options + ).getOneToken(); + } + + /** + * Gets the token that follows a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getTokenAfter(node, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[1], + -1, + options + ).getOneToken(); + } + + /** + * Gets the first token between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getFirstTokenBetween(left, right, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options + ).getOneToken(); + } + + /** + * Gets the last token between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getLastTokenBetween(left, right, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options + ).getOneToken(); + } + + /** + * Gets the token that precedes a given node or token in the token stream. + * This is defined for backward compatibility. Use `includeComments` option instead. + * TODO: We have a plan to remove this in a future major version. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number} [skip=0] A number of tokens to skip. + * @returns {Token|null} An object representing the token. + * @deprecated + */ + getTokenOrCommentBefore(node, skip) { + return this.getTokenBefore(node, { includeComments: true, skip }); + } + + /** + * Gets the token that follows a given node or token in the token stream. + * This is defined for backward compatibility. Use `includeComments` option instead. + * TODO: We have a plan to remove this in a future major version. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number} [skip=0] A number of tokens to skip. + * @returns {Token|null} An object representing the token. + * @deprecated + */ + getTokenOrCommentAfter(node, skip) { + return this.getTokenAfter(node, { includeComments: true, skip }); + } + + //-------------------------------------------------------------------------- + // Gets multiple tokens. + //-------------------------------------------------------------------------- + + /** + * Gets the first `count` tokens of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Tokens. + */ + getFirstTokens(node, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options + ).getAllTokens(); + } + + /** + * Gets the last `count` tokens of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getLastTokens(node, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options + ).getAllTokens().reverse(); + } + + /** + * Gets the `count` tokens that precedes a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getTokensBefore(node, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + node.range[0], + options + ).getAllTokens().reverse(); + } + + /** + * Gets the `count` tokens that follows a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getTokensAfter(node, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[1], + -1, + options + ).getAllTokens(); + } + + /** + * Gets the first `count` tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens between left and right. + */ + getFirstTokensBetween(left, right, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options + ).getAllTokens(); + } + + /** + * Gets the last `count` tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens between left and right. + */ + getLastTokensBetween(left, right, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options + ).getAllTokens().reverse(); + } + + /** + * Gets all tokens that are related to the given node. + * @param {ASTNode} node The AST node. + * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Array of objects representing tokens. + */ + /** + * Gets all tokens that are related to the given node. + * @param {ASTNode} node The AST node. + * @param {int} [beforeCount=0] The number of tokens before the node to retrieve. + * @param {int} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {Token[]} Array of objects representing tokens. + */ + getTokens(node, beforeCount, afterCount) { + return createCursorWithPadding( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + beforeCount, + afterCount + ).getAllTokens(); + } + + /** + * Gets all of the tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Tokens between left and right. + */ + /** + * Gets all of the tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {int} [padding=0] Number of extra tokens on either side of center. + * @returns {Token[]} Tokens between left and right. + */ + getTokensBetween(left, right, padding) { + return createCursorWithPadding( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + padding, + padding + ).getAllTokens(); + } + + //-------------------------------------------------------------------------- + // Others. + //-------------------------------------------------------------------------- + + /** + * Checks whether any comments exist or not between the given 2 nodes. + * @param {ASTNode} left The node to check. + * @param {ASTNode} right The node to check. + * @returns {boolean} `true` if one or more comments exist. + */ + commentsExistBetween(left, right) { + const index = utils.search(this[COMMENTS], left.range[1]); + + return ( + index < this[COMMENTS].length && + this[COMMENTS][index].range[1] <= right.range[0] + ); + } + + /** + * Gets all comment tokens directly before the given node or token. + * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsBefore(nodeOrToken) { + const cursor = createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + nodeOrToken.range[0], + { includeComments: true } + ); + + return getAdjacentCommentTokensFromCursor(cursor).reverse(); + } + + /** + * Gets all comment tokens directly after the given node or token. + * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsAfter(nodeOrToken) { + const cursor = createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + nodeOrToken.range[1], + -1, + { includeComments: true } + ); + + return getAdjacentCommentTokensFromCursor(cursor); + } + + /** + * Gets all comment tokens inside the given node. + * @param {ASTNode} node The AST node to get the comments for. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsInside(node) { + return this.getTokens(node, { + includeComments: true, + filter: isCommentToken + }); + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/limit-cursor.js b/node_modules/eslint/lib/source-code/token-store/limit-cursor.js new file mode 100644 index 0000000..0fd92a7 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/limit-cursor.js @@ -0,0 +1,40 @@ +/** + * @fileoverview Define the cursor which limits the number of tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which limits the number of tokens. + */ +module.exports = class LimitCursor extends DecorativeCursor { + + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {number} count The count of tokens this cursor iterates. + */ + constructor(cursor, count) { + super(cursor); + this.count = count; + } + + /** @inheritdoc */ + moveNext() { + if (this.count > 0) { + this.count -= 1; + return super.moveNext(); + } + return false; + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/padded-token-cursor.js b/node_modules/eslint/lib/source-code/token-store/padded-token-cursor.js new file mode 100644 index 0000000..89349fa --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/padded-token-cursor.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Define the cursor which iterates tokens only, with inflated range. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const ForwardTokenCursor = require("./forward-token-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only, with inflated range. + * This is for the backward compatibility of padding options. + */ +module.exports = class PaddedTokenCursor extends ForwardTokenCursor { + + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number} beforeCount The number of tokens this cursor iterates before start. + * @param {number} afterCount The number of tokens this cursor iterates after end. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) { + super(tokens, comments, indexMap, startLoc, endLoc); + this.index = Math.max(0, this.index - beforeCount); + this.indexEnd = Math.min(tokens.length - 1, this.indexEnd + afterCount); + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/skip-cursor.js b/node_modules/eslint/lib/source-code/token-store/skip-cursor.js new file mode 100644 index 0000000..f068f53 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/skip-cursor.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Define the cursor which ignores the first few tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which ignores the first few tokens. + */ +module.exports = class SkipCursor extends DecorativeCursor { + + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {number} count The count of tokens this cursor skips. + */ + constructor(cursor, count) { + super(cursor); + this.count = count; + } + + /** @inheritdoc */ + moveNext() { + while (this.count > 0) { + this.count -= 1; + if (!super.moveNext()) { + return false; + } + } + return super.moveNext(); + } +}; diff --git a/node_modules/eslint/lib/source-code/token-store/utils.js b/node_modules/eslint/lib/source-code/token-store/utils.js new file mode 100644 index 0000000..3e01470 --- /dev/null +++ b/node_modules/eslint/lib/source-code/token-store/utils.js @@ -0,0 +1,107 @@ +/** + * @fileoverview Define utility functions for token store. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * Finds the index of the first token which is after the given location. + * If it was not found, this returns `tokens.length`. + * @param {(Token|Comment)[]} tokens It searches the token in this list. + * @param {number} location The location to search. + * @returns {number} The found index or `tokens.length`. + */ +exports.search = function search(tokens, location) { + for (let minIndex = 0, maxIndex = tokens.length - 1; minIndex <= maxIndex;) { + + /* + * Calculate the index in the middle between minIndex and maxIndex. + * `| 0` is used to round a fractional value down to the nearest integer: this is similar to + * using `Math.trunc()` or `Math.floor()`, but performance tests have shown this method to + * be faster. + */ + const index = (minIndex + maxIndex) / 2 | 0; + const token = tokens[index]; + const tokenStartLocation = token.range[0]; + + if (location <= tokenStartLocation) { + if (index === minIndex) { + return index; + } + maxIndex = index; + } else { + minIndex = index + 1; + } + } + return tokens.length; +}; + +/** + * Gets the index of the `startLoc` in `tokens`. + * `startLoc` can be the value of `node.range[1]`, so this checks about `startLoc - 1` as well. + * @param {(Token|Comment)[]} tokens The tokens to find an index. + * @param {Object} indexMap The map from locations to indices. + * @param {number} startLoc The location to get an index. + * @returns {number} The index. + */ +exports.getFirstIndex = function getFirstIndex(tokens, indexMap, startLoc) { + if (startLoc in indexMap) { + return indexMap[startLoc]; + } + if ((startLoc - 1) in indexMap) { + const index = indexMap[startLoc - 1]; + const token = tokens[index]; + + // If the mapped index is out of bounds, the returned cursor index will point after the end of the tokens array. + if (!token) { + return tokens.length; + } + + /* + * For the map of "comment's location -> token's index", it points the next token of a comment. + * In that case, +1 is unnecessary. + */ + if (token.range[0] >= startLoc) { + return index; + } + return index + 1; + } + return 0; +}; + +/** + * Gets the index of the `endLoc` in `tokens`. + * The information of end locations are recorded at `endLoc - 1` in `indexMap`, so this checks about `endLoc - 1` as well. + * @param {(Token|Comment)[]} tokens The tokens to find an index. + * @param {Object} indexMap The map from locations to indices. + * @param {number} endLoc The location to get an index. + * @returns {number} The index. + */ +exports.getLastIndex = function getLastIndex(tokens, indexMap, endLoc) { + if (endLoc in indexMap) { + return indexMap[endLoc] - 1; + } + if ((endLoc - 1) in indexMap) { + const index = indexMap[endLoc - 1]; + const token = tokens[index]; + + // If the mapped index is out of bounds, the returned cursor index will point before the end of the tokens array. + if (!token) { + return tokens.length - 1; + } + + /* + * For the map of "comment's location -> token's index", it points the next token of a comment. + * In that case, -1 is necessary. + */ + if (token.range[1] > endLoc) { + return index - 1; + } + return index; + } + return tokens.length - 1; +}; diff --git a/node_modules/eslint/lib/unsupported-api.js b/node_modules/eslint/lib/unsupported-api.js new file mode 100644 index 0000000..8a2e147 --- /dev/null +++ b/node_modules/eslint/lib/unsupported-api.js @@ -0,0 +1,30 @@ +/** + * @fileoverview APIs that are not officially supported by ESLint. + * These APIs may change or be removed at any time. Use at your + * own risk. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { FileEnumerator } = require("./cli-engine/file-enumerator"); +const { FlatESLint, shouldUseFlatConfig } = require("./eslint/flat-eslint"); +const FlatRuleTester = require("./rule-tester/flat-rule-tester"); +const { ESLint } = require("./eslint/eslint"); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + builtinRules: require("./rules"), + FlatESLint, + shouldUseFlatConfig, + FlatRuleTester, + FileEnumerator, + LegacyESLint: ESLint +}; diff --git a/node_modules/eslint/messages/all-files-ignored.js b/node_modules/eslint/messages/all-files-ignored.js new file mode 100644 index 0000000..70877a4 --- /dev/null +++ b/node_modules/eslint/messages/all-files-ignored.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function(it) { + const { pattern } = it; + + return ` +You are linting "${pattern}", but all of the files matching the glob pattern "${pattern}" are ignored. + +If you don't want to lint these files, remove the pattern "${pattern}" from the list of arguments passed to ESLint. + +If you do want to lint these files, try the following solutions: + +* Check your .eslintignore file, or the eslintIgnore property in package.json, to ensure that the files are not configured to be ignored. +* Explicitly list the files from this glob that you'd like to lint on the command-line, rather than providing a glob as an argument. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/eslintrc-incompat.js b/node_modules/eslint/messages/eslintrc-incompat.js new file mode 100644 index 0000000..deffca5 --- /dev/null +++ b/node_modules/eslint/messages/eslintrc-incompat.js @@ -0,0 +1,98 @@ +"use strict"; + +/* eslint consistent-return: 0 -- no default case */ + +const messages = { + + env: ` +A config object is using the "env" key, which is not supported in flat config system. + +Flat config uses "languageOptions.globals" to define global variables for your files. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configuring-language-options +`, + + extends: ` +A config object is using the "extends" key, which is not supported in flat config system. + +Instead of "extends", you can include config objects that you'd like to extend from directly in the flat config array. + +Please see the following page for more information: +https://eslint.org/docs/latest/use/configure/migration-guide#predefined-configs +`, + + globals: ` +A config object is using the "globals" key, which is not supported in flat config system. + +Flat config uses "languageOptions.globals" to define global variables for your files. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configuring-language-options +`, + + ignorePatterns: ` +A config object is using the "ignorePatterns" key, which is not supported in flat config system. + +Flat config uses "ignores" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#ignoring-files +`, + + noInlineConfig: ` +A config object is using the "noInlineConfig" key, which is not supported in flat config system. + +Flat config uses "linterOptions.noInlineConfig" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#linter-options +`, + + overrides: ` +A config object is using the "overrides" key, which is not supported in flat config system. + +Flat config is an array that acts like the eslintrc "overrides" array. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#glob-based-configs +`, + + parser: ` +A config object is using the "parser" key, which is not supported in flat config system. + +Flat config uses "languageOptions.parser" to override the default parser. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#custom-parsers +`, + + parserOptions: ` +A config object is using the "parserOptions" key, which is not supported in flat config system. + +Flat config uses "languageOptions.parserOptions" to specify parser options. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configuring-language-options +`, + + reportUnusedDisableDirectives: ` +A config object is using the "reportUnusedDisableDirectives" key, which is not supported in flat config system. + +Flat config uses "linterOptions.reportUnusedDisableDirectives" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#linter-options +`, + + root: ` +A config object is using the "root" key, which is not supported in flat config system. + +Flat configs always act as if they are the root config file, so this key can be safely removed. +` +}; + +module.exports = function({ key }) { + + return messages[key].trim(); +}; diff --git a/node_modules/eslint/messages/eslintrc-plugins.js b/node_modules/eslint/messages/eslintrc-plugins.js new file mode 100644 index 0000000..bb708c9 --- /dev/null +++ b/node_modules/eslint/messages/eslintrc-plugins.js @@ -0,0 +1,24 @@ +"use strict"; + +module.exports = function({ plugins }) { + + const isArrayOfStrings = typeof plugins[0] === "string"; + + return ` +A config object has a "plugins" key defined as an array${isArrayOfStrings ? " of strings" : ""}. + +Flat config requires "plugins" to be an object in this form: + + { + plugins: { + ${isArrayOfStrings && plugins[0] ? plugins[0] : "namespace"}: pluginObject + } + } + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#importing-plugins-and-custom-parsers + +If you're using a shareable config that you cannot rewrite in flat config format, then use the compatibility utility: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`; +}; diff --git a/node_modules/eslint/messages/extend-config-missing.js b/node_modules/eslint/messages/extend-config-missing.js new file mode 100644 index 0000000..5b3498f --- /dev/null +++ b/node_modules/eslint/messages/extend-config-missing.js @@ -0,0 +1,13 @@ +"use strict"; + +module.exports = function(it) { + const { configName, importerName } = it; + + return ` +ESLint couldn't find the config "${configName}" to extend from. Please check that the name of the config is correct. + +The config "${configName}" was referenced from the config file in "${importerName}". + +If you still have problems, please stop by https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/failed-to-read-json.js b/node_modules/eslint/messages/failed-to-read-json.js new file mode 100644 index 0000000..e7c6cb5 --- /dev/null +++ b/node_modules/eslint/messages/failed-to-read-json.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = function(it) { + const { path, message } = it; + + return ` +Failed to read JSON file at ${path}: + +${message} +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/file-not-found.js b/node_modules/eslint/messages/file-not-found.js new file mode 100644 index 0000000..1a62fcf --- /dev/null +++ b/node_modules/eslint/messages/file-not-found.js @@ -0,0 +1,10 @@ +"use strict"; + +module.exports = function(it) { + const { pattern, globDisabled } = it; + + return ` +No files matching the pattern "${pattern}"${globDisabled ? " (with disabling globs)" : ""} were found. +Please check for typing mistakes in the pattern. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/invalid-rule-options.js b/node_modules/eslint/messages/invalid-rule-options.js new file mode 100644 index 0000000..9a8acc9 --- /dev/null +++ b/node_modules/eslint/messages/invalid-rule-options.js @@ -0,0 +1,17 @@ +"use strict"; + +const { stringifyValueForError } = require("./shared"); + +module.exports = function({ ruleId, value }) { + return ` +Configuration for rule "${ruleId}" is invalid. Each rule must have a severity ("off", 0, "warn", 1, "error", or 2) and may be followed by additional options for the rule. + +You passed '${stringifyValueForError(value, 4)}', which doesn't contain a valid severity. + +If you're attempting to configure rule options, perhaps you meant: + + "${ruleId}": ["error", ${stringifyValueForError(value, 8)}] + +See https://eslint.org/docs/latest/use/configure/rules#using-configuration-files for configuring rules. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/invalid-rule-severity.js b/node_modules/eslint/messages/invalid-rule-severity.js new file mode 100644 index 0000000..3f13183 --- /dev/null +++ b/node_modules/eslint/messages/invalid-rule-severity.js @@ -0,0 +1,13 @@ +"use strict"; + +const { stringifyValueForError } = require("./shared"); + +module.exports = function({ ruleId, value }) { + return ` +Configuration for rule "${ruleId}" is invalid. Expected severity of "off", 0, "warn", 1, "error", or 2. + +You passed '${stringifyValueForError(value, 4)}'. + +See https://eslint.org/docs/latest/use/configure/rules#using-configuration-files for configuring rules. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/no-config-found.js b/node_modules/eslint/messages/no-config-found.js new file mode 100644 index 0000000..21cf549 --- /dev/null +++ b/node_modules/eslint/messages/no-config-found.js @@ -0,0 +1,15 @@ +"use strict"; + +module.exports = function(it) { + const { directoryPath } = it; + + return ` +ESLint couldn't find a configuration file. To set up a configuration file for this project, please run: + + npm init @eslint/config + +ESLint looked for configuration files in ${directoryPath} and its ancestors. If it found none, it then looked in your home directory. + +If you think you already have a configuration file or if you need more help, please stop by the ESLint Discord server: https://eslint.org/chat +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/plugin-conflict.js b/node_modules/eslint/messages/plugin-conflict.js new file mode 100644 index 0000000..c8c060e --- /dev/null +++ b/node_modules/eslint/messages/plugin-conflict.js @@ -0,0 +1,22 @@ +"use strict"; + +module.exports = function(it) { + const { pluginId, plugins } = it; + + let result = `ESLint couldn't determine the plugin "${pluginId}" uniquely. +`; + + for (const { filePath, importerName } of plugins) { + result += ` +- ${filePath} (loaded in "${importerName}")`; + } + + result += ` + +Please remove the "plugins" setting from either config or remove either plugin installation. + +If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. +`; + + return result; +}; diff --git a/node_modules/eslint/messages/plugin-invalid.js b/node_modules/eslint/messages/plugin-invalid.js new file mode 100644 index 0000000..8b471d4 --- /dev/null +++ b/node_modules/eslint/messages/plugin-invalid.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function(it) { + const { configName, importerName } = it; + + return ` +"${configName}" is invalid syntax for a config specifier. + +* If your intention is to extend from a configuration exported from the plugin, add the configuration name after a slash: e.g. "${configName}/myConfig". +* If this is the name of a shareable config instead of a plugin, remove the "plugin:" prefix: i.e. "${configName.slice("plugin:".length)}". + +"${configName}" was referenced from the config file in "${importerName}". + +If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/plugin-missing.js b/node_modules/eslint/messages/plugin-missing.js new file mode 100644 index 0000000..0b7d34e --- /dev/null +++ b/node_modules/eslint/messages/plugin-missing.js @@ -0,0 +1,19 @@ +"use strict"; + +module.exports = function(it) { + const { pluginName, resolvePluginsRelativeTo, importerName } = it; + + return ` +ESLint couldn't find the plugin "${pluginName}". + +(The package "${pluginName}" was not found when loaded as a Node module from the directory "${resolvePluginsRelativeTo}".) + +It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: + + npm install ${pluginName}@latest --save-dev + +The plugin "${pluginName}" was referenced from the config file in "${importerName}". + +If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/print-config-with-directory-path.js b/node_modules/eslint/messages/print-config-with-directory-path.js new file mode 100644 index 0000000..4559c8d --- /dev/null +++ b/node_modules/eslint/messages/print-config-with-directory-path.js @@ -0,0 +1,8 @@ +"use strict"; + +module.exports = function() { + return ` +The '--print-config' CLI option requires a path to a source code file rather than a directory. +See also: https://eslint.org/docs/latest/use/command-line-interface#--print-config +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/shared.js b/node_modules/eslint/messages/shared.js new file mode 100644 index 0000000..8c6e9b9 --- /dev/null +++ b/node_modules/eslint/messages/shared.js @@ -0,0 +1,18 @@ +/** + * @fileoverview Shared utilities for error messages. + * @author Josh Goldberg + */ + +"use strict"; + +/** + * Converts a value to a string that may be printed in errors. + * @param {any} value The invalid value. + * @param {number} indentation How many spaces to indent + * @returns {string} The value, stringified. + */ +function stringifyValueForError(value, indentation) { + return value ? JSON.stringify(value, null, 4).replace(/\n/gu, `\n${" ".repeat(indentation)}`) : `${value}`; +} + +module.exports = { stringifyValueForError }; diff --git a/node_modules/eslint/messages/whitespace-found.js b/node_modules/eslint/messages/whitespace-found.js new file mode 100644 index 0000000..8a801bc --- /dev/null +++ b/node_modules/eslint/messages/whitespace-found.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = function(it) { + const { pluginName } = it; + + return ` +ESLint couldn't find the plugin "${pluginName}". because there is whitespace in the name. Please check your configuration and remove all whitespace from the plugin name. + +If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/node_modules/.bin/js-yaml b/node_modules/eslint/node_modules/.bin/js-yaml new file mode 120000 index 0000000..9dbd010 --- /dev/null +++ b/node_modules/eslint/node_modules/.bin/js-yaml @@ -0,0 +1 @@ +../js-yaml/bin/js-yaml.js \ No newline at end of file diff --git a/node_modules/eslint/node_modules/argparse/CHANGELOG.md b/node_modules/eslint/node_modules/argparse/CHANGELOG.md new file mode 100644 index 0000000..dc39ed6 --- /dev/null +++ b/node_modules/eslint/node_modules/argparse/CHANGELOG.md @@ -0,0 +1,216 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [2.0.1] - 2020-08-29 +### Fixed +- Fix issue with `process.argv` when used with interpreters (`coffee`, `ts-node`, etc.), #150. + + +## [2.0.0] - 2020-08-14 +### Changed +- Full rewrite. Now port from python 3.9.0 & more precise following. + See [doc](./doc) for difference and migration info. +- node.js 10+ required +- Removed most of local docs in favour of original ones. + + +## [1.0.10] - 2018-02-15 +### Fixed +- Use .concat instead of + for arrays, #122. + + +## [1.0.9] - 2016-09-29 +### Changed +- Rerelease after 1.0.8 - deps cleanup. + + +## [1.0.8] - 2016-09-29 +### Changed +- Maintenance (deps bump, fix node 6.5+ tests, coverage report). + + +## [1.0.7] - 2016-03-17 +### Changed +- Teach `addArgument` to accept string arg names. #97, @tomxtobin. + + +## [1.0.6] - 2016-02-06 +### Changed +- Maintenance: moved to eslint & updated CS. + + +## [1.0.5] - 2016-02-05 +### Changed +- Removed lodash dependency to significantly reduce install size. + Thanks to @mourner. + + +## [1.0.4] - 2016-01-17 +### Changed +- Maintenance: lodash update to 4.0.0. + + +## [1.0.3] - 2015-10-27 +### Fixed +- Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple. + + +## [1.0.2] - 2015-03-22 +### Changed +- Relaxed lodash version dependency. + + +## [1.0.1] - 2015-02-20 +### Changed +- Changed dependencies to be compatible with ancient nodejs. + + +## [1.0.0] - 2015-02-19 +### Changed +- Maintenance release. +- Replaced `underscore` with `lodash`. +- Bumped version to 1.0.0 to better reflect semver meaning. +- HISTORY.md -> CHANGELOG.md + + +## [0.1.16] - 2013-12-01 +### Changed +- Maintenance release. Updated dependencies and docs. + + +## [0.1.15] - 2013-05-13 +### Fixed +- Fixed #55, @trebor89 + + +## [0.1.14] - 2013-05-12 +### Fixed +- Fixed #62, @maxtaco + + +## [0.1.13] - 2013-04-08 +### Changed +- Added `.npmignore` to reduce package size + + +## [0.1.12] - 2013-02-10 +### Fixed +- Fixed conflictHandler (#46), @hpaulj + + +## [0.1.11] - 2013-02-07 +### Added +- Added 70+ tests (ported from python), @hpaulj +- Added conflictHandler, @applepicke +- Added fromfilePrefixChar, @hpaulj + +### Fixed +- Multiple bugfixes, @hpaulj + + +## [0.1.10] - 2012-12-30 +### Added +- Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) + support, thanks to @hpaulj + +### Fixed +- Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj + + +## [0.1.9] - 2012-12-27 +### Fixed +- Fixed option dest interferens with other options (issue #23), thanks to @hpaulj +- Fixed default value behavior with `*` positionals, thanks to @hpaulj +- Improve `getDefault()` behavior, thanks to @hpaulj +- Improve negative argument parsing, thanks to @hpaulj + + +## [0.1.8] - 2012-12-01 +### Fixed +- Fixed parser parents (issue #19), thanks to @hpaulj +- Fixed negative argument parse (issue #20), thanks to @hpaulj + + +## [0.1.7] - 2012-10-14 +### Fixed +- Fixed 'choices' argument parse (issue #16) +- Fixed stderr output (issue #15) + + +## [0.1.6] - 2012-09-09 +### Fixed +- Fixed check for conflict of options (thanks to @tomxtobin) + + +## [0.1.5] - 2012-09-03 +### Fixed +- Fix parser #setDefaults method (thanks to @tomxtobin) + + +## [0.1.4] - 2012-07-30 +### Fixed +- Fixed pseudo-argument support (thanks to @CGamesPlay) +- Fixed addHelp default (should be true), if not set (thanks to @benblank) + + +## [0.1.3] - 2012-06-27 +### Fixed +- Fixed formatter api name: Formatter -> HelpFormatter + + +## [0.1.2] - 2012-05-29 +### Fixed +- Removed excess whitespace in help +- Fixed error reporting, when parcer with subcommands + called with empty arguments + +### Added +- Added basic tests + + +## [0.1.1] - 2012-05-23 +### Fixed +- Fixed line wrapping in help formatter +- Added better error reporting on invalid arguments + + +## [0.1.0] - 2012-05-16 +### Added +- First release. + + +[2.0.1]: https://github.com/nodeca/argparse/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/nodeca/argparse/compare/1.0.10...2.0.0 +[1.0.10]: https://github.com/nodeca/argparse/compare/1.0.9...1.0.10 +[1.0.9]: https://github.com/nodeca/argparse/compare/1.0.8...1.0.9 +[1.0.8]: https://github.com/nodeca/argparse/compare/1.0.7...1.0.8 +[1.0.7]: https://github.com/nodeca/argparse/compare/1.0.6...1.0.7 +[1.0.6]: https://github.com/nodeca/argparse/compare/1.0.5...1.0.6 +[1.0.5]: https://github.com/nodeca/argparse/compare/1.0.4...1.0.5 +[1.0.4]: https://github.com/nodeca/argparse/compare/1.0.3...1.0.4 +[1.0.3]: https://github.com/nodeca/argparse/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/argparse/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/argparse/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/argparse/compare/0.1.16...1.0.0 +[0.1.16]: https://github.com/nodeca/argparse/compare/0.1.15...0.1.16 +[0.1.15]: https://github.com/nodeca/argparse/compare/0.1.14...0.1.15 +[0.1.14]: https://github.com/nodeca/argparse/compare/0.1.13...0.1.14 +[0.1.13]: https://github.com/nodeca/argparse/compare/0.1.12...0.1.13 +[0.1.12]: https://github.com/nodeca/argparse/compare/0.1.11...0.1.12 +[0.1.11]: https://github.com/nodeca/argparse/compare/0.1.10...0.1.11 +[0.1.10]: https://github.com/nodeca/argparse/compare/0.1.9...0.1.10 +[0.1.9]: https://github.com/nodeca/argparse/compare/0.1.8...0.1.9 +[0.1.8]: https://github.com/nodeca/argparse/compare/0.1.7...0.1.8 +[0.1.7]: https://github.com/nodeca/argparse/compare/0.1.6...0.1.7 +[0.1.6]: https://github.com/nodeca/argparse/compare/0.1.5...0.1.6 +[0.1.5]: https://github.com/nodeca/argparse/compare/0.1.4...0.1.5 +[0.1.4]: https://github.com/nodeca/argparse/compare/0.1.3...0.1.4 +[0.1.3]: https://github.com/nodeca/argparse/compare/0.1.2...0.1.3 +[0.1.2]: https://github.com/nodeca/argparse/compare/0.1.1...0.1.2 +[0.1.1]: https://github.com/nodeca/argparse/compare/0.1.0...0.1.1 +[0.1.0]: https://github.com/nodeca/argparse/releases/tag/0.1.0 diff --git a/node_modules/eslint/node_modules/argparse/LICENSE b/node_modules/eslint/node_modules/argparse/LICENSE new file mode 100644 index 0000000..66a3ac8 --- /dev/null +++ b/node_modules/eslint/node_modules/argparse/LICENSE @@ -0,0 +1,254 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see http://www.opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the Internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the Internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/eslint/node_modules/argparse/README.md b/node_modules/eslint/node_modules/argparse/README.md new file mode 100644 index 0000000..550b5c9 --- /dev/null +++ b/node_modules/eslint/node_modules/argparse/README.md @@ -0,0 +1,84 @@ +argparse +======== + +[![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) +[![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) + +CLI arguments parser for node.js, with [sub-commands](https://docs.python.org/3.9/library/argparse.html#sub-commands) support. Port of python's [argparse](http://docs.python.org/dev/library/argparse.html) (version [3.9.0](https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py)). + +**Difference with original.** + +- JS has no keyword arguments support. + - Pass options instead: `new ArgumentParser({ description: 'example', add_help: true })`. +- JS has no python's types `int`, `float`, ... + - Use string-typed names: `.add_argument('-b', { type: 'int', help: 'help' })`. +- `%r` format specifier uses `require('util').inspect()`. + +More details in [doc](./doc). + + +Example +------- + +`test.js` file: + +```javascript +#!/usr/bin/env node +'use strict'; + +const { ArgumentParser } = require('argparse'); +const { version } = require('./package.json'); + +const parser = new ArgumentParser({ + description: 'Argparse example' +}); + +parser.add_argument('-v', '--version', { action: 'version', version }); +parser.add_argument('-f', '--foo', { help: 'foo bar' }); +parser.add_argument('-b', '--bar', { help: 'bar foo' }); +parser.add_argument('--baz', { help: 'baz bar' }); + +console.dir(parser.parse_args()); +``` + +Display help: + +``` +$ ./test.js -h +usage: test.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] + +Argparse example + +optional arguments: + -h, --help show this help message and exit + -v, --version show program's version number and exit + -f FOO, --foo FOO foo bar + -b BAR, --bar BAR bar foo + --baz BAZ baz bar +``` + +Parse arguments: + +``` +$ ./test.js -f=3 --bar=4 --baz 5 +{ foo: '3', bar: '4', baz: '5' } +``` + + +API docs +-------- + +Since this is a port with minimal divergence, there's no separate documentation. +Use original one instead, with notes about difference. + +1. [Original doc](https://docs.python.org/3.9/library/argparse.html). +2. [Original tutorial](https://docs.python.org/3.9/howto/argparse.html). +3. [Difference with python](./doc). + + +argparse for enterprise +----------------------- + +Available as part of the Tidelift Subscription + +The maintainers of argparse and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-argparse?utm_source=npm-argparse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/eslint/node_modules/argparse/argparse.js b/node_modules/eslint/node_modules/argparse/argparse.js new file mode 100644 index 0000000..2b8c8c6 --- /dev/null +++ b/node_modules/eslint/node_modules/argparse/argparse.js @@ -0,0 +1,3707 @@ +// Port of python's argparse module, version 3.9.0: +// https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py + +'use strict' + +// Copyright (C) 2010-2020 Python Software Foundation. +// Copyright (C) 2020 argparse.js authors + +/* + * Command-line parsing library + * + * This module is an optparse-inspired command-line parsing library that: + * + * - handles both optional and positional arguments + * - produces highly informative usage messages + * - supports parsers that dispatch to sub-parsers + * + * The following is a simple usage example that sums integers from the + * command-line and writes the result to a file:: + * + * parser = argparse.ArgumentParser( + * description='sum the integers at the command line') + * parser.add_argument( + * 'integers', metavar='int', nargs='+', type=int, + * help='an integer to be summed') + * parser.add_argument( + * '--log', default=sys.stdout, type=argparse.FileType('w'), + * help='the file where the sum should be written') + * args = parser.parse_args() + * args.log.write('%s' % sum(args.integers)) + * args.log.close() + * + * The module contains the following public classes: + * + * - ArgumentParser -- The main entry point for command-line parsing. As the + * example above shows, the add_argument() method is used to populate + * the parser with actions for optional and positional arguments. Then + * the parse_args() method is invoked to convert the args at the + * command-line into an object with attributes. + * + * - ArgumentError -- The exception raised by ArgumentParser objects when + * there are errors with the parser's actions. Errors raised while + * parsing the command-line are caught by ArgumentParser and emitted + * as command-line messages. + * + * - FileType -- A factory for defining types of files to be created. As the + * example above shows, instances of FileType are typically passed as + * the type= argument of add_argument() calls. + * + * - Action -- The base class for parser actions. Typically actions are + * selected by passing strings like 'store_true' or 'append_const' to + * the action= argument of add_argument(). However, for greater + * customization of ArgumentParser actions, subclasses of Action may + * be defined and passed as the action= argument. + * + * - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, + * ArgumentDefaultsHelpFormatter -- Formatter classes which + * may be passed as the formatter_class= argument to the + * ArgumentParser constructor. HelpFormatter is the default, + * RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser + * not to change the formatting for help text, and + * ArgumentDefaultsHelpFormatter adds information about argument defaults + * to the help. + * + * All other classes in this module are considered implementation details. + * (Also note that HelpFormatter and RawDescriptionHelpFormatter are only + * considered public as object names -- the API of the formatter objects is + * still considered an implementation detail.) + */ + +const SUPPRESS = '==SUPPRESS==' + +const OPTIONAL = '?' +const ZERO_OR_MORE = '*' +const ONE_OR_MORE = '+' +const PARSER = 'A...' +const REMAINDER = '...' +const _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' + + +// ================================== +// Utility functions used for porting +// ================================== +const assert = require('assert') +const util = require('util') +const fs = require('fs') +const sub = require('./lib/sub') +const path = require('path') +const repr = util.inspect + +function get_argv() { + // omit first argument (which is assumed to be interpreter - `node`, `coffee`, `ts-node`, etc.) + return process.argv.slice(1) +} + +function get_terminal_size() { + return { + columns: +process.env.COLUMNS || process.stdout.columns || 80 + } +} + +function hasattr(object, name) { + return Object.prototype.hasOwnProperty.call(object, name) +} + +function getattr(object, name, value) { + return hasattr(object, name) ? object[name] : value +} + +function setattr(object, name, value) { + object[name] = value +} + +function setdefault(object, name, value) { + if (!hasattr(object, name)) object[name] = value + return object[name] +} + +function delattr(object, name) { + delete object[name] +} + +function range(from, to, step=1) { + // range(10) is equivalent to range(0, 10) + if (arguments.length === 1) [ to, from ] = [ from, 0 ] + if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') { + throw new TypeError('argument cannot be interpreted as an integer') + } + if (step === 0) throw new TypeError('range() arg 3 must not be zero') + + let result = [] + if (step > 0) { + for (let i = from; i < to; i += step) result.push(i) + } else { + for (let i = from; i > to; i += step) result.push(i) + } + return result +} + +function splitlines(str, keepends = false) { + let result + if (!keepends) { + result = str.split(/\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]/) + } else { + result = [] + let parts = str.split(/(\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029])/) + for (let i = 0; i < parts.length; i += 2) { + result.push(parts[i] + (i + 1 < parts.length ? parts[i + 1] : '')) + } + } + if (!result[result.length - 1]) result.pop() + return result +} + +function _string_lstrip(string, prefix_chars) { + let idx = 0 + while (idx < string.length && prefix_chars.includes(string[idx])) idx++ + return idx ? string.slice(idx) : string +} + +function _string_split(string, sep, maxsplit) { + let result = string.split(sep) + if (result.length > maxsplit) { + result = result.slice(0, maxsplit).concat([ result.slice(maxsplit).join(sep) ]) + } + return result +} + +function _array_equal(array1, array2) { + if (array1.length !== array2.length) return false + for (let i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) return false + } + return true +} + +function _array_remove(array, item) { + let idx = array.indexOf(item) + if (idx === -1) throw new TypeError(sub('%r not in list', item)) + array.splice(idx, 1) +} + +// normalize choices to array; +// this isn't required in python because `in` and `map` operators work with anything, +// but in js dealing with multiple types here is too clunky +function _choices_to_array(choices) { + if (choices === undefined) { + return [] + } else if (Array.isArray(choices)) { + return choices + } else if (choices !== null && typeof choices[Symbol.iterator] === 'function') { + return Array.from(choices) + } else if (typeof choices === 'object' && choices !== null) { + return Object.keys(choices) + } else { + throw new Error(sub('invalid choices value: %r', choices)) + } +} + +// decorator that allows a class to be called without new +function _callable(cls) { + let result = { // object is needed for inferred class name + [cls.name]: function (...args) { + let this_class = new.target === result || !new.target + return Reflect.construct(cls, args, this_class ? cls : new.target) + } + } + result[cls.name].prototype = cls.prototype + // fix default tag for toString, e.g. [object Action] instead of [object Object] + cls.prototype[Symbol.toStringTag] = cls.name + return result[cls.name] +} + +function _alias(object, from, to) { + try { + let name = object.constructor.name + Object.defineProperty(object, from, { + value: util.deprecate(object[to], sub('%s.%s() is renamed to %s.%s()', + name, from, name, to)), + enumerable: false + }) + } catch {} +} + +// decorator that allows snake_case class methods to be called with camelCase and vice versa +function _camelcase_alias(_class) { + for (let name of Object.getOwnPropertyNames(_class.prototype)) { + let camelcase = name.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) + if (camelcase !== name) _alias(_class.prototype, camelcase, name) + } + return _class +} + +function _to_legacy_name(key) { + key = key.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) + if (key === 'default') key = 'defaultValue' + if (key === 'const') key = 'constant' + return key +} + +function _to_new_name(key) { + if (key === 'defaultValue') key = 'default' + if (key === 'constant') key = 'const' + key = key.replace(/[A-Z]/g, c => '_' + c.toLowerCase()) + return key +} + +// parse options +let no_default = Symbol('no_default_value') +function _parse_opts(args, descriptor) { + function get_name() { + let stack = new Error().stack.split('\n') + .map(x => x.match(/^ at (.*) \(.*\)$/)) + .filter(Boolean) + .map(m => m[1]) + .map(fn => fn.match(/[^ .]*$/)[0]) + + if (stack.length && stack[0] === get_name.name) stack.shift() + if (stack.length && stack[0] === _parse_opts.name) stack.shift() + return stack.length ? stack[0] : '' + } + + args = Array.from(args) + let kwargs = {} + let result = [] + let last_opt = args.length && args[args.length - 1] + + if (typeof last_opt === 'object' && last_opt !== null && !Array.isArray(last_opt) && + (!last_opt.constructor || last_opt.constructor.name === 'Object')) { + kwargs = Object.assign({}, args.pop()) + } + + // LEGACY (v1 compatibility): camelcase + let renames = [] + for (let key of Object.keys(descriptor)) { + let old_name = _to_legacy_name(key) + if (old_name !== key && (old_name in kwargs)) { + if (key in kwargs) { + // default and defaultValue specified at the same time, happens often in old tests + //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) + } else { + kwargs[key] = kwargs[old_name] + } + renames.push([ old_name, key ]) + delete kwargs[old_name] + } + } + if (renames.length) { + let name = get_name() + deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', + name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) + } + // end + + let missing_positionals = [] + let positional_count = args.length + + for (let [ key, def ] of Object.entries(descriptor)) { + if (key[0] === '*') { + if (key.length > 0 && key[1] === '*') { + // LEGACY (v1 compatibility): camelcase + let renames = [] + for (let key of Object.keys(kwargs)) { + let new_name = _to_new_name(key) + if (new_name !== key && (key in kwargs)) { + if (new_name in kwargs) { + // default and defaultValue specified at the same time, happens often in old tests + //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), new_name)) + } else { + kwargs[new_name] = kwargs[key] + } + renames.push([ key, new_name ]) + delete kwargs[key] + } + } + if (renames.length) { + let name = get_name() + deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', + name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) + } + // end + result.push(kwargs) + kwargs = {} + } else { + result.push(args) + args = [] + } + } else if (key in kwargs && args.length > 0) { + throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) + } else if (key in kwargs) { + result.push(kwargs[key]) + delete kwargs[key] + } else if (args.length > 0) { + result.push(args.shift()) + } else if (def !== no_default) { + result.push(def) + } else { + missing_positionals.push(key) + } + } + + if (Object.keys(kwargs).length) { + throw new TypeError(sub('%s() got an unexpected keyword argument %r', + get_name(), Object.keys(kwargs)[0])) + } + + if (args.length) { + let from = Object.entries(descriptor).filter(([ k, v ]) => k[0] !== '*' && v !== no_default).length + let to = Object.entries(descriptor).filter(([ k ]) => k[0] !== '*').length + throw new TypeError(sub('%s() takes %s positional argument%s but %s %s given', + get_name(), + from === to ? sub('from %s to %s', from, to) : to, + from === to && to === 1 ? '' : 's', + positional_count, + positional_count === 1 ? 'was' : 'were')) + } + + if (missing_positionals.length) { + let strs = missing_positionals.map(repr) + if (strs.length > 1) strs[strs.length - 1] = 'and ' + strs[strs.length - 1] + let str_joined = strs.join(strs.length === 2 ? '' : ', ') + throw new TypeError(sub('%s() missing %i required positional argument%s: %s', + get_name(), strs.length, strs.length === 1 ? '' : 's', str_joined)) + } + + return result +} + +let _deprecations = {} +function deprecate(id, string) { + _deprecations[id] = _deprecations[id] || util.deprecate(() => {}, string) + _deprecations[id]() +} + + +// ============================= +// Utility functions and classes +// ============================= +function _AttributeHolder(cls = Object) { + /* + * Abstract base class that provides __repr__. + * + * The __repr__ method returns a string in the format:: + * ClassName(attr=name, attr=name, ...) + * The attributes are determined either by a class-level attribute, + * '_kwarg_names', or by inspecting the instance __dict__. + */ + + return class _AttributeHolder extends cls { + [util.inspect.custom]() { + let type_name = this.constructor.name + let arg_strings = [] + let star_args = {} + for (let arg of this._get_args()) { + arg_strings.push(repr(arg)) + } + for (let [ name, value ] of this._get_kwargs()) { + if (/^[a-z_][a-z0-9_$]*$/i.test(name)) { + arg_strings.push(sub('%s=%r', name, value)) + } else { + star_args[name] = value + } + } + if (Object.keys(star_args).length) { + arg_strings.push(sub('**%s', repr(star_args))) + } + return sub('%s(%s)', type_name, arg_strings.join(', ')) + } + + toString() { + return this[util.inspect.custom]() + } + + _get_kwargs() { + return Object.entries(this) + } + + _get_args() { + return [] + } + } +} + + +function _copy_items(items) { + if (items === undefined) { + return [] + } + return items.slice(0) +} + + +// =============== +// Formatting Help +// =============== +const HelpFormatter = _camelcase_alias(_callable(class HelpFormatter { + /* + * Formatter for generating usage messages and argument help strings. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + constructor() { + let [ + prog, + indent_increment, + max_help_position, + width + ] = _parse_opts(arguments, { + prog: no_default, + indent_increment: 2, + max_help_position: 24, + width: undefined + }) + + // default setting for width + if (width === undefined) { + width = get_terminal_size().columns + width -= 2 + } + + this._prog = prog + this._indent_increment = indent_increment + this._max_help_position = Math.min(max_help_position, + Math.max(width - 20, indent_increment * 2)) + this._width = width + + this._current_indent = 0 + this._level = 0 + this._action_max_length = 0 + + this._root_section = this._Section(this, undefined) + this._current_section = this._root_section + + this._whitespace_matcher = /[ \t\n\r\f\v]+/g // equivalent to python /\s+/ with ASCII flag + this._long_break_matcher = /\n\n\n+/g + } + + // =============================== + // Section and indentation methods + // =============================== + _indent() { + this._current_indent += this._indent_increment + this._level += 1 + } + + _dedent() { + this._current_indent -= this._indent_increment + assert(this._current_indent >= 0, 'Indent decreased below 0.') + this._level -= 1 + } + + _add_item(func, args) { + this._current_section.items.push([ func, args ]) + } + + // ======================== + // Message building methods + // ======================== + start_section(heading) { + this._indent() + let section = this._Section(this, this._current_section, heading) + this._add_item(section.format_help.bind(section), []) + this._current_section = section + } + + end_section() { + this._current_section = this._current_section.parent + this._dedent() + } + + add_text(text) { + if (text !== SUPPRESS && text !== undefined) { + this._add_item(this._format_text.bind(this), [text]) + } + } + + add_usage(usage, actions, groups, prefix = undefined) { + if (usage !== SUPPRESS) { + let args = [ usage, actions, groups, prefix ] + this._add_item(this._format_usage.bind(this), args) + } + } + + add_argument(action) { + if (action.help !== SUPPRESS) { + + // find all invocations + let invocations = [this._format_action_invocation(action)] + for (let subaction of this._iter_indented_subactions(action)) { + invocations.push(this._format_action_invocation(subaction)) + } + + // update the maximum item length + let invocation_length = Math.max(...invocations.map(invocation => invocation.length)) + let action_length = invocation_length + this._current_indent + this._action_max_length = Math.max(this._action_max_length, + action_length) + + // add the item to the list + this._add_item(this._format_action.bind(this), [action]) + } + } + + add_arguments(actions) { + for (let action of actions) { + this.add_argument(action) + } + } + + // ======================= + // Help-formatting methods + // ======================= + format_help() { + let help = this._root_section.format_help() + if (help) { + help = help.replace(this._long_break_matcher, '\n\n') + help = help.replace(/^\n+|\n+$/g, '') + '\n' + } + return help + } + + _join_parts(part_strings) { + return part_strings.filter(part => part && part !== SUPPRESS).join('') + } + + _format_usage(usage, actions, groups, prefix) { + if (prefix === undefined) { + prefix = 'usage: ' + } + + // if usage is specified, use that + if (usage !== undefined) { + usage = sub(usage, { prog: this._prog }) + + // if no optionals or positionals are available, usage is just prog + } else if (usage === undefined && !actions.length) { + usage = sub('%(prog)s', { prog: this._prog }) + + // if optionals and positionals are available, calculate usage + } else if (usage === undefined) { + let prog = sub('%(prog)s', { prog: this._prog }) + + // split optionals from positionals + let optionals = [] + let positionals = [] + for (let action of actions) { + if (action.option_strings.length) { + optionals.push(action) + } else { + positionals.push(action) + } + } + + // build full usage string + let action_usage = this._format_actions_usage([].concat(optionals).concat(positionals), groups) + usage = [ prog, action_usage ].map(String).join(' ') + + // wrap the usage parts if it's too long + let text_width = this._width - this._current_indent + if (prefix.length + usage.length > text_width) { + + // break usage into wrappable parts + let part_regexp = /\(.*?\)+(?=\s|$)|\[.*?\]+(?=\s|$)|\S+/g + let opt_usage = this._format_actions_usage(optionals, groups) + let pos_usage = this._format_actions_usage(positionals, groups) + let opt_parts = opt_usage.match(part_regexp) || [] + let pos_parts = pos_usage.match(part_regexp) || [] + assert(opt_parts.join(' ') === opt_usage) + assert(pos_parts.join(' ') === pos_usage) + + // helper for wrapping lines + let get_lines = (parts, indent, prefix = undefined) => { + let lines = [] + let line = [] + let line_len + if (prefix !== undefined) { + line_len = prefix.length - 1 + } else { + line_len = indent.length - 1 + } + for (let part of parts) { + if (line_len + 1 + part.length > text_width && line) { + lines.push(indent + line.join(' ')) + line = [] + line_len = indent.length - 1 + } + line.push(part) + line_len += part.length + 1 + } + if (line.length) { + lines.push(indent + line.join(' ')) + } + if (prefix !== undefined) { + lines[0] = lines[0].slice(indent.length) + } + return lines + } + + let lines + + // if prog is short, follow it with optionals or positionals + if (prefix.length + prog.length <= 0.75 * text_width) { + let indent = ' '.repeat(prefix.length + prog.length + 1) + if (opt_parts.length) { + lines = get_lines([prog].concat(opt_parts), indent, prefix) + lines = lines.concat(get_lines(pos_parts, indent)) + } else if (pos_parts.length) { + lines = get_lines([prog].concat(pos_parts), indent, prefix) + } else { + lines = [prog] + } + + // if prog is long, put it on its own line + } else { + let indent = ' '.repeat(prefix.length) + let parts = [].concat(opt_parts).concat(pos_parts) + lines = get_lines(parts, indent) + if (lines.length > 1) { + lines = [] + lines = lines.concat(get_lines(opt_parts, indent)) + lines = lines.concat(get_lines(pos_parts, indent)) + } + lines = [prog].concat(lines) + } + + // join lines into usage + usage = lines.join('\n') + } + } + + // prefix with 'usage:' + return sub('%s%s\n\n', prefix, usage) + } + + _format_actions_usage(actions, groups) { + // find group indices and identify actions in groups + let group_actions = new Set() + let inserts = {} + for (let group of groups) { + let start = actions.indexOf(group._group_actions[0]) + if (start === -1) { + continue + } else { + let end = start + group._group_actions.length + if (_array_equal(actions.slice(start, end), group._group_actions)) { + for (let action of group._group_actions) { + group_actions.add(action) + } + if (!group.required) { + if (start in inserts) { + inserts[start] += ' [' + } else { + inserts[start] = '[' + } + if (end in inserts) { + inserts[end] += ']' + } else { + inserts[end] = ']' + } + } else { + if (start in inserts) { + inserts[start] += ' (' + } else { + inserts[start] = '(' + } + if (end in inserts) { + inserts[end] += ')' + } else { + inserts[end] = ')' + } + } + for (let i of range(start + 1, end)) { + inserts[i] = '|' + } + } + } + } + + // collect all actions format strings + let parts = [] + for (let [ i, action ] of Object.entries(actions)) { + + // suppressed arguments are marked with None + // remove | separators for suppressed arguments + if (action.help === SUPPRESS) { + parts.push(undefined) + if (inserts[+i] === '|') { + delete inserts[+i] + } else if (inserts[+i + 1] === '|') { + delete inserts[+i + 1] + } + + // produce all arg strings + } else if (!action.option_strings.length) { + let default_value = this._get_default_metavar_for_positional(action) + let part = this._format_args(action, default_value) + + // if it's in a group, strip the outer [] + if (group_actions.has(action)) { + if (part[0] === '[' && part[part.length - 1] === ']') { + part = part.slice(1, -1) + } + } + + // add the action string to the list + parts.push(part) + + // produce the first way to invoke the option in brackets + } else { + let option_string = action.option_strings[0] + let part + + // if the Optional doesn't take a value, format is: + // -s or --long + if (action.nargs === 0) { + part = action.format_usage() + + // if the Optional takes a value, format is: + // -s ARGS or --long ARGS + } else { + let default_value = this._get_default_metavar_for_optional(action) + let args_string = this._format_args(action, default_value) + part = sub('%s %s', option_string, args_string) + } + + // make it look optional if it's not required or in a group + if (!action.required && !group_actions.has(action)) { + part = sub('[%s]', part) + } + + // add the action string to the list + parts.push(part) + } + } + + // insert things at the necessary indices + for (let i of Object.keys(inserts).map(Number).sort((a, b) => b - a)) { + parts.splice(+i, 0, inserts[+i]) + } + + // join all the action items with spaces + let text = parts.filter(Boolean).join(' ') + + // clean up separators for mutually exclusive groups + text = text.replace(/([\[(]) /g, '$1') + text = text.replace(/ ([\])])/g, '$1') + text = text.replace(/[\[(] *[\])]/g, '') + text = text.replace(/\(([^|]*)\)/g, '$1', text) + text = text.trim() + + // return the text + return text + } + + _format_text(text) { + if (text.includes('%(prog)')) { + text = sub(text, { prog: this._prog }) + } + let text_width = Math.max(this._width - this._current_indent, 11) + let indent = ' '.repeat(this._current_indent) + return this._fill_text(text, text_width, indent) + '\n\n' + } + + _format_action(action) { + // determine the required width and the entry label + let help_position = Math.min(this._action_max_length + 2, + this._max_help_position) + let help_width = Math.max(this._width - help_position, 11) + let action_width = help_position - this._current_indent - 2 + let action_header = this._format_action_invocation(action) + let indent_first + + // no help; start on same line and add a final newline + if (!action.help) { + let tup = [ this._current_indent, '', action_header ] + action_header = sub('%*s%s\n', ...tup) + + // short action name; start on the same line and pad two spaces + } else if (action_header.length <= action_width) { + let tup = [ this._current_indent, '', action_width, action_header ] + action_header = sub('%*s%-*s ', ...tup) + indent_first = 0 + + // long action name; start on the next line + } else { + let tup = [ this._current_indent, '', action_header ] + action_header = sub('%*s%s\n', ...tup) + indent_first = help_position + } + + // collect the pieces of the action help + let parts = [action_header] + + // if there was help for the action, add lines of help text + if (action.help) { + let help_text = this._expand_help(action) + let help_lines = this._split_lines(help_text, help_width) + parts.push(sub('%*s%s\n', indent_first, '', help_lines[0])) + for (let line of help_lines.slice(1)) { + parts.push(sub('%*s%s\n', help_position, '', line)) + } + + // or add a newline if the description doesn't end with one + } else if (!action_header.endsWith('\n')) { + parts.push('\n') + } + + // if there are any sub-actions, add their help as well + for (let subaction of this._iter_indented_subactions(action)) { + parts.push(this._format_action(subaction)) + } + + // return a single string + return this._join_parts(parts) + } + + _format_action_invocation(action) { + if (!action.option_strings.length) { + let default_value = this._get_default_metavar_for_positional(action) + let metavar = this._metavar_formatter(action, default_value)(1)[0] + return metavar + + } else { + let parts = [] + + // if the Optional doesn't take a value, format is: + // -s, --long + if (action.nargs === 0) { + parts = parts.concat(action.option_strings) + + // if the Optional takes a value, format is: + // -s ARGS, --long ARGS + } else { + let default_value = this._get_default_metavar_for_optional(action) + let args_string = this._format_args(action, default_value) + for (let option_string of action.option_strings) { + parts.push(sub('%s %s', option_string, args_string)) + } + } + + return parts.join(', ') + } + } + + _metavar_formatter(action, default_metavar) { + let result + if (action.metavar !== undefined) { + result = action.metavar + } else if (action.choices !== undefined) { + let choice_strs = _choices_to_array(action.choices).map(String) + result = sub('{%s}', choice_strs.join(',')) + } else { + result = default_metavar + } + + function format(tuple_size) { + if (Array.isArray(result)) { + return result + } else { + return Array(tuple_size).fill(result) + } + } + return format + } + + _format_args(action, default_metavar) { + let get_metavar = this._metavar_formatter(action, default_metavar) + let result + if (action.nargs === undefined) { + result = sub('%s', ...get_metavar(1)) + } else if (action.nargs === OPTIONAL) { + result = sub('[%s]', ...get_metavar(1)) + } else if (action.nargs === ZERO_OR_MORE) { + let metavar = get_metavar(1) + if (metavar.length === 2) { + result = sub('[%s [%s ...]]', ...metavar) + } else { + result = sub('[%s ...]', ...metavar) + } + } else if (action.nargs === ONE_OR_MORE) { + result = sub('%s [%s ...]', ...get_metavar(2)) + } else if (action.nargs === REMAINDER) { + result = '...' + } else if (action.nargs === PARSER) { + result = sub('%s ...', ...get_metavar(1)) + } else if (action.nargs === SUPPRESS) { + result = '' + } else { + let formats + try { + formats = range(action.nargs).map(() => '%s') + } catch (err) { + throw new TypeError('invalid nargs value') + } + result = sub(formats.join(' '), ...get_metavar(action.nargs)) + } + return result + } + + _expand_help(action) { + let params = Object.assign({ prog: this._prog }, action) + for (let name of Object.keys(params)) { + if (params[name] === SUPPRESS) { + delete params[name] + } + } + for (let name of Object.keys(params)) { + if (params[name] && params[name].name) { + params[name] = params[name].name + } + } + if (params.choices !== undefined) { + let choices_str = _choices_to_array(params.choices).map(String).join(', ') + params.choices = choices_str + } + // LEGACY (v1 compatibility): camelcase + for (let key of Object.keys(params)) { + let old_name = _to_legacy_name(key) + if (old_name !== key) { + params[old_name] = params[key] + } + } + // end + return sub(this._get_help_string(action), params) + } + + * _iter_indented_subactions(action) { + if (typeof action._get_subactions === 'function') { + this._indent() + yield* action._get_subactions() + this._dedent() + } + } + + _split_lines(text, width) { + text = text.replace(this._whitespace_matcher, ' ').trim() + // The textwrap module is used only for formatting help. + // Delay its import for speeding up the common usage of argparse. + let textwrap = require('./lib/textwrap') + return textwrap.wrap(text, { width }) + } + + _fill_text(text, width, indent) { + text = text.replace(this._whitespace_matcher, ' ').trim() + let textwrap = require('./lib/textwrap') + return textwrap.fill(text, { width, + initial_indent: indent, + subsequent_indent: indent }) + } + + _get_help_string(action) { + return action.help + } + + _get_default_metavar_for_optional(action) { + return action.dest.toUpperCase() + } + + _get_default_metavar_for_positional(action) { + return action.dest + } +})) + +HelpFormatter.prototype._Section = _callable(class _Section { + + constructor(formatter, parent, heading = undefined) { + this.formatter = formatter + this.parent = parent + this.heading = heading + this.items = [] + } + + format_help() { + // format the indented section + if (this.parent !== undefined) { + this.formatter._indent() + } + let item_help = this.formatter._join_parts(this.items.map(([ func, args ]) => func.apply(null, args))) + if (this.parent !== undefined) { + this.formatter._dedent() + } + + // return nothing if the section was empty + if (!item_help) { + return '' + } + + // add the heading if the section was non-empty + let heading + if (this.heading !== SUPPRESS && this.heading !== undefined) { + let current_indent = this.formatter._current_indent + heading = sub('%*s%s:\n', current_indent, '', this.heading) + } else { + heading = '' + } + + // join the section-initial newline, the heading and the help + return this.formatter._join_parts(['\n', heading, item_help, '\n']) + } +}) + + +const RawDescriptionHelpFormatter = _camelcase_alias(_callable(class RawDescriptionHelpFormatter extends HelpFormatter { + /* + * Help message formatter which retains any formatting in descriptions. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _fill_text(text, width, indent) { + return splitlines(text, true).map(line => indent + line).join('') + } +})) + + +const RawTextHelpFormatter = _camelcase_alias(_callable(class RawTextHelpFormatter extends RawDescriptionHelpFormatter { + /* + * Help message formatter which retains formatting of all help text. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _split_lines(text/*, width*/) { + return splitlines(text) + } +})) + + +const ArgumentDefaultsHelpFormatter = _camelcase_alias(_callable(class ArgumentDefaultsHelpFormatter extends HelpFormatter { + /* + * Help message formatter which adds default values to argument help. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _get_help_string(action) { + let help = action.help + // LEGACY (v1 compatibility): additional check for defaultValue needed + if (!action.help.includes('%(default)') && !action.help.includes('%(defaultValue)')) { + if (action.default !== SUPPRESS) { + let defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] + if (action.option_strings.length || defaulting_nargs.includes(action.nargs)) { + help += ' (default: %(default)s)' + } + } + } + return help + } +})) + + +const MetavarTypeHelpFormatter = _camelcase_alias(_callable(class MetavarTypeHelpFormatter extends HelpFormatter { + /* + * Help message formatter which uses the argument 'type' as the default + * metavar value (instead of the argument 'dest') + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _get_default_metavar_for_optional(action) { + return typeof action.type === 'function' ? action.type.name : action.type + } + + _get_default_metavar_for_positional(action) { + return typeof action.type === 'function' ? action.type.name : action.type + } +})) + + +// ===================== +// Options and Arguments +// ===================== +function _get_action_name(argument) { + if (argument === undefined) { + return undefined + } else if (argument.option_strings.length) { + return argument.option_strings.join('/') + } else if (![ undefined, SUPPRESS ].includes(argument.metavar)) { + return argument.metavar + } else if (![ undefined, SUPPRESS ].includes(argument.dest)) { + return argument.dest + } else { + return undefined + } +} + + +const ArgumentError = _callable(class ArgumentError extends Error { + /* + * An error from creating or using an argument (optional or positional). + * + * The string value of this exception is the message, augmented with + * information about the argument that caused it. + */ + + constructor(argument, message) { + super() + this.name = 'ArgumentError' + this._argument_name = _get_action_name(argument) + this._message = message + this.message = this.str() + } + + str() { + let format + if (this._argument_name === undefined) { + format = '%(message)s' + } else { + format = 'argument %(argument_name)s: %(message)s' + } + return sub(format, { message: this._message, + argument_name: this._argument_name }) + } +}) + + +const ArgumentTypeError = _callable(class ArgumentTypeError extends Error { + /* + * An error from trying to convert a command line string to a type. + */ + + constructor(message) { + super(message) + this.name = 'ArgumentTypeError' + } +}) + + +// ============== +// Action classes +// ============== +const Action = _camelcase_alias(_callable(class Action extends _AttributeHolder(Function) { + /* + * Information about how to convert command line strings to Python objects. + * + * Action objects are used by an ArgumentParser to represent the information + * needed to parse a single argument from one or more strings from the + * command line. The keyword arguments to the Action constructor are also + * all attributes of Action instances. + * + * Keyword Arguments: + * + * - option_strings -- A list of command-line option strings which + * should be associated with this action. + * + * - dest -- The name of the attribute to hold the created object(s) + * + * - nargs -- The number of command-line arguments that should be + * consumed. By default, one argument will be consumed and a single + * value will be produced. Other values include: + * - N (an integer) consumes N arguments (and produces a list) + * - '?' consumes zero or one arguments + * - '*' consumes zero or more arguments (and produces a list) + * - '+' consumes one or more arguments (and produces a list) + * Note that the difference between the default and nargs=1 is that + * with the default, a single value will be produced, while with + * nargs=1, a list containing a single value will be produced. + * + * - const -- The value to be produced if the option is specified and the + * option uses an action that takes no values. + * + * - default -- The value to be produced if the option is not specified. + * + * - type -- A callable that accepts a single string argument, and + * returns the converted value. The standard Python types str, int, + * float, and complex are useful examples of such callables. If None, + * str is used. + * + * - choices -- A container of values that should be allowed. If not None, + * after a command-line argument has been converted to the appropriate + * type, an exception will be raised if it is not a member of this + * collection. + * + * - required -- True if the action must always be specified at the + * command line. This is only meaningful for optional command-line + * arguments. + * + * - help -- The help string describing the argument. + * + * - metavar -- The name to be used for the option's argument with the + * help string. If None, the 'dest' value will be used as the name. + */ + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + // when this class is called as a function, redirect it to .call() method of itself + super('return arguments.callee.call.apply(arguments.callee, arguments)') + + this.option_strings = option_strings + this.dest = dest + this.nargs = nargs + this.const = const_value + this.default = default_value + this.type = type + this.choices = choices + this.required = required + this.help = help + this.metavar = metavar + } + + _get_kwargs() { + let names = [ + 'option_strings', + 'dest', + 'nargs', + 'const', + 'default', + 'type', + 'choices', + 'help', + 'metavar' + ] + return names.map(name => [ name, getattr(this, name) ]) + } + + format_usage() { + return this.option_strings[0] + } + + call(/*parser, namespace, values, option_string = undefined*/) { + throw new Error('.call() not defined') + } +})) + + +const BooleanOptionalAction = _camelcase_alias(_callable(class BooleanOptionalAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + let _option_strings = [] + for (let option_string of option_strings) { + _option_strings.push(option_string) + + if (option_string.startsWith('--')) { + option_string = '--no-' + option_string.slice(2) + _option_strings.push(option_string) + } + } + + if (help !== undefined && default_value !== undefined) { + help += ` (default: ${default_value})` + } + + super({ + option_strings: _option_strings, + dest, + nargs: 0, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values, option_string = undefined) { + if (this.option_strings.includes(option_string)) { + setattr(namespace, this.dest, !option_string.startsWith('--no-')) + } + } + + format_usage() { + return this.option_strings.join(' | ') + } +})) + + +const _StoreAction = _callable(class _StoreAction extends Action { + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + if (nargs === 0) { + throw new TypeError('nargs for store actions must be != 0; if you ' + + 'have nothing to store, actions such as store ' + + 'true or store const may be more appropriate') + } + if (const_value !== undefined && nargs !== OPTIONAL) { + throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) + } + super({ + option_strings, + dest, + nargs, + const: const_value, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values/*, option_string = undefined*/) { + setattr(namespace, this.dest, values) + } +}) + + +const _StoreConstAction = _callable(class _StoreConstAction extends Action { + + constructor() { + let [ + option_strings, + dest, + const_value, + default_value, + required, + help + //, metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + const: no_default, + default: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + const: const_value, + default: default_value, + required, + help + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + setattr(namespace, this.dest, this.const) + } +}) + + +const _StoreTrueAction = _callable(class _StoreTrueAction extends _StoreConstAction { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: false, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + const: true, + default: default_value, + required, + help + }) + } +}) + + +const _StoreFalseAction = _callable(class _StoreFalseAction extends _StoreConstAction { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: true, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + const: false, + default: default_value, + required, + help + }) + } +}) + + +const _AppendAction = _callable(class _AppendAction extends Action { + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + if (nargs === 0) { + throw new TypeError('nargs for append actions must be != 0; if arg ' + + 'strings are not supplying the value to append, ' + + 'the append const action may be more appropriate') + } + if (const_value !== undefined && nargs !== OPTIONAL) { + throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) + } + super({ + option_strings, + dest, + nargs, + const: const_value, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values/*, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items.push(values) + setattr(namespace, this.dest, items) + } +}) + + +const _AppendConstAction = _callable(class _AppendConstAction extends Action { + + constructor() { + let [ + option_strings, + dest, + const_value, + default_value, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + const: no_default, + default: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + const: const_value, + default: default_value, + required, + help, + metavar + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items.push(this.const) + setattr(namespace, this.dest, items) + } +}) + + +const _CountAction = _callable(class _CountAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: undefined, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + default: default_value, + required, + help + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + let count = getattr(namespace, this.dest, undefined) + if (count === undefined) { + count = 0 + } + setattr(namespace, this.dest, count + 1) + } +}) + + +const _HelpAction = _callable(class _HelpAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: SUPPRESS, + default: SUPPRESS, + help: undefined + }) + + super({ + option_strings, + dest, + default: default_value, + nargs: 0, + help + }) + } + + call(parser/*, namespace, values, option_string = undefined*/) { + parser.print_help() + parser.exit() + } +}) + + +const _VersionAction = _callable(class _VersionAction extends Action { + + constructor() { + let [ + option_strings, + version, + dest, + default_value, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + version: undefined, + dest: SUPPRESS, + default: SUPPRESS, + help: "show program's version number and exit" + }) + + super({ + option_strings, + dest, + default: default_value, + nargs: 0, + help + }) + this.version = version + } + + call(parser/*, namespace, values, option_string = undefined*/) { + let version = this.version + if (version === undefined) { + version = parser.version + } + let formatter = parser._get_formatter() + formatter.add_text(version) + parser._print_message(formatter.format_help(), process.stdout) + parser.exit() + } +}) + + +const _SubParsersAction = _camelcase_alias(_callable(class _SubParsersAction extends Action { + + constructor() { + let [ + option_strings, + prog, + parser_class, + dest, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + prog: no_default, + parser_class: no_default, + dest: SUPPRESS, + required: false, + help: undefined, + metavar: undefined + }) + + let name_parser_map = {} + + super({ + option_strings, + dest, + nargs: PARSER, + choices: name_parser_map, + required, + help, + metavar + }) + + this._prog_prefix = prog + this._parser_class = parser_class + this._name_parser_map = name_parser_map + this._choices_actions = [] + } + + add_parser() { + let [ + name, + kwargs + ] = _parse_opts(arguments, { + name: no_default, + '**kwargs': no_default + }) + + // set prog from the existing prefix + if (kwargs.prog === undefined) { + kwargs.prog = sub('%s %s', this._prog_prefix, name) + } + + let aliases = getattr(kwargs, 'aliases', []) + delete kwargs.aliases + + // create a pseudo-action to hold the choice help + if ('help' in kwargs) { + let help = kwargs.help + delete kwargs.help + let choice_action = this._ChoicesPseudoAction(name, aliases, help) + this._choices_actions.push(choice_action) + } + + // create the parser and add it to the map + let parser = new this._parser_class(kwargs) + this._name_parser_map[name] = parser + + // make parser available under aliases also + for (let alias of aliases) { + this._name_parser_map[alias] = parser + } + + return parser + } + + _get_subactions() { + return this._choices_actions + } + + call(parser, namespace, values/*, option_string = undefined*/) { + let parser_name = values[0] + let arg_strings = values.slice(1) + + // set the parser name if requested + if (this.dest !== SUPPRESS) { + setattr(namespace, this.dest, parser_name) + } + + // select the parser + if (hasattr(this._name_parser_map, parser_name)) { + parser = this._name_parser_map[parser_name] + } else { + let args = {parser_name, + choices: this._name_parser_map.join(', ')} + let msg = sub('unknown parser %(parser_name)r (choices: %(choices)s)', args) + throw new ArgumentError(this, msg) + } + + // parse all the remaining options into the namespace + // store any unrecognized options on the object, so that the top + // level parser can decide what to do with them + + // In case this subparser defines new defaults, we parse them + // in a new namespace object and then update the original + // namespace for the relevant parts. + let subnamespace + [ subnamespace, arg_strings ] = parser.parse_known_args(arg_strings, undefined) + for (let [ key, value ] of Object.entries(subnamespace)) { + setattr(namespace, key, value) + } + + if (arg_strings.length) { + setdefault(namespace, _UNRECOGNIZED_ARGS_ATTR, []) + getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).push(...arg_strings) + } + } +})) + + +_SubParsersAction.prototype._ChoicesPseudoAction = _callable(class _ChoicesPseudoAction extends Action { + constructor(name, aliases, help) { + let metavar = name, dest = name + if (aliases.length) { + metavar += sub(' (%s)', aliases.join(', ')) + } + super({ option_strings: [], dest, help, metavar }) + } +}) + + +const _ExtendAction = _callable(class _ExtendAction extends _AppendAction { + call(parser, namespace, values/*, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items = items.concat(values) + setattr(namespace, this.dest, items) + } +}) + + +// ============== +// Type classes +// ============== +const FileType = _callable(class FileType extends Function { + /* + * Factory for creating file object types + * + * Instances of FileType are typically passed as type= arguments to the + * ArgumentParser add_argument() method. + * + * Keyword Arguments: + * - mode -- A string indicating how the file is to be opened. Accepts the + * same values as the builtin open() function. + * - bufsize -- The file's desired buffer size. Accepts the same values as + * the builtin open() function. + * - encoding -- The file's encoding. Accepts the same values as the + * builtin open() function. + * - errors -- A string indicating how encoding and decoding errors are to + * be handled. Accepts the same value as the builtin open() function. + */ + + constructor() { + let [ + flags, + encoding, + mode, + autoClose, + emitClose, + start, + end, + highWaterMark, + fs + ] = _parse_opts(arguments, { + flags: 'r', + encoding: undefined, + mode: undefined, // 0o666 + autoClose: undefined, // true + emitClose: undefined, // false + start: undefined, // 0 + end: undefined, // Infinity + highWaterMark: undefined, // 64 * 1024 + fs: undefined + }) + + // when this class is called as a function, redirect it to .call() method of itself + super('return arguments.callee.call.apply(arguments.callee, arguments)') + + Object.defineProperty(this, 'name', { + get() { + return sub('FileType(%r)', flags) + } + }) + this._flags = flags + this._options = {} + if (encoding !== undefined) this._options.encoding = encoding + if (mode !== undefined) this._options.mode = mode + if (autoClose !== undefined) this._options.autoClose = autoClose + if (emitClose !== undefined) this._options.emitClose = emitClose + if (start !== undefined) this._options.start = start + if (end !== undefined) this._options.end = end + if (highWaterMark !== undefined) this._options.highWaterMark = highWaterMark + if (fs !== undefined) this._options.fs = fs + } + + call(string) { + // the special argument "-" means sys.std{in,out} + if (string === '-') { + if (this._flags.includes('r')) { + return process.stdin + } else if (this._flags.includes('w')) { + return process.stdout + } else { + let msg = sub('argument "-" with mode %r', this._flags) + throw new TypeError(msg) + } + } + + // all other arguments are used as file names + let fd + try { + fd = fs.openSync(string, this._flags, this._options.mode) + } catch (e) { + let args = { filename: string, error: e.message } + let message = "can't open '%(filename)s': %(error)s" + throw new ArgumentTypeError(sub(message, args)) + } + + let options = Object.assign({ fd, flags: this._flags }, this._options) + if (this._flags.includes('r')) { + return fs.createReadStream(undefined, options) + } else if (this._flags.includes('w')) { + return fs.createWriteStream(undefined, options) + } else { + let msg = sub('argument "%s" with mode %r', string, this._flags) + throw new TypeError(msg) + } + } + + [util.inspect.custom]() { + let args = [ this._flags ] + let kwargs = Object.entries(this._options).map(([ k, v ]) => { + if (k === 'mode') v = { value: v, [util.inspect.custom]() { return '0o' + this.value.toString(8) } } + return [ k, v ] + }) + let args_str = [] + .concat(args.filter(arg => arg !== -1).map(repr)) + .concat(kwargs.filter(([/*kw*/, arg]) => arg !== undefined) + .map(([kw, arg]) => sub('%s=%r', kw, arg))) + .join(', ') + return sub('%s(%s)', this.constructor.name, args_str) + } + + toString() { + return this[util.inspect.custom]() + } +}) + +// =========================== +// Optional and Positional Parsing +// =========================== +const Namespace = _callable(class Namespace extends _AttributeHolder() { + /* + * Simple object for storing attributes. + * + * Implements equality by attribute names and values, and provides a simple + * string representation. + */ + + constructor(options = {}) { + super() + Object.assign(this, options) + } +}) + +// unset string tag to mimic plain object +Namespace.prototype[Symbol.toStringTag] = undefined + + +const _ActionsContainer = _camelcase_alias(_callable(class _ActionsContainer { + + constructor() { + let [ + description, + prefix_chars, + argument_default, + conflict_handler + ] = _parse_opts(arguments, { + description: no_default, + prefix_chars: no_default, + argument_default: no_default, + conflict_handler: no_default + }) + + this.description = description + this.argument_default = argument_default + this.prefix_chars = prefix_chars + this.conflict_handler = conflict_handler + + // set up registries + this._registries = {} + + // register actions + this.register('action', undefined, _StoreAction) + this.register('action', 'store', _StoreAction) + this.register('action', 'store_const', _StoreConstAction) + this.register('action', 'store_true', _StoreTrueAction) + this.register('action', 'store_false', _StoreFalseAction) + this.register('action', 'append', _AppendAction) + this.register('action', 'append_const', _AppendConstAction) + this.register('action', 'count', _CountAction) + this.register('action', 'help', _HelpAction) + this.register('action', 'version', _VersionAction) + this.register('action', 'parsers', _SubParsersAction) + this.register('action', 'extend', _ExtendAction) + // LEGACY (v1 compatibility): camelcase variants + ;[ 'storeConst', 'storeTrue', 'storeFalse', 'appendConst' ].forEach(old_name => { + let new_name = _to_new_name(old_name) + this.register('action', old_name, util.deprecate(this._registry_get('action', new_name), + sub('{action: "%s"} is renamed to {action: "%s"}', old_name, new_name))) + }) + // end + + // raise an exception if the conflict handler is invalid + this._get_handler() + + // action storage + this._actions = [] + this._option_string_actions = {} + + // groups + this._action_groups = [] + this._mutually_exclusive_groups = [] + + // defaults storage + this._defaults = {} + + // determines whether an "option" looks like a negative number + this._negative_number_matcher = /^-\d+$|^-\d*\.\d+$/ + + // whether or not there are any optionals that look like negative + // numbers -- uses a list so it can be shared and edited + this._has_negative_number_optionals = [] + } + + // ==================== + // Registration methods + // ==================== + register(registry_name, value, object) { + let registry = setdefault(this._registries, registry_name, {}) + registry[value] = object + } + + _registry_get(registry_name, value, default_value = undefined) { + return getattr(this._registries[registry_name], value, default_value) + } + + // ================================== + // Namespace default accessor methods + // ================================== + set_defaults(kwargs) { + Object.assign(this._defaults, kwargs) + + // if these defaults match any existing arguments, replace + // the previous default on the object with the new one + for (let action of this._actions) { + if (action.dest in kwargs) { + action.default = kwargs[action.dest] + } + } + } + + get_default(dest) { + for (let action of this._actions) { + if (action.dest === dest && action.default !== undefined) { + return action.default + } + } + return this._defaults[dest] + } + + + // ======================= + // Adding argument actions + // ======================= + add_argument() { + /* + * add_argument(dest, ..., name=value, ...) + * add_argument(option_string, option_string, ..., name=value, ...) + */ + let [ + args, + kwargs + ] = _parse_opts(arguments, { + '*args': no_default, + '**kwargs': no_default + }) + // LEGACY (v1 compatibility), old-style add_argument([ args ], { options }) + if (args.length === 1 && Array.isArray(args[0])) { + args = args[0] + deprecate('argument-array', + sub('use add_argument(%(args)s, {...}) instead of add_argument([ %(args)s ], { ... })', { + args: args.map(repr).join(', ') + })) + } + // end + + // if no positional args are supplied or only one is supplied and + // it doesn't look like an option string, parse a positional + // argument + let chars = this.prefix_chars + if (!args.length || args.length === 1 && !chars.includes(args[0][0])) { + if (args.length && 'dest' in kwargs) { + throw new TypeError('dest supplied twice for positional argument') + } + kwargs = this._get_positional_kwargs(...args, kwargs) + + // otherwise, we're adding an optional argument + } else { + kwargs = this._get_optional_kwargs(...args, kwargs) + } + + // if no default was supplied, use the parser-level default + if (!('default' in kwargs)) { + let dest = kwargs.dest + if (dest in this._defaults) { + kwargs.default = this._defaults[dest] + } else if (this.argument_default !== undefined) { + kwargs.default = this.argument_default + } + } + + // create the action object, and add it to the parser + let action_class = this._pop_action_class(kwargs) + if (typeof action_class !== 'function') { + throw new TypeError(sub('unknown action "%s"', action_class)) + } + // eslint-disable-next-line new-cap + let action = new action_class(kwargs) + + // raise an error if the action type is not callable + let type_func = this._registry_get('type', action.type, action.type) + if (typeof type_func !== 'function') { + throw new TypeError(sub('%r is not callable', type_func)) + } + + if (type_func === FileType) { + throw new TypeError(sub('%r is a FileType class object, instance of it' + + ' must be passed', type_func)) + } + + // raise an error if the metavar does not match the type + if ('_get_formatter' in this) { + try { + this._get_formatter()._format_args(action, undefined) + } catch (err) { + // check for 'invalid nargs value' is an artifact of TypeError and ValueError in js being the same + if (err instanceof TypeError && err.message !== 'invalid nargs value') { + throw new TypeError('length of metavar tuple does not match nargs') + } else { + throw err + } + } + } + + return this._add_action(action) + } + + add_argument_group() { + let group = _ArgumentGroup(this, ...arguments) + this._action_groups.push(group) + return group + } + + add_mutually_exclusive_group() { + // eslint-disable-next-line no-use-before-define + let group = _MutuallyExclusiveGroup(this, ...arguments) + this._mutually_exclusive_groups.push(group) + return group + } + + _add_action(action) { + // resolve any conflicts + this._check_conflict(action) + + // add to actions list + this._actions.push(action) + action.container = this + + // index the action by any option strings it has + for (let option_string of action.option_strings) { + this._option_string_actions[option_string] = action + } + + // set the flag if any option strings look like negative numbers + for (let option_string of action.option_strings) { + if (this._negative_number_matcher.test(option_string)) { + if (!this._has_negative_number_optionals.length) { + this._has_negative_number_optionals.push(true) + } + } + } + + // return the created action + return action + } + + _remove_action(action) { + _array_remove(this._actions, action) + } + + _add_container_actions(container) { + // collect groups by titles + let title_group_map = {} + for (let group of this._action_groups) { + if (group.title in title_group_map) { + let msg = 'cannot merge actions - two groups are named %r' + throw new TypeError(sub(msg, group.title)) + } + title_group_map[group.title] = group + } + + // map each action to its group + let group_map = new Map() + for (let group of container._action_groups) { + + // if a group with the title exists, use that, otherwise + // create a new group matching the container's group + if (!(group.title in title_group_map)) { + title_group_map[group.title] = this.add_argument_group({ + title: group.title, + description: group.description, + conflict_handler: group.conflict_handler + }) + } + + // map the actions to their new group + for (let action of group._group_actions) { + group_map.set(action, title_group_map[group.title]) + } + } + + // add container's mutually exclusive groups + // NOTE: if add_mutually_exclusive_group ever gains title= and + // description= then this code will need to be expanded as above + for (let group of container._mutually_exclusive_groups) { + let mutex_group = this.add_mutually_exclusive_group({ + required: group.required + }) + + // map the actions to their new mutex group + for (let action of group._group_actions) { + group_map.set(action, mutex_group) + } + } + + // add all actions to this container or their group + for (let action of container._actions) { + group_map.get(action)._add_action(action) + } + } + + _get_positional_kwargs() { + let [ + dest, + kwargs + ] = _parse_opts(arguments, { + dest: no_default, + '**kwargs': no_default + }) + + // make sure required is not specified + if ('required' in kwargs) { + let msg = "'required' is an invalid argument for positionals" + throw new TypeError(msg) + } + + // mark positional arguments as required if at least one is + // always required + if (![OPTIONAL, ZERO_OR_MORE].includes(kwargs.nargs)) { + kwargs.required = true + } + if (kwargs.nargs === ZERO_OR_MORE && !('default' in kwargs)) { + kwargs.required = true + } + + // return the keyword arguments with no option strings + return Object.assign(kwargs, { dest, option_strings: [] }) + } + + _get_optional_kwargs() { + let [ + args, + kwargs + ] = _parse_opts(arguments, { + '*args': no_default, + '**kwargs': no_default + }) + + // determine short and long option strings + let option_strings = [] + let long_option_strings = [] + let option_string + for (option_string of args) { + // error on strings that don't start with an appropriate prefix + if (!this.prefix_chars.includes(option_string[0])) { + let args = {option: option_string, + prefix_chars: this.prefix_chars} + let msg = 'invalid option string %(option)r: ' + + 'must start with a character %(prefix_chars)r' + throw new TypeError(sub(msg, args)) + } + + // strings starting with two prefix characters are long options + option_strings.push(option_string) + if (option_string.length > 1 && this.prefix_chars.includes(option_string[1])) { + long_option_strings.push(option_string) + } + } + + // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' + let dest = kwargs.dest + delete kwargs.dest + if (dest === undefined) { + let dest_option_string + if (long_option_strings.length) { + dest_option_string = long_option_strings[0] + } else { + dest_option_string = option_strings[0] + } + dest = _string_lstrip(dest_option_string, this.prefix_chars) + if (!dest) { + let msg = 'dest= is required for options like %r' + throw new TypeError(sub(msg, option_string)) + } + dest = dest.replace(/-/g, '_') + } + + // return the updated keyword arguments + return Object.assign(kwargs, { dest, option_strings }) + } + + _pop_action_class(kwargs, default_value = undefined) { + let action = getattr(kwargs, 'action', default_value) + delete kwargs.action + return this._registry_get('action', action, action) + } + + _get_handler() { + // determine function from conflict handler string + let handler_func_name = sub('_handle_conflict_%s', this.conflict_handler) + if (typeof this[handler_func_name] === 'function') { + return this[handler_func_name] + } else { + let msg = 'invalid conflict_resolution value: %r' + throw new TypeError(sub(msg, this.conflict_handler)) + } + } + + _check_conflict(action) { + + // find all options that conflict with this option + let confl_optionals = [] + for (let option_string of action.option_strings) { + if (hasattr(this._option_string_actions, option_string)) { + let confl_optional = this._option_string_actions[option_string] + confl_optionals.push([ option_string, confl_optional ]) + } + } + + // resolve any conflicts + if (confl_optionals.length) { + let conflict_handler = this._get_handler() + conflict_handler.call(this, action, confl_optionals) + } + } + + _handle_conflict_error(action, conflicting_actions) { + let message = conflicting_actions.length === 1 ? + 'conflicting option string: %s' : + 'conflicting option strings: %s' + let conflict_string = conflicting_actions.map(([ option_string/*, action*/ ]) => option_string).join(', ') + throw new ArgumentError(action, sub(message, conflict_string)) + } + + _handle_conflict_resolve(action, conflicting_actions) { + + // remove all conflicting options + for (let [ option_string, action ] of conflicting_actions) { + + // remove the conflicting option + _array_remove(action.option_strings, option_string) + delete this._option_string_actions[option_string] + + // if the option now has no option string, remove it from the + // container holding it + if (!action.option_strings.length) { + action.container._remove_action(action) + } + } + } +})) + + +const _ArgumentGroup = _callable(class _ArgumentGroup extends _ActionsContainer { + + constructor() { + let [ + container, + title, + description, + kwargs + ] = _parse_opts(arguments, { + container: no_default, + title: undefined, + description: undefined, + '**kwargs': no_default + }) + + // add any missing keyword arguments by checking the container + setdefault(kwargs, 'conflict_handler', container.conflict_handler) + setdefault(kwargs, 'prefix_chars', container.prefix_chars) + setdefault(kwargs, 'argument_default', container.argument_default) + super(Object.assign({ description }, kwargs)) + + // group attributes + this.title = title + this._group_actions = [] + + // share most attributes with the container + this._registries = container._registries + this._actions = container._actions + this._option_string_actions = container._option_string_actions + this._defaults = container._defaults + this._has_negative_number_optionals = + container._has_negative_number_optionals + this._mutually_exclusive_groups = container._mutually_exclusive_groups + } + + _add_action(action) { + action = super._add_action(action) + this._group_actions.push(action) + return action + } + + _remove_action(action) { + super._remove_action(action) + _array_remove(this._group_actions, action) + } +}) + + +const _MutuallyExclusiveGroup = _callable(class _MutuallyExclusiveGroup extends _ArgumentGroup { + + constructor() { + let [ + container, + required + ] = _parse_opts(arguments, { + container: no_default, + required: false + }) + + super(container) + this.required = required + this._container = container + } + + _add_action(action) { + if (action.required) { + let msg = 'mutually exclusive arguments must be optional' + throw new TypeError(msg) + } + action = this._container._add_action(action) + this._group_actions.push(action) + return action + } + + _remove_action(action) { + this._container._remove_action(action) + _array_remove(this._group_actions, action) + } +}) + + +const ArgumentParser = _camelcase_alias(_callable(class ArgumentParser extends _AttributeHolder(_ActionsContainer) { + /* + * Object for parsing command line strings into Python objects. + * + * Keyword Arguments: + * - prog -- The name of the program (default: sys.argv[0]) + * - usage -- A usage message (default: auto-generated from arguments) + * - description -- A description of what the program does + * - epilog -- Text following the argument descriptions + * - parents -- Parsers whose arguments should be copied into this one + * - formatter_class -- HelpFormatter class for printing help messages + * - prefix_chars -- Characters that prefix optional arguments + * - fromfile_prefix_chars -- Characters that prefix files containing + * additional arguments + * - argument_default -- The default value for all arguments + * - conflict_handler -- String indicating how to handle conflicts + * - add_help -- Add a -h/-help option + * - allow_abbrev -- Allow long options to be abbreviated unambiguously + * - exit_on_error -- Determines whether or not ArgumentParser exits with + * error info when an error occurs + */ + + constructor() { + let [ + prog, + usage, + description, + epilog, + parents, + formatter_class, + prefix_chars, + fromfile_prefix_chars, + argument_default, + conflict_handler, + add_help, + allow_abbrev, + exit_on_error, + debug, // LEGACY (v1 compatibility), debug mode + version // LEGACY (v1 compatibility), version + ] = _parse_opts(arguments, { + prog: undefined, + usage: undefined, + description: undefined, + epilog: undefined, + parents: [], + formatter_class: HelpFormatter, + prefix_chars: '-', + fromfile_prefix_chars: undefined, + argument_default: undefined, + conflict_handler: 'error', + add_help: true, + allow_abbrev: true, + exit_on_error: true, + debug: undefined, // LEGACY (v1 compatibility), debug mode + version: undefined // LEGACY (v1 compatibility), version + }) + + // LEGACY (v1 compatibility) + if (debug !== undefined) { + deprecate('debug', + 'The "debug" argument to ArgumentParser is deprecated. Please ' + + 'override ArgumentParser.exit function instead.' + ) + } + + if (version !== undefined) { + deprecate('version', + 'The "version" argument to ArgumentParser is deprecated. Please use ' + + "add_argument(..., { action: 'version', version: 'N', ... }) instead." + ) + } + // end + + super({ + description, + prefix_chars, + argument_default, + conflict_handler + }) + + // default setting for prog + if (prog === undefined) { + prog = path.basename(get_argv()[0] || '') + } + + this.prog = prog + this.usage = usage + this.epilog = epilog + this.formatter_class = formatter_class + this.fromfile_prefix_chars = fromfile_prefix_chars + this.add_help = add_help + this.allow_abbrev = allow_abbrev + this.exit_on_error = exit_on_error + // LEGACY (v1 compatibility), debug mode + this.debug = debug + // end + + this._positionals = this.add_argument_group('positional arguments') + this._optionals = this.add_argument_group('optional arguments') + this._subparsers = undefined + + // register types + function identity(string) { + return string + } + this.register('type', undefined, identity) + this.register('type', null, identity) + this.register('type', 'auto', identity) + this.register('type', 'int', function (x) { + let result = Number(x) + if (!Number.isInteger(result)) { + throw new TypeError(sub('could not convert string to int: %r', x)) + } + return result + }) + this.register('type', 'float', function (x) { + let result = Number(x) + if (isNaN(result)) { + throw new TypeError(sub('could not convert string to float: %r', x)) + } + return result + }) + this.register('type', 'str', String) + // LEGACY (v1 compatibility): custom types + this.register('type', 'string', + util.deprecate(String, 'use {type:"str"} or {type:String} instead of {type:"string"}')) + // end + + // add help argument if necessary + // (using explicit default to override global argument_default) + let default_prefix = prefix_chars.includes('-') ? '-' : prefix_chars[0] + if (this.add_help) { + this.add_argument( + default_prefix + 'h', + default_prefix.repeat(2) + 'help', + { + action: 'help', + default: SUPPRESS, + help: 'show this help message and exit' + } + ) + } + // LEGACY (v1 compatibility), version + if (version) { + this.add_argument( + default_prefix + 'v', + default_prefix.repeat(2) + 'version', + { + action: 'version', + default: SUPPRESS, + version: this.version, + help: "show program's version number and exit" + } + ) + } + // end + + // add parent arguments and defaults + for (let parent of parents) { + this._add_container_actions(parent) + Object.assign(this._defaults, parent._defaults) + } + } + + // ======================= + // Pretty __repr__ methods + // ======================= + _get_kwargs() { + let names = [ + 'prog', + 'usage', + 'description', + 'formatter_class', + 'conflict_handler', + 'add_help' + ] + return names.map(name => [ name, getattr(this, name) ]) + } + + // ================================== + // Optional/Positional adding methods + // ================================== + add_subparsers() { + let [ + kwargs + ] = _parse_opts(arguments, { + '**kwargs': no_default + }) + + if (this._subparsers !== undefined) { + this.error('cannot have multiple subparser arguments') + } + + // add the parser class to the arguments if it's not present + setdefault(kwargs, 'parser_class', this.constructor) + + if ('title' in kwargs || 'description' in kwargs) { + let title = getattr(kwargs, 'title', 'subcommands') + let description = getattr(kwargs, 'description', undefined) + delete kwargs.title + delete kwargs.description + this._subparsers = this.add_argument_group(title, description) + } else { + this._subparsers = this._positionals + } + + // prog defaults to the usage message of this parser, skipping + // optional arguments and with no "usage:" prefix + if (kwargs.prog === undefined) { + let formatter = this._get_formatter() + let positionals = this._get_positional_actions() + let groups = this._mutually_exclusive_groups + formatter.add_usage(this.usage, positionals, groups, '') + kwargs.prog = formatter.format_help().trim() + } + + // create the parsers action and add it to the positionals list + let parsers_class = this._pop_action_class(kwargs, 'parsers') + // eslint-disable-next-line new-cap + let action = new parsers_class(Object.assign({ option_strings: [] }, kwargs)) + this._subparsers._add_action(action) + + // return the created parsers action + return action + } + + _add_action(action) { + if (action.option_strings.length) { + this._optionals._add_action(action) + } else { + this._positionals._add_action(action) + } + return action + } + + _get_optional_actions() { + return this._actions.filter(action => action.option_strings.length) + } + + _get_positional_actions() { + return this._actions.filter(action => !action.option_strings.length) + } + + // ===================================== + // Command line argument parsing methods + // ===================================== + parse_args(args = undefined, namespace = undefined) { + let argv + [ args, argv ] = this.parse_known_args(args, namespace) + if (argv && argv.length > 0) { + let msg = 'unrecognized arguments: %s' + this.error(sub(msg, argv.join(' '))) + } + return args + } + + parse_known_args(args = undefined, namespace = undefined) { + if (args === undefined) { + args = get_argv().slice(1) + } + + // default Namespace built from parser defaults + if (namespace === undefined) { + namespace = new Namespace() + } + + // add any action defaults that aren't present + for (let action of this._actions) { + if (action.dest !== SUPPRESS) { + if (!hasattr(namespace, action.dest)) { + if (action.default !== SUPPRESS) { + setattr(namespace, action.dest, action.default) + } + } + } + } + + // add any parser defaults that aren't present + for (let dest of Object.keys(this._defaults)) { + if (!hasattr(namespace, dest)) { + setattr(namespace, dest, this._defaults[dest]) + } + } + + // parse the arguments and exit if there are any errors + if (this.exit_on_error) { + try { + [ namespace, args ] = this._parse_known_args(args, namespace) + } catch (err) { + if (err instanceof ArgumentError) { + this.error(err.message) + } else { + throw err + } + } + } else { + [ namespace, args ] = this._parse_known_args(args, namespace) + } + + if (hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) { + args = args.concat(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) + delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) + } + + return [ namespace, args ] + } + + _parse_known_args(arg_strings, namespace) { + // replace arg strings that are file references + if (this.fromfile_prefix_chars !== undefined) { + arg_strings = this._read_args_from_files(arg_strings) + } + + // map all mutually exclusive arguments to the other arguments + // they can't occur with + let action_conflicts = new Map() + for (let mutex_group of this._mutually_exclusive_groups) { + let group_actions = mutex_group._group_actions + for (let [ i, mutex_action ] of Object.entries(mutex_group._group_actions)) { + let conflicts = action_conflicts.get(mutex_action) || [] + conflicts = conflicts.concat(group_actions.slice(0, +i)) + conflicts = conflicts.concat(group_actions.slice(+i + 1)) + action_conflicts.set(mutex_action, conflicts) + } + } + + // find all option indices, and determine the arg_string_pattern + // which has an 'O' if there is an option at an index, + // an 'A' if there is an argument, or a '-' if there is a '--' + let option_string_indices = {} + let arg_string_pattern_parts = [] + let arg_strings_iter = Object.entries(arg_strings)[Symbol.iterator]() + for (let [ i, arg_string ] of arg_strings_iter) { + + // all args after -- are non-options + if (arg_string === '--') { + arg_string_pattern_parts.push('-') + for ([ i, arg_string ] of arg_strings_iter) { + arg_string_pattern_parts.push('A') + } + + // otherwise, add the arg to the arg strings + // and note the index if it was an option + } else { + let option_tuple = this._parse_optional(arg_string) + let pattern + if (option_tuple === undefined) { + pattern = 'A' + } else { + option_string_indices[i] = option_tuple + pattern = 'O' + } + arg_string_pattern_parts.push(pattern) + } + } + + // join the pieces together to form the pattern + let arg_strings_pattern = arg_string_pattern_parts.join('') + + // converts arg strings to the appropriate and then takes the action + let seen_actions = new Set() + let seen_non_default_actions = new Set() + let extras + + let take_action = (action, argument_strings, option_string = undefined) => { + seen_actions.add(action) + let argument_values = this._get_values(action, argument_strings) + + // error if this argument is not allowed with other previously + // seen arguments, assuming that actions that use the default + // value don't really count as "present" + if (argument_values !== action.default) { + seen_non_default_actions.add(action) + for (let conflict_action of action_conflicts.get(action) || []) { + if (seen_non_default_actions.has(conflict_action)) { + let msg = 'not allowed with argument %s' + let action_name = _get_action_name(conflict_action) + throw new ArgumentError(action, sub(msg, action_name)) + } + } + } + + // take the action if we didn't receive a SUPPRESS value + // (e.g. from a default) + if (argument_values !== SUPPRESS) { + action(this, namespace, argument_values, option_string) + } + } + + // function to convert arg_strings into an optional action + let consume_optional = start_index => { + + // get the optional identified at this index + let option_tuple = option_string_indices[start_index] + let [ action, option_string, explicit_arg ] = option_tuple + + // identify additional optionals in the same arg string + // (e.g. -xyz is the same as -x -y -z if no args are required) + let action_tuples = [] + let stop + for (;;) { + + // if we found no optional action, skip it + if (action === undefined) { + extras.push(arg_strings[start_index]) + return start_index + 1 + } + + // if there is an explicit argument, try to match the + // optional's string arguments to only this + if (explicit_arg !== undefined) { + let arg_count = this._match_argument(action, 'A') + + // if the action is a single-dash option and takes no + // arguments, try to parse more single-dash options out + // of the tail of the option string + let chars = this.prefix_chars + if (arg_count === 0 && !chars.includes(option_string[1])) { + action_tuples.push([ action, [], option_string ]) + let char = option_string[0] + option_string = char + explicit_arg[0] + let new_explicit_arg = explicit_arg.slice(1) || undefined + let optionals_map = this._option_string_actions + if (hasattr(optionals_map, option_string)) { + action = optionals_map[option_string] + explicit_arg = new_explicit_arg + } else { + let msg = 'ignored explicit argument %r' + throw new ArgumentError(action, sub(msg, explicit_arg)) + } + + // if the action expect exactly one argument, we've + // successfully matched the option; exit the loop + } else if (arg_count === 1) { + stop = start_index + 1 + let args = [ explicit_arg ] + action_tuples.push([ action, args, option_string ]) + break + + // error if a double-dash option did not use the + // explicit argument + } else { + let msg = 'ignored explicit argument %r' + throw new ArgumentError(action, sub(msg, explicit_arg)) + } + + // if there is no explicit argument, try to match the + // optional's string arguments with the following strings + // if successful, exit the loop + } else { + let start = start_index + 1 + let selected_patterns = arg_strings_pattern.slice(start) + let arg_count = this._match_argument(action, selected_patterns) + stop = start + arg_count + let args = arg_strings.slice(start, stop) + action_tuples.push([ action, args, option_string ]) + break + } + } + + // add the Optional to the list and return the index at which + // the Optional's string args stopped + assert(action_tuples.length) + for (let [ action, args, option_string ] of action_tuples) { + take_action(action, args, option_string) + } + return stop + } + + // the list of Positionals left to be parsed; this is modified + // by consume_positionals() + let positionals = this._get_positional_actions() + + // function to convert arg_strings into positional actions + let consume_positionals = start_index => { + // match as many Positionals as possible + let selected_pattern = arg_strings_pattern.slice(start_index) + let arg_counts = this._match_arguments_partial(positionals, selected_pattern) + + // slice off the appropriate arg strings for each Positional + // and add the Positional and its args to the list + for (let i = 0; i < positionals.length && i < arg_counts.length; i++) { + let action = positionals[i] + let arg_count = arg_counts[i] + let args = arg_strings.slice(start_index, start_index + arg_count) + start_index += arg_count + take_action(action, args) + } + + // slice off the Positionals that we just parsed and return the + // index at which the Positionals' string args stopped + positionals = positionals.slice(arg_counts.length) + return start_index + } + + // consume Positionals and Optionals alternately, until we have + // passed the last option string + extras = [] + let start_index = 0 + let max_option_string_index = Math.max(-1, ...Object.keys(option_string_indices).map(Number)) + while (start_index <= max_option_string_index) { + + // consume any Positionals preceding the next option + let next_option_string_index = Math.min( + // eslint-disable-next-line no-loop-func + ...Object.keys(option_string_indices).map(Number).filter(index => index >= start_index) + ) + if (start_index !== next_option_string_index) { + let positionals_end_index = consume_positionals(start_index) + + // only try to parse the next optional if we didn't consume + // the option string during the positionals parsing + if (positionals_end_index > start_index) { + start_index = positionals_end_index + continue + } else { + start_index = positionals_end_index + } + } + + // if we consumed all the positionals we could and we're not + // at the index of an option string, there were extra arguments + if (!(start_index in option_string_indices)) { + let strings = arg_strings.slice(start_index, next_option_string_index) + extras = extras.concat(strings) + start_index = next_option_string_index + } + + // consume the next optional and any arguments for it + start_index = consume_optional(start_index) + } + + // consume any positionals following the last Optional + let stop_index = consume_positionals(start_index) + + // if we didn't consume all the argument strings, there were extras + extras = extras.concat(arg_strings.slice(stop_index)) + + // make sure all required actions were present and also convert + // action defaults which were not given as arguments + let required_actions = [] + for (let action of this._actions) { + if (!seen_actions.has(action)) { + if (action.required) { + required_actions.push(_get_action_name(action)) + } else { + // Convert action default now instead of doing it before + // parsing arguments to avoid calling convert functions + // twice (which may fail) if the argument was given, but + // only if it was defined already in the namespace + if (action.default !== undefined && + typeof action.default === 'string' && + hasattr(namespace, action.dest) && + action.default === getattr(namespace, action.dest)) { + setattr(namespace, action.dest, + this._get_value(action, action.default)) + } + } + } + } + + if (required_actions.length) { + this.error(sub('the following arguments are required: %s', + required_actions.join(', '))) + } + + // make sure all required groups had one option present + for (let group of this._mutually_exclusive_groups) { + if (group.required) { + let no_actions_used = true + for (let action of group._group_actions) { + if (seen_non_default_actions.has(action)) { + no_actions_used = false + break + } + } + + // if no actions were used, report the error + if (no_actions_used) { + let names = group._group_actions + .filter(action => action.help !== SUPPRESS) + .map(action => _get_action_name(action)) + let msg = 'one of the arguments %s is required' + this.error(sub(msg, names.join(' '))) + } + } + } + + // return the updated namespace and the extra arguments + return [ namespace, extras ] + } + + _read_args_from_files(arg_strings) { + // expand arguments referencing files + let new_arg_strings = [] + for (let arg_string of arg_strings) { + + // for regular arguments, just add them back into the list + if (!arg_string || !this.fromfile_prefix_chars.includes(arg_string[0])) { + new_arg_strings.push(arg_string) + + // replace arguments referencing files with the file content + } else { + try { + let args_file = fs.readFileSync(arg_string.slice(1), 'utf8') + let arg_strings = [] + for (let arg_line of splitlines(args_file)) { + for (let arg of this.convert_arg_line_to_args(arg_line)) { + arg_strings.push(arg) + } + } + arg_strings = this._read_args_from_files(arg_strings) + new_arg_strings = new_arg_strings.concat(arg_strings) + } catch (err) { + this.error(err.message) + } + } + } + + // return the modified argument list + return new_arg_strings + } + + convert_arg_line_to_args(arg_line) { + return [arg_line] + } + + _match_argument(action, arg_strings_pattern) { + // match the pattern for this action to the arg strings + let nargs_pattern = this._get_nargs_pattern(action) + let match = arg_strings_pattern.match(new RegExp('^' + nargs_pattern)) + + // raise an exception if we weren't able to find a match + if (match === null) { + let nargs_errors = { + undefined: 'expected one argument', + [OPTIONAL]: 'expected at most one argument', + [ONE_OR_MORE]: 'expected at least one argument' + } + let msg = nargs_errors[action.nargs] + if (msg === undefined) { + msg = sub(action.nargs === 1 ? 'expected %s argument' : 'expected %s arguments', action.nargs) + } + throw new ArgumentError(action, msg) + } + + // return the number of arguments matched + return match[1].length + } + + _match_arguments_partial(actions, arg_strings_pattern) { + // progressively shorten the actions list by slicing off the + // final actions until we find a match + let result = [] + for (let i of range(actions.length, 0, -1)) { + let actions_slice = actions.slice(0, i) + let pattern = actions_slice.map(action => this._get_nargs_pattern(action)).join('') + let match = arg_strings_pattern.match(new RegExp('^' + pattern)) + if (match !== null) { + result = result.concat(match.slice(1).map(string => string.length)) + break + } + } + + // return the list of arg string counts + return result + } + + _parse_optional(arg_string) { + // if it's an empty string, it was meant to be a positional + if (!arg_string) { + return undefined + } + + // if it doesn't start with a prefix, it was meant to be positional + if (!this.prefix_chars.includes(arg_string[0])) { + return undefined + } + + // if the option string is present in the parser, return the action + if (arg_string in this._option_string_actions) { + let action = this._option_string_actions[arg_string] + return [ action, arg_string, undefined ] + } + + // if it's just a single character, it was meant to be positional + if (arg_string.length === 1) { + return undefined + } + + // if the option string before the "=" is present, return the action + if (arg_string.includes('=')) { + let [ option_string, explicit_arg ] = _string_split(arg_string, '=', 1) + if (option_string in this._option_string_actions) { + let action = this._option_string_actions[option_string] + return [ action, option_string, explicit_arg ] + } + } + + // search through all possible prefixes of the option string + // and all actions in the parser for possible interpretations + let option_tuples = this._get_option_tuples(arg_string) + + // if multiple actions match, the option string was ambiguous + if (option_tuples.length > 1) { + let options = option_tuples.map(([ /*action*/, option_string/*, explicit_arg*/ ]) => option_string).join(', ') + let args = {option: arg_string, matches: options} + let msg = 'ambiguous option: %(option)s could match %(matches)s' + this.error(sub(msg, args)) + + // if exactly one action matched, this segmentation is good, + // so return the parsed action + } else if (option_tuples.length === 1) { + let [ option_tuple ] = option_tuples + return option_tuple + } + + // if it was not found as an option, but it looks like a negative + // number, it was meant to be positional + // unless there are negative-number-like options + if (this._negative_number_matcher.test(arg_string)) { + if (!this._has_negative_number_optionals.length) { + return undefined + } + } + + // if it contains a space, it was meant to be a positional + if (arg_string.includes(' ')) { + return undefined + } + + // it was meant to be an optional but there is no such option + // in this parser (though it might be a valid option in a subparser) + return [ undefined, arg_string, undefined ] + } + + _get_option_tuples(option_string) { + let result = [] + + // option strings starting with two prefix characters are only + // split at the '=' + let chars = this.prefix_chars + if (chars.includes(option_string[0]) && chars.includes(option_string[1])) { + if (this.allow_abbrev) { + let option_prefix, explicit_arg + if (option_string.includes('=')) { + [ option_prefix, explicit_arg ] = _string_split(option_string, '=', 1) + } else { + option_prefix = option_string + explicit_arg = undefined + } + for (let option_string of Object.keys(this._option_string_actions)) { + if (option_string.startsWith(option_prefix)) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, explicit_arg ] + result.push(tup) + } + } + } + + // single character options can be concatenated with their arguments + // but multiple character options always have to have their argument + // separate + } else if (chars.includes(option_string[0]) && !chars.includes(option_string[1])) { + let option_prefix = option_string + let explicit_arg = undefined + let short_option_prefix = option_string.slice(0, 2) + let short_explicit_arg = option_string.slice(2) + + for (let option_string of Object.keys(this._option_string_actions)) { + if (option_string === short_option_prefix) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, short_explicit_arg ] + result.push(tup) + } else if (option_string.startsWith(option_prefix)) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, explicit_arg ] + result.push(tup) + } + } + + // shouldn't ever get here + } else { + this.error(sub('unexpected option string: %s', option_string)) + } + + // return the collected option tuples + return result + } + + _get_nargs_pattern(action) { + // in all examples below, we have to allow for '--' args + // which are represented as '-' in the pattern + let nargs = action.nargs + let nargs_pattern + + // the default (None) is assumed to be a single argument + if (nargs === undefined) { + nargs_pattern = '(-*A-*)' + + // allow zero or one arguments + } else if (nargs === OPTIONAL) { + nargs_pattern = '(-*A?-*)' + + // allow zero or more arguments + } else if (nargs === ZERO_OR_MORE) { + nargs_pattern = '(-*[A-]*)' + + // allow one or more arguments + } else if (nargs === ONE_OR_MORE) { + nargs_pattern = '(-*A[A-]*)' + + // allow any number of options or arguments + } else if (nargs === REMAINDER) { + nargs_pattern = '([-AO]*)' + + // allow one argument followed by any number of options or arguments + } else if (nargs === PARSER) { + nargs_pattern = '(-*A[-AO]*)' + + // suppress action, like nargs=0 + } else if (nargs === SUPPRESS) { + nargs_pattern = '(-*-*)' + + // all others should be integers + } else { + nargs_pattern = sub('(-*%s-*)', 'A'.repeat(nargs).split('').join('-*')) + } + + // if this is an optional action, -- is not allowed + if (action.option_strings.length) { + nargs_pattern = nargs_pattern.replace(/-\*/g, '') + nargs_pattern = nargs_pattern.replace(/-/g, '') + } + + // return the pattern + return nargs_pattern + } + + // ======================== + // Alt command line argument parsing, allowing free intermix + // ======================== + + parse_intermixed_args(args = undefined, namespace = undefined) { + let argv + [ args, argv ] = this.parse_known_intermixed_args(args, namespace) + if (argv.length) { + let msg = 'unrecognized arguments: %s' + this.error(sub(msg, argv.join(' '))) + } + return args + } + + parse_known_intermixed_args(args = undefined, namespace = undefined) { + // returns a namespace and list of extras + // + // positional can be freely intermixed with optionals. optionals are + // first parsed with all positional arguments deactivated. The 'extras' + // are then parsed. If the parser definition is incompatible with the + // intermixed assumptions (e.g. use of REMAINDER, subparsers) a + // TypeError is raised. + // + // positionals are 'deactivated' by setting nargs and default to + // SUPPRESS. This blocks the addition of that positional to the + // namespace + + let extras + let positionals = this._get_positional_actions() + let a = positionals.filter(action => [ PARSER, REMAINDER ].includes(action.nargs)) + if (a.length) { + throw new TypeError(sub('parse_intermixed_args: positional arg' + + ' with nargs=%s', a[0].nargs)) + } + + for (let group of this._mutually_exclusive_groups) { + for (let action of group._group_actions) { + if (positionals.includes(action)) { + throw new TypeError('parse_intermixed_args: positional in' + + ' mutuallyExclusiveGroup') + } + } + } + + let save_usage + try { + save_usage = this.usage + let remaining_args + try { + if (this.usage === undefined) { + // capture the full usage for use in error messages + this.usage = this.format_usage().slice(7) + } + for (let action of positionals) { + // deactivate positionals + action.save_nargs = action.nargs + // action.nargs = 0 + action.nargs = SUPPRESS + action.save_default = action.default + action.default = SUPPRESS + } + [ namespace, remaining_args ] = this.parse_known_args(args, + namespace) + for (let action of positionals) { + // remove the empty positional values from namespace + let attr = getattr(namespace, action.dest) + if (Array.isArray(attr) && attr.length === 0) { + // eslint-disable-next-line no-console + console.warn(sub('Do not expect %s in %s', action.dest, namespace)) + delattr(namespace, action.dest) + } + } + } finally { + // restore nargs and usage before exiting + for (let action of positionals) { + action.nargs = action.save_nargs + action.default = action.save_default + } + } + let optionals = this._get_optional_actions() + try { + // parse positionals. optionals aren't normally required, but + // they could be, so make sure they aren't. + for (let action of optionals) { + action.save_required = action.required + action.required = false + } + for (let group of this._mutually_exclusive_groups) { + group.save_required = group.required + group.required = false + } + [ namespace, extras ] = this.parse_known_args(remaining_args, + namespace) + } finally { + // restore parser values before exiting + for (let action of optionals) { + action.required = action.save_required + } + for (let group of this._mutually_exclusive_groups) { + group.required = group.save_required + } + } + } finally { + this.usage = save_usage + } + return [ namespace, extras ] + } + + // ======================== + // Value conversion methods + // ======================== + _get_values(action, arg_strings) { + // for everything but PARSER, REMAINDER args, strip out first '--' + if (![PARSER, REMAINDER].includes(action.nargs)) { + try { + _array_remove(arg_strings, '--') + } catch (err) {} + } + + let value + // optional argument produces a default when not present + if (!arg_strings.length && action.nargs === OPTIONAL) { + if (action.option_strings.length) { + value = action.const + } else { + value = action.default + } + if (typeof value === 'string') { + value = this._get_value(action, value) + this._check_value(action, value) + } + + // when nargs='*' on a positional, if there were no command-line + // args, use the default if it is anything other than None + } else if (!arg_strings.length && action.nargs === ZERO_OR_MORE && + !action.option_strings.length) { + if (action.default !== undefined) { + value = action.default + } else { + value = arg_strings + } + this._check_value(action, value) + + // single argument or optional argument produces a single value + } else if (arg_strings.length === 1 && [undefined, OPTIONAL].includes(action.nargs)) { + let arg_string = arg_strings[0] + value = this._get_value(action, arg_string) + this._check_value(action, value) + + // REMAINDER arguments convert all values, checking none + } else if (action.nargs === REMAINDER) { + value = arg_strings.map(v => this._get_value(action, v)) + + // PARSER arguments convert all values, but check only the first + } else if (action.nargs === PARSER) { + value = arg_strings.map(v => this._get_value(action, v)) + this._check_value(action, value[0]) + + // SUPPRESS argument does not put anything in the namespace + } else if (action.nargs === SUPPRESS) { + value = SUPPRESS + + // all other types of nargs produce a list + } else { + value = arg_strings.map(v => this._get_value(action, v)) + for (let v of value) { + this._check_value(action, v) + } + } + + // return the converted value + return value + } + + _get_value(action, arg_string) { + let type_func = this._registry_get('type', action.type, action.type) + if (typeof type_func !== 'function') { + let msg = '%r is not callable' + throw new ArgumentError(action, sub(msg, type_func)) + } + + // convert the value to the appropriate type + let result + try { + try { + result = type_func(arg_string) + } catch (err) { + // Dear TC39, why would you ever consider making es6 classes not callable? + // We had one universal interface, [[Call]], which worked for anything + // (with familiar this-instanceof guard for classes). Now we have two. + if (err instanceof TypeError && + /Class constructor .* cannot be invoked without 'new'/.test(err.message)) { + // eslint-disable-next-line new-cap + result = new type_func(arg_string) + } else { + throw err + } + } + + } catch (err) { + // ArgumentTypeErrors indicate errors + if (err instanceof ArgumentTypeError) { + //let name = getattr(action.type, 'name', repr(action.type)) + let msg = err.message + throw new ArgumentError(action, msg) + + // TypeErrors or ValueErrors also indicate errors + } else if (err instanceof TypeError) { + let name = getattr(action.type, 'name', repr(action.type)) + let args = {type: name, value: arg_string} + let msg = 'invalid %(type)s value: %(value)r' + throw new ArgumentError(action, sub(msg, args)) + } else { + throw err + } + } + + // return the converted value + return result + } + + _check_value(action, value) { + // converted value must be one of the choices (if specified) + if (action.choices !== undefined && !_choices_to_array(action.choices).includes(value)) { + let args = {value, + choices: _choices_to_array(action.choices).map(repr).join(', ')} + let msg = 'invalid choice: %(value)r (choose from %(choices)s)' + throw new ArgumentError(action, sub(msg, args)) + } + } + + // ======================= + // Help-formatting methods + // ======================= + format_usage() { + let formatter = this._get_formatter() + formatter.add_usage(this.usage, this._actions, + this._mutually_exclusive_groups) + return formatter.format_help() + } + + format_help() { + let formatter = this._get_formatter() + + // usage + formatter.add_usage(this.usage, this._actions, + this._mutually_exclusive_groups) + + // description + formatter.add_text(this.description) + + // positionals, optionals and user-defined groups + for (let action_group of this._action_groups) { + formatter.start_section(action_group.title) + formatter.add_text(action_group.description) + formatter.add_arguments(action_group._group_actions) + formatter.end_section() + } + + // epilog + formatter.add_text(this.epilog) + + // determine help from format above + return formatter.format_help() + } + + _get_formatter() { + // eslint-disable-next-line new-cap + return new this.formatter_class({ prog: this.prog }) + } + + // ===================== + // Help-printing methods + // ===================== + print_usage(file = undefined) { + if (file === undefined) file = process.stdout + this._print_message(this.format_usage(), file) + } + + print_help(file = undefined) { + if (file === undefined) file = process.stdout + this._print_message(this.format_help(), file) + } + + _print_message(message, file = undefined) { + if (message) { + if (file === undefined) file = process.stderr + file.write(message) + } + } + + // =============== + // Exiting methods + // =============== + exit(status = 0, message = undefined) { + if (message) { + this._print_message(message, process.stderr) + } + process.exit(status) + } + + error(message) { + /* + * error(message: string) + * + * Prints a usage message incorporating the message to stderr and + * exits. + * + * If you override this in a subclass, it should not return -- it + * should either exit or raise an exception. + */ + + // LEGACY (v1 compatibility), debug mode + if (this.debug === true) throw new Error(message) + // end + this.print_usage(process.stderr) + let args = {prog: this.prog, message: message} + this.exit(2, sub('%(prog)s: error: %(message)s\n', args)) + } +})) + + +module.exports = { + ArgumentParser, + ArgumentError, + ArgumentTypeError, + BooleanOptionalAction, + FileType, + HelpFormatter, + ArgumentDefaultsHelpFormatter, + RawDescriptionHelpFormatter, + RawTextHelpFormatter, + MetavarTypeHelpFormatter, + Namespace, + Action, + ONE_OR_MORE, + OPTIONAL, + PARSER, + REMAINDER, + SUPPRESS, + ZERO_OR_MORE +} + +// LEGACY (v1 compatibility), Const alias +Object.defineProperty(module.exports, 'Const', { + get() { + let result = {} + Object.entries({ ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE }).forEach(([ n, v ]) => { + Object.defineProperty(result, n, { + get() { + deprecate(n, sub('use argparse.%s instead of argparse.Const.%s', n, n)) + return v + } + }) + }) + Object.entries({ _UNRECOGNIZED_ARGS_ATTR }).forEach(([ n, v ]) => { + Object.defineProperty(result, n, { + get() { + deprecate(n, sub('argparse.Const.%s is an internal symbol and will no longer be available', n)) + return v + } + }) + }) + return result + }, + enumerable: false +}) +// end diff --git a/node_modules/eslint/node_modules/argparse/lib/sub.js b/node_modules/eslint/node_modules/argparse/lib/sub.js new file mode 100644 index 0000000..e3eb321 --- /dev/null +++ b/node_modules/eslint/node_modules/argparse/lib/sub.js @@ -0,0 +1,67 @@ +// Limited implementation of python % string operator, supports only %s and %r for now +// (other formats are not used here, but may appear in custom templates) + +'use strict' + +const { inspect } = require('util') + + +module.exports = function sub(pattern, ...values) { + let regex = /%(?:(%)|(-)?(\*)?(?:\((\w+)\))?([A-Za-z]))/g + + let result = pattern.replace(regex, function (_, is_literal, is_left_align, is_padded, name, format) { + if (is_literal) return '%' + + let padded_count = 0 + if (is_padded) { + if (values.length === 0) throw new TypeError('not enough arguments for format string') + padded_count = values.shift() + if (!Number.isInteger(padded_count)) throw new TypeError('* wants int') + } + + let str + if (name !== undefined) { + let dict = values[0] + if (typeof dict !== 'object' || dict === null) throw new TypeError('format requires a mapping') + if (!(name in dict)) throw new TypeError(`no such key: '${name}'`) + str = dict[name] + } else { + if (values.length === 0) throw new TypeError('not enough arguments for format string') + str = values.shift() + } + + switch (format) { + case 's': + str = String(str) + break + case 'r': + str = inspect(str) + break + case 'd': + case 'i': + if (typeof str !== 'number') { + throw new TypeError(`%${format} format: a number is required, not ${typeof str}`) + } + str = String(str.toFixed(0)) + break + default: + throw new TypeError(`unsupported format character '${format}'`) + } + + if (padded_count > 0) { + return is_left_align ? str.padEnd(padded_count) : str.padStart(padded_count) + } else { + return str + } + }) + + if (values.length) { + if (values.length === 1 && typeof values[0] === 'object' && values[0] !== null) { + // mapping + } else { + throw new TypeError('not all arguments converted during string formatting') + } + } + + return result +} diff --git a/node_modules/eslint/node_modules/argparse/lib/textwrap.js b/node_modules/eslint/node_modules/argparse/lib/textwrap.js new file mode 100644 index 0000000..23d51cd --- /dev/null +++ b/node_modules/eslint/node_modules/argparse/lib/textwrap.js @@ -0,0 +1,440 @@ +// Partial port of python's argparse module, version 3.9.0 (only wrap and fill functions): +// https://github.com/python/cpython/blob/v3.9.0b4/Lib/textwrap.py + +'use strict' + +/* + * Text wrapping and filling. + */ + +// Copyright (C) 1999-2001 Gregory P. Ward. +// Copyright (C) 2002, 2003 Python Software Foundation. +// Copyright (C) 2020 argparse.js authors +// Originally written by Greg Ward + +// Hardcode the recognized whitespace characters to the US-ASCII +// whitespace characters. The main reason for doing this is that +// some Unicode spaces (like \u00a0) are non-breaking whitespaces. +// +// This less funky little regex just split on recognized spaces. E.g. +// "Hello there -- you goof-ball, use the -b option!" +// splits into +// Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ +const wordsep_simple_re = /([\t\n\x0b\x0c\r ]+)/ + +class TextWrapper { + /* + * Object for wrapping/filling text. The public interface consists of + * the wrap() and fill() methods; the other methods are just there for + * subclasses to override in order to tweak the default behaviour. + * If you want to completely replace the main wrapping algorithm, + * you'll probably have to override _wrap_chunks(). + * + * Several instance attributes control various aspects of wrapping: + * width (default: 70) + * the maximum width of wrapped lines (unless break_long_words + * is false) + * initial_indent (default: "") + * string that will be prepended to the first line of wrapped + * output. Counts towards the line's width. + * subsequent_indent (default: "") + * string that will be prepended to all lines save the first + * of wrapped output; also counts towards each line's width. + * expand_tabs (default: true) + * Expand tabs in input text to spaces before further processing. + * Each tab will become 0 .. 'tabsize' spaces, depending on its position + * in its line. If false, each tab is treated as a single character. + * tabsize (default: 8) + * Expand tabs in input text to 0 .. 'tabsize' spaces, unless + * 'expand_tabs' is false. + * replace_whitespace (default: true) + * Replace all whitespace characters in the input text by spaces + * after tab expansion. Note that if expand_tabs is false and + * replace_whitespace is true, every tab will be converted to a + * single space! + * fix_sentence_endings (default: false) + * Ensure that sentence-ending punctuation is always followed + * by two spaces. Off by default because the algorithm is + * (unavoidably) imperfect. + * break_long_words (default: true) + * Break words longer than 'width'. If false, those words will not + * be broken, and some lines might be longer than 'width'. + * break_on_hyphens (default: true) + * Allow breaking hyphenated words. If true, wrapping will occur + * preferably on whitespaces and right after hyphens part of + * compound words. + * drop_whitespace (default: true) + * Drop leading and trailing whitespace from lines. + * max_lines (default: None) + * Truncate wrapped lines. + * placeholder (default: ' [...]') + * Append to the last line of truncated text. + */ + + constructor(options = {}) { + let { + width = 70, + initial_indent = '', + subsequent_indent = '', + expand_tabs = true, + replace_whitespace = true, + fix_sentence_endings = false, + break_long_words = true, + drop_whitespace = true, + break_on_hyphens = true, + tabsize = 8, + max_lines = undefined, + placeholder=' [...]' + } = options + + this.width = width + this.initial_indent = initial_indent + this.subsequent_indent = subsequent_indent + this.expand_tabs = expand_tabs + this.replace_whitespace = replace_whitespace + this.fix_sentence_endings = fix_sentence_endings + this.break_long_words = break_long_words + this.drop_whitespace = drop_whitespace + this.break_on_hyphens = break_on_hyphens + this.tabsize = tabsize + this.max_lines = max_lines + this.placeholder = placeholder + } + + + // -- Private methods ----------------------------------------------- + // (possibly useful for subclasses to override) + + _munge_whitespace(text) { + /* + * _munge_whitespace(text : string) -> string + * + * Munge whitespace in text: expand tabs and convert all other + * whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz" + * becomes " foo bar baz". + */ + if (this.expand_tabs) { + text = text.replace(/\t/g, ' '.repeat(this.tabsize)) // not strictly correct in js + } + if (this.replace_whitespace) { + text = text.replace(/[\t\n\x0b\x0c\r]/g, ' ') + } + return text + } + + _split(text) { + /* + * _split(text : string) -> [string] + * + * Split the text to wrap into indivisible chunks. Chunks are + * not quite the same as words; see _wrap_chunks() for full + * details. As an example, the text + * Look, goof-ball -- use the -b option! + * breaks into the following chunks: + * 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', + * 'use', ' ', 'the', ' ', '-b', ' ', 'option!' + * if break_on_hyphens is True, or in: + * 'Look,', ' ', 'goof-ball', ' ', '--', ' ', + * 'use', ' ', 'the', ' ', '-b', ' ', option!' + * otherwise. + */ + let chunks = text.split(wordsep_simple_re) + chunks = chunks.filter(Boolean) + return chunks + } + + _handle_long_word(reversed_chunks, cur_line, cur_len, width) { + /* + * _handle_long_word(chunks : [string], + * cur_line : [string], + * cur_len : int, width : int) + * + * Handle a chunk of text (most likely a word, not whitespace) that + * is too long to fit in any line. + */ + // Figure out when indent is larger than the specified width, and make + // sure at least one character is stripped off on every pass + let space_left + if (width < 1) { + space_left = 1 + } else { + space_left = width - cur_len + } + + // If we're allowed to break long words, then do so: put as much + // of the next chunk onto the current line as will fit. + if (this.break_long_words) { + cur_line.push(reversed_chunks[reversed_chunks.length - 1].slice(0, space_left)) + reversed_chunks[reversed_chunks.length - 1] = reversed_chunks[reversed_chunks.length - 1].slice(space_left) + + // Otherwise, we have to preserve the long word intact. Only add + // it to the current line if there's nothing already there -- + // that minimizes how much we violate the width constraint. + } else if (!cur_line) { + cur_line.push(...reversed_chunks.pop()) + } + + // If we're not allowed to break long words, and there's already + // text on the current line, do nothing. Next time through the + // main loop of _wrap_chunks(), we'll wind up here again, but + // cur_len will be zero, so the next line will be entirely + // devoted to the long word that we can't handle right now. + } + + _wrap_chunks(chunks) { + /* + * _wrap_chunks(chunks : [string]) -> [string] + * + * Wrap a sequence of text chunks and return a list of lines of + * length 'self.width' or less. (If 'break_long_words' is false, + * some lines may be longer than this.) Chunks correspond roughly + * to words and the whitespace between them: each chunk is + * indivisible (modulo 'break_long_words'), but a line break can + * come between any two chunks. Chunks should not have internal + * whitespace; ie. a chunk is either all whitespace or a "word". + * Whitespace chunks will be removed from the beginning and end of + * lines, but apart from that whitespace is preserved. + */ + let lines = [] + let indent + if (this.width <= 0) { + throw Error(`invalid width ${this.width} (must be > 0)`) + } + if (this.max_lines !== undefined) { + if (this.max_lines > 1) { + indent = this.subsequent_indent + } else { + indent = this.initial_indent + } + if (indent.length + this.placeholder.trimStart().length > this.width) { + throw Error('placeholder too large for max width') + } + } + + // Arrange in reverse order so items can be efficiently popped + // from a stack of chucks. + chunks = chunks.reverse() + + while (chunks.length > 0) { + + // Start the list of chunks that will make up the current line. + // cur_len is just the length of all the chunks in cur_line. + let cur_line = [] + let cur_len = 0 + + // Figure out which static string will prefix this line. + let indent + if (lines) { + indent = this.subsequent_indent + } else { + indent = this.initial_indent + } + + // Maximum width for this line. + let width = this.width - indent.length + + // First chunk on line is whitespace -- drop it, unless this + // is the very beginning of the text (ie. no lines started yet). + if (this.drop_whitespace && chunks[chunks.length - 1].trim() === '' && lines.length > 0) { + chunks.pop() + } + + while (chunks.length > 0) { + let l = chunks[chunks.length - 1].length + + // Can at least squeeze this chunk onto the current line. + if (cur_len + l <= width) { + cur_line.push(chunks.pop()) + cur_len += l + + // Nope, this line is full. + } else { + break + } + } + + // The current line is full, and the next chunk is too big to + // fit on *any* line (not just this one). + if (chunks.length && chunks[chunks.length - 1].length > width) { + this._handle_long_word(chunks, cur_line, cur_len, width) + cur_len = cur_line.map(l => l.length).reduce((a, b) => a + b, 0) + } + + // If the last chunk on this line is all whitespace, drop it. + if (this.drop_whitespace && cur_line.length > 0 && cur_line[cur_line.length - 1].trim() === '') { + cur_len -= cur_line[cur_line.length - 1].length + cur_line.pop() + } + + if (cur_line) { + if (this.max_lines === undefined || + lines.length + 1 < this.max_lines || + (chunks.length === 0 || + this.drop_whitespace && + chunks.length === 1 && + !chunks[0].trim()) && cur_len <= width) { + // Convert current line back to a string and store it in + // list of all lines (return value). + lines.push(indent + cur_line.join('')) + } else { + let had_break = false + while (cur_line) { + if (cur_line[cur_line.length - 1].trim() && + cur_len + this.placeholder.length <= width) { + cur_line.push(this.placeholder) + lines.push(indent + cur_line.join('')) + had_break = true + break + } + cur_len -= cur_line[-1].length + cur_line.pop() + } + if (!had_break) { + if (lines) { + let prev_line = lines[lines.length - 1].trimEnd() + if (prev_line.length + this.placeholder.length <= + this.width) { + lines[lines.length - 1] = prev_line + this.placeholder + break + } + } + lines.push(indent + this.placeholder.lstrip()) + } + break + } + } + } + + return lines + } + + _split_chunks(text) { + text = this._munge_whitespace(text) + return this._split(text) + } + + // -- Public interface ---------------------------------------------- + + wrap(text) { + /* + * wrap(text : string) -> [string] + * + * Reformat the single paragraph in 'text' so it fits in lines of + * no more than 'self.width' columns, and return a list of wrapped + * lines. Tabs in 'text' are expanded with string.expandtabs(), + * and all other whitespace characters (including newline) are + * converted to space. + */ + let chunks = this._split_chunks(text) + // not implemented in js + //if (this.fix_sentence_endings) { + // this._fix_sentence_endings(chunks) + //} + return this._wrap_chunks(chunks) + } + + fill(text) { + /* + * fill(text : string) -> string + * + * Reformat the single paragraph in 'text' to fit in lines of no + * more than 'self.width' columns, and return a new string + * containing the entire wrapped paragraph. + */ + return this.wrap(text).join('\n') + } +} + + +// -- Convenience interface --------------------------------------------- + +function wrap(text, options = {}) { + /* + * Wrap a single paragraph of text, returning a list of wrapped lines. + * + * Reformat the single paragraph in 'text' so it fits in lines of no + * more than 'width' columns, and return a list of wrapped lines. By + * default, tabs in 'text' are expanded with string.expandtabs(), and + * all other whitespace characters (including newline) are converted to + * space. See TextWrapper class for available keyword args to customize + * wrapping behaviour. + */ + let { width = 70, ...kwargs } = options + let w = new TextWrapper(Object.assign({ width }, kwargs)) + return w.wrap(text) +} + +function fill(text, options = {}) { + /* + * Fill a single paragraph of text, returning a new string. + * + * Reformat the single paragraph in 'text' to fit in lines of no more + * than 'width' columns, and return a new string containing the entire + * wrapped paragraph. As with wrap(), tabs are expanded and other + * whitespace characters converted to space. See TextWrapper class for + * available keyword args to customize wrapping behaviour. + */ + let { width = 70, ...kwargs } = options + let w = new TextWrapper(Object.assign({ width }, kwargs)) + return w.fill(text) +} + +// -- Loosely related functionality ------------------------------------- + +let _whitespace_only_re = /^[ \t]+$/mg +let _leading_whitespace_re = /(^[ \t]*)(?:[^ \t\n])/mg + +function dedent(text) { + /* + * Remove any common leading whitespace from every line in `text`. + * + * This can be used to make triple-quoted strings line up with the left + * edge of the display, while still presenting them in the source code + * in indented form. + * + * Note that tabs and spaces are both treated as whitespace, but they + * are not equal: the lines " hello" and "\\thello" are + * considered to have no common leading whitespace. + * + * Entirely blank lines are normalized to a newline character. + */ + // Look for the longest leading string of spaces and tabs common to + // all lines. + let margin = undefined + text = text.replace(_whitespace_only_re, '') + let indents = text.match(_leading_whitespace_re) || [] + for (let indent of indents) { + indent = indent.slice(0, -1) + + if (margin === undefined) { + margin = indent + + // Current line more deeply indented than previous winner: + // no change (previous winner is still on top). + } else if (indent.startsWith(margin)) { + // pass + + // Current line consistent with and no deeper than previous winner: + // it's the new winner. + } else if (margin.startsWith(indent)) { + margin = indent + + // Find the largest common whitespace between current line and previous + // winner. + } else { + for (let i = 0; i < margin.length && i < indent.length; i++) { + if (margin[i] !== indent[i]) { + margin = margin.slice(0, i) + break + } + } + } + } + + if (margin) { + text = text.replace(new RegExp('^' + margin, 'mg'), '') + } + return text +} + +module.exports = { wrap, fill, dedent } diff --git a/node_modules/eslint/node_modules/argparse/package.json b/node_modules/eslint/node_modules/argparse/package.json new file mode 100644 index 0000000..647d2af --- /dev/null +++ b/node_modules/eslint/node_modules/argparse/package.json @@ -0,0 +1,31 @@ +{ + "name": "argparse", + "description": "CLI arguments parser. Native port of python's argparse.", + "version": "2.0.1", + "keywords": [ + "cli", + "parser", + "argparse", + "option", + "args" + ], + "main": "argparse.js", + "files": [ + "argparse.js", + "lib/" + ], + "license": "Python-2.0", + "repository": "nodeca/argparse", + "scripts": { + "lint": "eslint .", + "test": "npm run lint && nyc mocha", + "coverage": "npm run test && nyc report --reporter html" + }, + "devDependencies": { + "@babel/eslint-parser": "^7.11.0", + "@babel/plugin-syntax-class-properties": "^7.10.4", + "eslint": "^7.5.0", + "mocha": "^8.0.1", + "nyc": "^15.1.0" + } +} diff --git a/node_modules/eslint/node_modules/find-up/index.d.ts b/node_modules/eslint/node_modules/find-up/index.d.ts new file mode 100644 index 0000000..6746bb7 --- /dev/null +++ b/node_modules/eslint/node_modules/find-up/index.d.ts @@ -0,0 +1,138 @@ +/* eslint-disable @typescript-eslint/unified-signatures */ +import {Options as LocatePathOptions} from 'locate-path'; + +declare const stop: unique symbol; + +declare namespace findUp { + interface Options extends LocatePathOptions {} + + type StopSymbol = typeof stop; + + type Match = string | StopSymbol | undefined; +} + +declare const findUp: { + sync: { + /** + Synchronously check if a path exists. + + @param path - Path to the file or directory. + @returns Whether the path exists. + + @example + ``` + import findUp = require('find-up'); + + console.log(findUp.sync.exists('/Users/sindresorhus/unicorn.png')); + //=> true + ``` + */ + exists: (path: string) => boolean; + + /** + Synchronously find a file or directory by walking up parent directories. + + @param name - Name of the file or directory to find. Can be multiple. + @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. + */ + (name: string | readonly string[], options?: findUp.Options): string | undefined; + + /** + Synchronously find a file or directory by walking up parent directories. + + @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. + @returns The first path found or `undefined` if none could be found. + + @example + ``` + import path = require('path'); + import findUp = require('find-up'); + + console.log(findUp.sync(directory => { + const hasUnicorns = findUp.sync.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' + ``` + */ + (matcher: (directory: string) => findUp.Match, options?: findUp.Options): string | undefined; + }; + + /** + Check if a path exists. + + @param path - Path to a file or directory. + @returns Whether the path exists. + + @example + ``` + import findUp = require('find-up'); + + (async () => { + console.log(await findUp.exists('/Users/sindresorhus/unicorn.png')); + //=> true + })(); + ``` + */ + exists: (path: string) => Promise; + + /** + Return this in a `matcher` function to stop the search and force `findUp` to immediately return `undefined`. + */ + readonly stop: findUp.StopSymbol; + + /** + Find a file or directory by walking up parent directories. + + @param name - Name of the file or directory to find. Can be multiple. + @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. + + @example + ``` + // / + // └── Users + // └── sindresorhus + // ├── unicorn.png + // └── foo + // └── bar + // ├── baz + // └── example.js + + // example.js + import findUp = require('find-up'); + + (async () => { + console.log(await findUp('unicorn.png')); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(['rainbow.png', 'unicorn.png'])); + //=> '/Users/sindresorhus/unicorn.png' + })(); + ``` + */ + (name: string | readonly string[], options?: findUp.Options): Promise; + + /** + Find a file or directory by walking up parent directories. + + @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. + @returns The first path found or `undefined` if none could be found. + + @example + ``` + import path = require('path'); + import findUp = require('find-up'); + + (async () => { + console.log(await findUp(async directory => { + const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' + })(); + ``` + */ + (matcher: (directory: string) => (findUp.Match | Promise), options?: findUp.Options): Promise; +}; + +export = findUp; diff --git a/node_modules/eslint/node_modules/find-up/index.js b/node_modules/eslint/node_modules/find-up/index.js new file mode 100644 index 0000000..ce564e5 --- /dev/null +++ b/node_modules/eslint/node_modules/find-up/index.js @@ -0,0 +1,89 @@ +'use strict'; +const path = require('path'); +const locatePath = require('locate-path'); +const pathExists = require('path-exists'); + +const stop = Symbol('findUp.stop'); + +module.exports = async (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = async locateOptions => { + if (typeof name !== 'function') { + return locatePath(paths, locateOptions); + } + + const foundPath = await name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + // eslint-disable-next-line no-await-in-loop + const foundPath = await runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } +}; + +module.exports.sync = (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = locateOptions => { + if (typeof name !== 'function') { + return locatePath.sync(paths, locateOptions); + } + + const foundPath = name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath.sync([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + const foundPath = runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } +}; + +module.exports.exists = pathExists; + +module.exports.sync.exists = pathExists.sync; + +module.exports.stop = stop; diff --git a/node_modules/eslint/node_modules/find-up/license b/node_modules/eslint/node_modules/find-up/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/eslint/node_modules/find-up/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/eslint/node_modules/find-up/package.json b/node_modules/eslint/node_modules/find-up/package.json new file mode 100644 index 0000000..56db6dd --- /dev/null +++ b/node_modules/eslint/node_modules/find-up/package.json @@ -0,0 +1,54 @@ +{ + "name": "find-up", + "version": "5.0.0", + "description": "Find a file or directory by walking up parent directories", + "license": "MIT", + "repository": "sindresorhus/find-up", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "find", + "up", + "find-up", + "findup", + "look-up", + "look", + "file", + "search", + "match", + "package", + "resolve", + "parent", + "parents", + "folder", + "directory", + "walk", + "walking", + "path" + ], + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "devDependencies": { + "ava": "^2.1.0", + "is-path-inside": "^2.1.0", + "tempy": "^0.6.0", + "tsd": "^0.13.1", + "xo": "^0.33.0" + } +} diff --git a/node_modules/eslint/node_modules/find-up/readme.md b/node_modules/eslint/node_modules/find-up/readme.md new file mode 100644 index 0000000..7ad908a --- /dev/null +++ b/node_modules/eslint/node_modules/find-up/readme.md @@ -0,0 +1,151 @@ +# find-up [![Build Status](https://travis-ci.com/sindresorhus/find-up.svg?branch=master)](https://travis-ci.com/github/sindresorhus/find-up) + +> Find a file or directory by walking up parent directories + +## Install + +``` +$ npm install find-up +``` + +## Usage + +``` +/ +└── Users + └── sindresorhus + ├── unicorn.png + └── foo + └── bar + ├── baz + └── example.js +``` + +`example.js` + +```js +const path = require('path'); +const findUp = require('find-up'); + +(async () => { + console.log(await findUp('unicorn.png')); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(['rainbow.png', 'unicorn.png'])); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(async directory => { + const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' +})(); +``` + +## API + +### findUp(name, options?) +### findUp(matcher, options?) + +Returns a `Promise` for either the path or `undefined` if it couldn't be found. + +### findUp([...name], options?) + +Returns a `Promise` for either the first path found (by respecting the order of the array) or `undefined` if none could be found. + +### findUp.sync(name, options?) +### findUp.sync(matcher, options?) + +Returns a path or `undefined` if it couldn't be found. + +### findUp.sync([...name], options?) + +Returns the first path found (by respecting the order of the array) or `undefined` if none could be found. + +#### name + +Type: `string` + +Name of the file or directory to find. + +#### matcher + +Type: `Function` + +A function that will be called with each directory until it returns a `string` with the path, which stops the search, or the root directory has been reached and nothing was found. Useful if you want to match files with certain patterns, set of permissions, or other advanced use-cases. + +When using async mode, the `matcher` may optionally be an async or promise-returning function that returns the path. + +#### options + +Type: `object` + +##### cwd + +Type: `string`\ +Default: `process.cwd()` + +Directory to start from. + +##### type + +Type: `string`\ +Default: `'file'`\ +Values: `'file'` `'directory'` + +The type of paths that can match. + +##### allowSymlinks + +Type: `boolean`\ +Default: `true` + +Allow symbolic links to match if they point to the chosen path type. + +### findUp.exists(path) + +Returns a `Promise` of whether the path exists. + +### findUp.sync.exists(path) + +Returns a `boolean` of whether the path exists. + +#### path + +Type: `string` + +Path to a file or directory. + +### findUp.stop + +A [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that can be returned by a `matcher` function to stop the search and cause `findUp` to immediately return `undefined`. Useful as a performance optimization in case the current working directory is deeply nested in the filesystem. + +```js +const path = require('path'); +const findUp = require('find-up'); + +(async () => { + await findUp(directory => { + return path.basename(directory) === 'work' ? findUp.stop : 'logo.png'; + }); +})(); +``` + +## Related + +- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module +- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file +- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package +- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module like `require.resolve()` but from a given path + +--- + +
+ + Get professional support for 'find-up' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/eslint/node_modules/js-yaml/CHANGELOG.md b/node_modules/eslint/node_modules/js-yaml/CHANGELOG.md new file mode 100644 index 0000000..ff2375e --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/CHANGELOG.md @@ -0,0 +1,616 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [4.1.0] - 2021-04-15 +### Added +- Types are now exported as `yaml.types.XXX`. +- Every type now has `options` property with original arguments kept as they were + (see `yaml.types.int.options` as an example). + +### Changed +- `Schema.extend()` now keeps old type order in case of conflicts + (e.g. Schema.extend([ a, b, c ]).extend([ b, a, d ]) is now ordered as `abcd` instead of `cbad`). + + +## [4.0.0] - 2021-01-03 +### Changed +- Check [migration guide](migrate_v3_to_v4.md) to see details for all breaking changes. +- Breaking: "unsafe" tags `!!js/function`, `!!js/regexp`, `!!js/undefined` are + moved to [js-yaml-js-types](https://github.com/nodeca/js-yaml-js-types) package. +- Breaking: removed `safe*` functions. Use `load`, `loadAll`, `dump` + instead which are all now safe by default. +- `yaml.DEFAULT_SAFE_SCHEMA` and `yaml.DEFAULT_FULL_SCHEMA` are removed, use + `yaml.DEFAULT_SCHEMA` instead. +- `yaml.Schema.create(schema, tags)` is removed, use `schema.extend(tags)` instead. +- `!!binary` now always mapped to `Uint8Array` on load. +- Reduced nesting of `/lib` folder. +- Parse numbers according to YAML 1.2 instead of YAML 1.1 (`01234` is now decimal, + `0o1234` is octal, `1:23` is parsed as string instead of base60). +- `dump()` no longer quotes `:`, `[`, `]`, `(`, `)` except when necessary, #470, #557. +- Line and column in exceptions are now formatted as `(X:Y)` instead of + `at line X, column Y` (also present in compact format), #332. +- Code snippet created in exceptions now contains multiple lines with line numbers. +- `dump()` now serializes `undefined` as `null` in collections and removes keys with + `undefined` in mappings, #571. +- `dump()` with `skipInvalid=true` now serializes invalid items in collections as null. +- Custom tags starting with `!` are now dumped as `!tag` instead of `!`, #576. +- Custom tags starting with `tag:yaml.org,2002:` are now shorthanded using `!!`, #258. + +### Added +- Added `.mjs` (es modules) support. +- Added `quotingType` and `forceQuotes` options for dumper to configure + string literal style, #290, #529. +- Added `styles: { '!!null': 'empty' }` option for dumper + (serializes `{ foo: null }` as "`foo: `"), #570. +- Added `replacer` option (similar to option in JSON.stringify), #339. +- Custom `Tag` can now handle all tags or multiple tags with the same prefix, #385. + +### Fixed +- Astral characters are no longer encoded by `dump()`, #587. +- "duplicate mapping key" exception now points at the correct column, #452. +- Extra commas in flow collections (e.g. `[foo,,bar]`) now throw an exception + instead of producing null, #321. +- `__proto__` key no longer overrides object prototype, #164. +- Removed `bower.json`. +- Tags are now url-decoded in `load()` and url-encoded in `dump()` + (previously usage of custom non-ascii tags may have led to invalid YAML that can't be parsed). +- Anchors now work correctly with empty nodes, #301. +- Fix incorrect parsing of invalid block mapping syntax, #418. +- Throw an error if block sequence/mapping indent contains a tab, #80. + + +## [3.14.1] - 2020-12-07 +### Security +- Fix possible code execution in (already unsafe) `.load()` (in &anchor). + + +## [3.14.0] - 2020-05-22 +### Changed +- Support `safe/loadAll(input, options)` variant of call. +- CI: drop outdated nodejs versions. +- Dev deps bump. + +### Fixed +- Quote `=` in plain scalars #519. +- Check the node type for `!` tag in case user manually specifies it. +- Verify that there are no null-bytes in input. +- Fix wrong quote position when writing condensed flow, #526. + + +## [3.13.1] - 2019-04-05 +### Security +- Fix possible code execution in (already unsafe) `.load()`, #480. + + +## [3.13.0] - 2019-03-20 +### Security +- Security fix: `safeLoad()` can hang when arrays with nested refs + used as key. Now throws exception for nested arrays. #475. + + +## [3.12.2] - 2019-02-26 +### Fixed +- Fix `noArrayIndent` option for root level, #468. + + +## [3.12.1] - 2019-01-05 +### Added +- Added `noArrayIndent` option, #432. + + +## [3.12.0] - 2018-06-02 +### Changed +- Support arrow functions without a block statement, #421. + + +## [3.11.0] - 2018-03-05 +### Added +- Add arrow functions suport for `!!js/function`. + +### Fixed +- Fix dump in bin/octal/hex formats for negative integers, #399. + + +## [3.10.0] - 2017-09-10 +### Fixed +- Fix `condenseFlow` output (quote keys for sure, instead of spaces), #371, #370. +- Dump astrals as codepoints instead of surrogate pair, #368. + + +## [3.9.1] - 2017-07-08 +### Fixed +- Ensure stack is present for custom errors in node 7.+, #351. + + +## [3.9.0] - 2017-07-08 +### Added +- Add `condenseFlow` option (to create pretty URL query params), #346. + +### Fixed +- Support array return from safeLoadAll/loadAll, #350. + + +## [3.8.4] - 2017-05-08 +### Fixed +- Dumper: prevent space after dash for arrays that wrap, #343. + + +## [3.8.3] - 2017-04-05 +### Fixed +- Should not allow numbers to begin and end with underscore, #335. + + +## [3.8.2] - 2017-03-02 +### Fixed +- Fix `!!float 123` (integers) parse, #333. +- Don't allow leading zeros in floats (except 0, 0.xxx). +- Allow positive exponent without sign in floats. + + +## [3.8.1] - 2017-02-07 +### Changed +- Maintenance: update browserified build. + + +## [3.8.0] - 2017-02-07 +### Fixed +- Fix reported position for `duplicated mapping key` errors. + Now points to block start instead of block end. + (#243, thanks to @shockey). + + +## [3.7.0] - 2016-11-12 +### Added +- Support polymorphism for tags (#300, thanks to @monken). + +### Fixed +- Fix parsing of quotes followed by newlines (#304, thanks to @dplepage). + + +## [3.6.1] - 2016-05-11 +### Fixed +- Fix output cut on a pipe, #286. + + +## [3.6.0] - 2016-04-16 +### Fixed +- Dumper rewrite, fix multiple bugs with trailing `\n`. + Big thanks to @aepsilon! +- Loader: fix leading/trailing newlines in block scalars, @aepsilon. + + +## [3.5.5] - 2016-03-17 +### Fixed +- Date parse fix: don't allow dates with on digit in month and day, #268. + + +## [3.5.4] - 2016-03-09 +### Added +- `noCompatMode` for dumper, to disable quoting YAML 1.1 values. + + +## [3.5.3] - 2016-02-11 +### Changed +- Maintenance release. + + +## [3.5.2] - 2016-01-11 +### Changed +- Maintenance: missed comma in bower config. + + +## [3.5.1] - 2016-01-11 +### Changed +- Removed `inherit` dependency, #239. +- Better browserify workaround for esprima load. +- Demo rewrite. + + +## [3.5.0] - 2016-01-10 +### Fixed +- Dumper. Fold strings only, #217. +- Dumper. `norefs` option, to clone linked objects, #229. +- Loader. Throw a warning for duplicate keys, #166. +- Improved browserify support (mark `esprima` & `Buffer` excluded). + + +## [3.4.6] - 2015-11-26 +### Changed +- Use standalone `inherit` to keep browserified files clear. + + +## [3.4.5] - 2015-11-23 +### Added +- Added `lineWidth` option to dumper. + + +## [3.4.4] - 2015-11-21 +### Fixed +- Fixed floats dump (missed dot for scientific format), #220. +- Allow non-printable characters inside quoted scalars, #192. + + +## [3.4.3] - 2015-10-10 +### Changed +- Maintenance release - deps bump (esprima, argparse). + + +## [3.4.2] - 2015-09-09 +### Fixed +- Fixed serialization of duplicated entries in sequences, #205. + Thanks to @vogelsgesang. + + +## [3.4.1] - 2015-09-05 +### Fixed +- Fixed stacktrace handling in generated errors, for browsers (FF/IE). + + +## [3.4.0] - 2015-08-23 +### Changed +- Don't throw on warnings anymore. Use `onWarning` option to catch. +- Throw error on unknown tags (was warning before). +- Reworked internals of error class. + +### Fixed +- Fixed multiline keys dump, #197. Thanks to @tcr. +- Fixed heading line breaks in some scalars (regression). + + +## [3.3.1] - 2015-05-13 +### Added +- Added `.sortKeys` dumper option, thanks to @rjmunro. + +### Fixed +- Fixed astral characters support, #191. + + +## [3.3.0] - 2015-04-26 +### Changed +- Significantly improved long strings formatting in dumper, thanks to @isaacs. +- Strip BOM if exists. + + +## [3.2.7] - 2015-02-19 +### Changed +- Maintenance release. +- Updated dependencies. +- HISTORY.md -> CHANGELOG.md + + +## [3.2.6] - 2015-02-07 +### Fixed +- Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE). +- Fixed demo dates dump (#113, thanks to @Hypercubed). + + +## [3.2.5] - 2014-12-28 +### Fixed +- Fixed resolving of all built-in types on empty nodes. +- Fixed invalid warning on empty lines within quoted scalars and flow collections. +- Fixed bug: Tag on an empty node didn't resolve in some cases. + + +## [3.2.4] - 2014-12-19 +### Fixed +- Fixed resolving of !!null tag on an empty node. + + +## [3.2.3] - 2014-11-08 +### Fixed +- Implemented dumping of objects with circular and cross references. +- Partially fixed aliasing of constructed objects. (see issue #141 for details) + + +## [3.2.2] - 2014-09-07 +### Fixed +- Fixed infinite loop on unindented block scalars. +- Rewritten base64 encode/decode in binary type, to keep code licence clear. + + +## [3.2.1] - 2014-08-24 +### Fixed +- Nothig new. Just fix npm publish error. + + +## [3.2.0] - 2014-08-24 +### Added +- Added input piping support to CLI. + +### Fixed +- Fixed typo, that could cause hand on initial indent (#139). + + +## [3.1.0] - 2014-07-07 +### Changed +- 1.5x-2x speed boost. +- Removed deprecated `require('xxx.yml')` support. +- Significant code cleanup and refactoring. +- Internal API changed. If you used custom types - see updated examples. + Others are not affected. +- Even if the input string has no trailing line break character, + it will be parsed as if it has one. +- Added benchmark scripts. +- Moved bower files to /dist folder +- Bugfixes. + + +## [3.0.2] - 2014-02-27 +### Fixed +- Fixed bug: "constructor" string parsed as `null`. + + +## [3.0.1] - 2013-12-22 +### Fixed +- Fixed parsing of literal scalars. (issue #108) +- Prevented adding unnecessary spaces in object dumps. (issue #68) +- Fixed dumping of objects with very long (> 1024 in length) keys. + + +## [3.0.0] - 2013-12-16 +### Changed +- Refactored code. Changed API for custom types. +- Removed output colors in CLI, dump json by default. +- Removed big dependencies from browser version (esprima, buffer). Load `esprima` manually, if `!!js/function` needed. `!!bin` now returns Array in browser +- AMD support. +- Don't quote dumped strings because of `-` & `?` (if not first char). +- __Deprecated__ loading yaml files via `require()`, as not recommended + behaviour for node. + + +## [2.1.3] - 2013-10-16 +### Fixed +- Fix wrong loading of empty block scalars. + + +## [2.1.2] - 2013-10-07 +### Fixed +- Fix unwanted line breaks in folded scalars. + + +## [2.1.1] - 2013-10-02 +### Fixed +- Dumper now respects deprecated booleans syntax from YAML 1.0/1.1 +- Fixed reader bug in JSON-like sequences/mappings. + + +## [2.1.0] - 2013-06-05 +### Added +- Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`), + JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`). +- Add `skipInvalid` dumper option. + +### Changed +- Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA` + and `SAFE_SCHEMA` to `DEFAULT_SAFE_SCHEMA`. +- Use `safeLoad` for `require` extension. + +### Fixed +- Bug fix: export `NIL` constant from the public interface. + + +## [2.0.5] - 2013-04-26 +### Security +- Close security issue in !!js/function constructor. + Big thanks to @nealpoole for security audit. + + +## [2.0.4] - 2013-04-08 +### Changed +- Updated .npmignore to reduce package size + + +## [2.0.3] - 2013-02-26 +### Fixed +- Fixed dumping of empty arrays ans objects. ([] and {} instead of null) + + +## [2.0.2] - 2013-02-15 +### Fixed +- Fixed input validation: tabs are printable characters. + + +## [2.0.1] - 2013-02-09 +### Fixed +- Fixed error, when options not passed to function cass + + +## [2.0.0] - 2013-02-09 +### Changed +- Full rewrite. New architecture. Fast one-stage parsing. +- Changed custom types API. +- Added YAML dumper. + + +## [1.0.3] - 2012-11-05 +### Fixed +- Fixed utf-8 files loading. + + +## [1.0.2] - 2012-08-02 +### Fixed +- Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44. +- Fix timstamps incorectly parsed in local time when no time part specified. + + +## [1.0.1] - 2012-07-07 +### Fixed +- Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong. +- Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46. + + +## [1.0.0] - 2012-07-01 +### Changed +- `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore. + Fixes #42. +- `require(filename)` now returns a single document and throws an Error if + file contains more than one document. +- CLI was merged back from js-yaml.bin + + +## [0.3.7] - 2012-02-28 +### Fixed +- Fix export of `addConstructor()`. Closes #39. + + +## [0.3.6] - 2012-02-22 +### Changed +- Removed AMD parts - too buggy to use. Need help to rewrite from scratch + +### Fixed +- Removed YUI compressor warning (renamed `double` variable). Closes #40. + + +## [0.3.5] - 2012-01-10 +### Fixed +- Workagound for .npmignore fuckup under windows. Thanks to airportyh. + + +## [0.3.4] - 2011-12-24 +### Fixed +- Fixes str[] for oldIEs support. +- Adds better has change support for browserified demo. +- improves compact output of Error. Closes #33. + + +## [0.3.3] - 2011-12-20 +### Added +- adds `compact` stringification of Errors. + +### Changed +- jsyaml executable moved to separate module. + + +## [0.3.2] - 2011-12-16 +### Added +- Added jsyaml executable. +- Added !!js/function support. Closes #12. + +### Fixed +- Fixes ug with block style scalars. Closes #26. +- All sources are passing JSLint now. +- Fixes bug in Safari. Closes #28. +- Fixes bug in Opers. Closes #29. +- Improves browser support. Closes #20. + + +## [0.3.1] - 2011-11-18 +### Added +- Added AMD support for browserified version. +- Added permalinks for online demo YAML snippets. Now we have YPaste service, lol. +- Added !!js/regexp and !!js/undefined types. Partially solves #12. + +### Changed +- Wrapped browserified js-yaml into closure. + +### Fixed +- Fixed the resolvement of non-specific tags. Closes #17. +- Fixed !!set mapping. +- Fixed month parse in dates. Closes #19. + + +## [0.3.0] - 2011-11-09 +### Added +- Added browserified version. Closes #13. +- Added live demo of browserified version. +- Ported some of the PyYAML tests. See #14. + +### Fixed +- Removed JS.Class dependency. Closes #3. +- Fixed timestamp bug when fraction was given. + + +## [0.2.2] - 2011-11-06 +### Fixed +- Fixed crash on docs without ---. Closes #8. +- Fixed multiline string parse +- Fixed tests/comments for using array as key + + +## [0.2.1] - 2011-11-02 +### Fixed +- Fixed short file read (<4k). Closes #9. + + +## [0.2.0] - 2011-11-02 +### Changed +- First public release + + +[4.1.0]: https://github.com/nodeca/js-yaml/compare/4.0.0...4.1.0 +[4.0.0]: https://github.com/nodeca/js-yaml/compare/3.14.0...4.0.0 +[3.14.0]: https://github.com/nodeca/js-yaml/compare/3.13.1...3.14.0 +[3.13.1]: https://github.com/nodeca/js-yaml/compare/3.13.0...3.13.1 +[3.13.0]: https://github.com/nodeca/js-yaml/compare/3.12.2...3.13.0 +[3.12.2]: https://github.com/nodeca/js-yaml/compare/3.12.1...3.12.2 +[3.12.1]: https://github.com/nodeca/js-yaml/compare/3.12.0...3.12.1 +[3.12.0]: https://github.com/nodeca/js-yaml/compare/3.11.0...3.12.0 +[3.11.0]: https://github.com/nodeca/js-yaml/compare/3.10.0...3.11.0 +[3.10.0]: https://github.com/nodeca/js-yaml/compare/3.9.1...3.10.0 +[3.9.1]: https://github.com/nodeca/js-yaml/compare/3.9.0...3.9.1 +[3.9.0]: https://github.com/nodeca/js-yaml/compare/3.8.4...3.9.0 +[3.8.4]: https://github.com/nodeca/js-yaml/compare/3.8.3...3.8.4 +[3.8.3]: https://github.com/nodeca/js-yaml/compare/3.8.2...3.8.3 +[3.8.2]: https://github.com/nodeca/js-yaml/compare/3.8.1...3.8.2 +[3.8.1]: https://github.com/nodeca/js-yaml/compare/3.8.0...3.8.1 +[3.8.0]: https://github.com/nodeca/js-yaml/compare/3.7.0...3.8.0 +[3.7.0]: https://github.com/nodeca/js-yaml/compare/3.6.1...3.7.0 +[3.6.1]: https://github.com/nodeca/js-yaml/compare/3.6.0...3.6.1 +[3.6.0]: https://github.com/nodeca/js-yaml/compare/3.5.5...3.6.0 +[3.5.5]: https://github.com/nodeca/js-yaml/compare/3.5.4...3.5.5 +[3.5.4]: https://github.com/nodeca/js-yaml/compare/3.5.3...3.5.4 +[3.5.3]: https://github.com/nodeca/js-yaml/compare/3.5.2...3.5.3 +[3.5.2]: https://github.com/nodeca/js-yaml/compare/3.5.1...3.5.2 +[3.5.1]: https://github.com/nodeca/js-yaml/compare/3.5.0...3.5.1 +[3.5.0]: https://github.com/nodeca/js-yaml/compare/3.4.6...3.5.0 +[3.4.6]: https://github.com/nodeca/js-yaml/compare/3.4.5...3.4.6 +[3.4.5]: https://github.com/nodeca/js-yaml/compare/3.4.4...3.4.5 +[3.4.4]: https://github.com/nodeca/js-yaml/compare/3.4.3...3.4.4 +[3.4.3]: https://github.com/nodeca/js-yaml/compare/3.4.2...3.4.3 +[3.4.2]: https://github.com/nodeca/js-yaml/compare/3.4.1...3.4.2 +[3.4.1]: https://github.com/nodeca/js-yaml/compare/3.4.0...3.4.1 +[3.4.0]: https://github.com/nodeca/js-yaml/compare/3.3.1...3.4.0 +[3.3.1]: https://github.com/nodeca/js-yaml/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/nodeca/js-yaml/compare/3.2.7...3.3.0 +[3.2.7]: https://github.com/nodeca/js-yaml/compare/3.2.6...3.2.7 +[3.2.6]: https://github.com/nodeca/js-yaml/compare/3.2.5...3.2.6 +[3.2.5]: https://github.com/nodeca/js-yaml/compare/3.2.4...3.2.5 +[3.2.4]: https://github.com/nodeca/js-yaml/compare/3.2.3...3.2.4 +[3.2.3]: https://github.com/nodeca/js-yaml/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/nodeca/js-yaml/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/nodeca/js-yaml/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/nodeca/js-yaml/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/nodeca/js-yaml/compare/3.0.2...3.1.0 +[3.0.2]: https://github.com/nodeca/js-yaml/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/nodeca/js-yaml/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/nodeca/js-yaml/compare/2.1.3...3.0.0 +[2.1.3]: https://github.com/nodeca/js-yaml/compare/2.1.2...2.1.3 +[2.1.2]: https://github.com/nodeca/js-yaml/compare/2.1.1...2.1.2 +[2.1.1]: https://github.com/nodeca/js-yaml/compare/2.1.0...2.1.1 +[2.1.0]: https://github.com/nodeca/js-yaml/compare/2.0.5...2.1.0 +[2.0.5]: https://github.com/nodeca/js-yaml/compare/2.0.4...2.0.5 +[2.0.4]: https://github.com/nodeca/js-yaml/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/nodeca/js-yaml/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/nodeca/js-yaml/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/nodeca/js-yaml/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/nodeca/js-yaml/compare/1.0.3...2.0.0 +[1.0.3]: https://github.com/nodeca/js-yaml/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/js-yaml/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/js-yaml/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/js-yaml/compare/0.3.7...1.0.0 +[0.3.7]: https://github.com/nodeca/js-yaml/compare/0.3.6...0.3.7 +[0.3.6]: https://github.com/nodeca/js-yaml/compare/0.3.5...0.3.6 +[0.3.5]: https://github.com/nodeca/js-yaml/compare/0.3.4...0.3.5 +[0.3.4]: https://github.com/nodeca/js-yaml/compare/0.3.3...0.3.4 +[0.3.3]: https://github.com/nodeca/js-yaml/compare/0.3.2...0.3.3 +[0.3.2]: https://github.com/nodeca/js-yaml/compare/0.3.1...0.3.2 +[0.3.1]: https://github.com/nodeca/js-yaml/compare/0.3.0...0.3.1 +[0.3.0]: https://github.com/nodeca/js-yaml/compare/0.2.2...0.3.0 +[0.2.2]: https://github.com/nodeca/js-yaml/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/nodeca/js-yaml/compare/0.2.0...0.2.1 +[0.2.0]: https://github.com/nodeca/js-yaml/releases/tag/0.2.0 diff --git a/node_modules/eslint/node_modules/js-yaml/LICENSE b/node_modules/eslint/node_modules/js-yaml/LICENSE new file mode 100644 index 0000000..09d3a29 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2011-2015 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/eslint/node_modules/js-yaml/README.md b/node_modules/eslint/node_modules/js-yaml/README.md new file mode 100644 index 0000000..3cbc4bd --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/README.md @@ -0,0 +1,246 @@ +JS-YAML - YAML 1.2 parser / writer for JavaScript +================================================= + +[![CI](https://github.com/nodeca/js-yaml/workflows/CI/badge.svg?branch=master)](https://github.com/nodeca/js-yaml/actions) +[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) + +__[Online Demo](http://nodeca.github.com/js-yaml/)__ + + +This is an implementation of [YAML](http://yaml.org/), a human-friendly data +serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was +completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. + + +Installation +------------ + +### YAML module for node.js + +``` +npm install js-yaml +``` + + +### CLI executable + +If you want to inspect your YAML files from CLI, install js-yaml globally: + +``` +npm install -g js-yaml +``` + +#### Usage + +``` +usage: js-yaml [-h] [-v] [-c] [-t] file + +Positional arguments: + file File with YAML document(s) + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -c, --compact Display errors in compact mode + -t, --trace Show stack trace on error +``` + + +API +--- + +Here we cover the most 'useful' methods. If you need advanced details (creating +your own tags), see [examples](https://github.com/nodeca/js-yaml/tree/master/examples) +for more info. + +``` javascript +const yaml = require('js-yaml'); +const fs = require('fs'); + +// Get document, or throw exception on error +try { + const doc = yaml.load(fs.readFileSync('/home/ixti/example.yml', 'utf8')); + console.log(doc); +} catch (e) { + console.log(e); +} +``` + + +### load (string [ , options ]) + +Parses `string` as single YAML document. Returns either a +plain object, a string, a number, `null` or `undefined`, or throws `YAMLException` on error. By default, does +not support regexps, functions and undefined. + +options: + +- `filename` _(default: null)_ - string to be used as a file path in + error/warning messages. +- `onWarning` _(default: null)_ - function to call on warning messages. + Loader will call this function with an instance of `YAMLException` for each warning. +- `schema` _(default: `DEFAULT_SCHEMA`)_ - specifies a schema to use. + - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: + http://www.yaml.org/spec/1.2/spec.html#id2802346 + - `JSON_SCHEMA` - all JSON-supported types: + http://www.yaml.org/spec/1.2/spec.html#id2803231 + - `CORE_SCHEMA` - same as `JSON_SCHEMA`: + http://www.yaml.org/spec/1.2/spec.html#id2804923 + - `DEFAULT_SCHEMA` - all supported YAML types. +- `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. + +NOTE: This function **does not** understand multi-document sources, it throws +exception on those. + +NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. +So, the JSON schema is not as strictly defined in the YAML specification. +It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. +The core schema also has no such restrictions. It allows binary notation for integers. + + +### loadAll (string [, iterator] [, options ]) + +Same as `load()`, but understands multi-document sources. Applies +`iterator` to each document if specified, or returns array of documents. + +``` javascript +const yaml = require('js-yaml'); + +yaml.loadAll(data, function (doc) { + console.log(doc); +}); +``` + + +### dump (object [ , options ]) + +Serializes `object` as a YAML document. Uses `DEFAULT_SCHEMA`, so it will +throw an exception if you try to dump regexps or functions. However, you can +disable exceptions by setting the `skipInvalid` option to `true`. + +options: + +- `indent` _(default: 2)_ - indentation width to use (in spaces). +- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements +- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function + in the safe schema) and skip pairs and single values with such types. +- `flowLevel` _(default: -1)_ - specifies level of nesting, when to switch from + block to flow style for collections. -1 means block style everwhere +- `styles` - "tag" => "style" map. Each tag may have own set of styles. +- `schema` _(default: `DEFAULT_SCHEMA`)_ specifies a schema to use. +- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a + function, use the function to sort the keys. +- `lineWidth` _(default: `80`)_ - set max line width. Set `-1` for unlimited width. +- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references +- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older + yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 +- `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. +- `quotingType` _(`'` or `"`, default: `'`)_ - strings will be quoted using this quoting style. If you specify single quotes, double quotes will still be used for non-printable characters. +- `forceQuotes` _(default: `false`)_ - if `true`, all non-key strings will be quoted even if they normally don't need to. +- `replacer` - callback `function (key, value)` called recursively on each key/value in source object (see `replacer` docs for `JSON.stringify`). + +The following table show availlable styles (e.g. "canonical", +"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml +output is shown on the right side after `=>` (default setting) or `->`: + +``` none +!!null + "canonical" -> "~" + "lowercase" => "null" + "uppercase" -> "NULL" + "camelcase" -> "Null" + +!!int + "binary" -> "0b1", "0b101010", "0b1110001111010" + "octal" -> "0o1", "0o52", "0o16172" + "decimal" => "1", "42", "7290" + "hexadecimal" -> "0x1", "0x2A", "0x1C7A" + +!!bool + "lowercase" => "true", "false" + "uppercase" -> "TRUE", "FALSE" + "camelcase" -> "True", "False" + +!!float + "lowercase" => ".nan", '.inf' + "uppercase" -> ".NAN", '.INF' + "camelcase" -> ".NaN", '.Inf' +``` + +Example: + +``` javascript +dump(object, { + 'styles': { + '!!null': 'canonical' // dump null as ~ + }, + 'sortKeys': true // sort object keys +}); +``` + +Supported YAML types +-------------------- + +The list of standard YAML tags and corresponding JavaScript types. See also +[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and +[YAML types repository](http://yaml.org/type/). + +``` +!!null '' # null +!!bool 'yes' # bool +!!int '3...' # number +!!float '3.14...' # number +!!binary '...base64...' # buffer +!!timestamp 'YYYY-...' # date +!!omap [ ... ] # array of key-value pairs +!!pairs [ ... ] # array or array pairs +!!set { ... } # array of objects with given keys and null values +!!str '...' # string +!!seq [ ... ] # array +!!map { ... } # object +``` + +**JavaScript-specific tags** + +See [js-yaml-js-types](https://github.com/nodeca/js-yaml-js-types) for +extra types. + + +Caveats +------- + +Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects +or arrays as keys, and stringifies (by calling `toString()` method) them at the +moment of adding them. + +``` yaml +--- +? [ foo, bar ] +: - baz +? { foo: bar } +: - baz + - baz +``` + +``` javascript +{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } +``` + +Also, reading of properties on implicit block mapping keys is not supported yet. +So, the following YAML document cannot be loaded. + +``` yaml +&anchor foo: + foo: bar + *anchor: duplicate key + baz: bat + *anchor: duplicate key +``` + + +js-yaml for enterprise +---------------------- + +Available as part of the Tidelift Subscription + +The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/eslint/node_modules/js-yaml/bin/js-yaml.js b/node_modules/eslint/node_modules/js-yaml/bin/js-yaml.js new file mode 100755 index 0000000..a182f1a --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/bin/js-yaml.js @@ -0,0 +1,126 @@ +#!/usr/bin/env node + + +'use strict'; + +/*eslint-disable no-console*/ + + +var fs = require('fs'); +var argparse = require('argparse'); +var yaml = require('..'); + + +//////////////////////////////////////////////////////////////////////////////// + + +var cli = new argparse.ArgumentParser({ + prog: 'js-yaml', + add_help: true +}); + +cli.add_argument('-v', '--version', { + action: 'version', + version: require('../package.json').version +}); + +cli.add_argument('-c', '--compact', { + help: 'Display errors in compact mode', + action: 'store_true' +}); + +// deprecated (not needed after we removed output colors) +// option suppressed, but not completely removed for compatibility +cli.add_argument('-j', '--to-json', { + help: argparse.SUPPRESS, + dest: 'json', + action: 'store_true' +}); + +cli.add_argument('-t', '--trace', { + help: 'Show stack trace on error', + action: 'store_true' +}); + +cli.add_argument('file', { + help: 'File to read, utf-8 encoded without BOM', + nargs: '?', + default: '-' +}); + + +//////////////////////////////////////////////////////////////////////////////// + + +var options = cli.parse_args(); + + +//////////////////////////////////////////////////////////////////////////////// + +function readFile(filename, encoding, callback) { + if (options.file === '-') { + // read from stdin + + var chunks = []; + + process.stdin.on('data', function (chunk) { + chunks.push(chunk); + }); + + process.stdin.on('end', function () { + return callback(null, Buffer.concat(chunks).toString(encoding)); + }); + } else { + fs.readFile(filename, encoding, callback); + } +} + +readFile(options.file, 'utf8', function (error, input) { + var output, isYaml; + + if (error) { + if (error.code === 'ENOENT') { + console.error('File not found: ' + options.file); + process.exit(2); + } + + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + + try { + output = JSON.parse(input); + isYaml = false; + } catch (err) { + if (err instanceof SyntaxError) { + try { + output = []; + yaml.loadAll(input, function (doc) { output.push(doc); }, {}); + isYaml = true; + + if (output.length === 0) output = null; + else if (output.length === 1) output = output[0]; + + } catch (e) { + if (options.trace && err.stack) console.error(e.stack); + else console.error(e.toString(options.compact)); + + process.exit(1); + } + } else { + console.error( + options.trace && err.stack || + err.message || + String(err)); + + process.exit(1); + } + } + + if (isYaml) console.log(JSON.stringify(output, null, ' ')); + else console.log(yaml.dump(output)); +}); diff --git a/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.js b/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.js new file mode 100644 index 0000000..4cc0ddf --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.js @@ -0,0 +1,3874 @@ + +/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jsyaml = {})); +}(this, (function (exports) { 'use strict'; + + function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); + } + + + function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); + } + + + function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; + } + + + function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; + } + + + function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; + } + + + function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); + } + + + var isNothing_1 = isNothing; + var isObject_1 = isObject; + var toArray_1 = toArray; + var repeat_1 = repeat; + var isNegativeZero_1 = isNegativeZero; + var extend_1 = extend; + + var common = { + isNothing: isNothing_1, + isObject: isObject_1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 + }; + + // YAML error class. http://stackoverflow.com/questions/8458984 + + + function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; + + if (!exception.mark) return message; + + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } + + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } + + return message + ' ' + where; + } + + + function YAMLException$1(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } + } + + + // Inherit from Error + YAMLException$1.prototype = Object.create(Error.prototype); + YAMLException$1.prototype.constructor = YAMLException$1; + + + YAMLException$1.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); + }; + + + var exception = YAMLException$1; + + // get snippet for a single line, respecting maxLength + function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; + } + + + function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; + } + + + function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); + } + + + var snippet = makeSnippet; + + var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' + ]; + + var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' + ]; + + function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; + } + + function Type$1(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } + } + + var type = Type$1; + + /*eslint-disable max-len*/ + + + + + + function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; + } + + + function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; + } + + + function Schema$1(definition) { + return this.extend(definition); + } + + + Schema$1.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new exception('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type$1.loadKind && type$1.loadKind !== 'scalar') { + throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type$1.multi) { + throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema$1.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; + }; + + + var schema = Schema$1; + + var str = new type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } + }); + + var seq = new type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } + }); + + var map = new type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } + }); + + var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] + }); + + function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); + } + + function constructYamlNull() { + return null; + } + + function isNull(object) { + return object === null; + } + + var _null = new type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' + }); + + function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); + } + + function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; + } + + function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; + } + + var bool = new type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' + }); + + function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); + } + + function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); + } + + function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); + } + + function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; + } + + function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); + } + + function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); + } + + var int = new type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } + }); + + var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + + function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; + } + + function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); + } + + + var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + + function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; + } + + function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); + } + + var float = new type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' + }); + + var json = failsafe.extend({ + implicit: [ + _null, + bool, + int, + float + ] + }); + + var core = json; + + var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + + var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + + function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; + } + + function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; + } + + function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); + } + + var timestamp = new type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp + }); + + function resolveYamlMerge(data) { + return data === '<<' || data === null; + } + + var merge = new type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge + }); + + /*eslint-disable no-bitwise*/ + + + + + + // [ 64, 65, 66 ] -> [ padding, CR, LF ] + var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + + function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; + } + + function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); + } + + function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; + } + + function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; + } + + var binary = new type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary + }); + + var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; + var _toString$2 = Object.prototype.toString; + + function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString$2.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty$3.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; + } + + function constructYamlOmap(data) { + return data !== null ? data : []; + } + + var omap = new type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap + }); + + var _toString$1 = Object.prototype.toString; + + function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString$1.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; + } + + function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; + } + + var pairs = new type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs + }); + + var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + + function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$2.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; + } + + function constructYamlSet(data) { + return data !== null ? data : {}; + } + + var set = new type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet + }); + + var _default = core.extend({ + implicit: [ + timestamp, + merge + ], + explicit: [ + binary, + omap, + pairs, + set + ] + }); + + /*eslint-disable max-len,no-use-before-define*/ + + + + + + + + var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + + + var CONTEXT_FLOW_IN = 1; + var CONTEXT_FLOW_OUT = 2; + var CONTEXT_BLOCK_IN = 3; + var CONTEXT_BLOCK_OUT = 4; + + + var CHOMPING_CLIP = 1; + var CHOMPING_STRIP = 2; + var CHOMPING_KEEP = 3; + + + var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; + var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; + var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; + var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + + function _class(obj) { return Object.prototype.toString.call(obj); } + + function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); + } + + function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); + } + + function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); + } + + function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; + } + + function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; + } + + function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; + } + + function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; + } + + function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; + } + + function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); + } + + var simpleEscapeCheck = new Array(256); // integer, for fast access + var simpleEscapeMap = new Array(256); + for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); + } + + + function State$1(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || _default; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + + } + + + function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = snippet(mark); + + return new exception(message, mark); + } + + function throwError(state, message) { + throw generateError(state, message); + } + + function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } + } + + + var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$1.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } + }; + + + function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } + } + + function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty$1.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } + } + + function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$1.call(overridableKeys, keyNode) && + _hasOwnProperty$1.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } + + return _result; + } + + function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; + } + + function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; + } + + function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; + } + + function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } + } + + + function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; + } + + function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); + } + + function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); + } + + function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); + } + + function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; + } + + function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; + } + + function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; + } + + function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; + } + + function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; + } + + function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; + } + + function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; + } + + function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } + } + + + function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State$1(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; + } + + + function loadAll$1(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } + } + + + function load$1(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception('expected a single document in the stream, but found more'); + } + + + var loadAll_1 = loadAll$1; + var load_1 = load$1; + + var loader = { + loadAll: loadAll_1, + load: load_1 + }; + + /*eslint-disable no-use-before-define*/ + + + + + + var _toString = Object.prototype.toString; + var _hasOwnProperty = Object.prototype.hasOwnProperty; + + var CHAR_BOM = 0xFEFF; + var CHAR_TAB = 0x09; /* Tab */ + var CHAR_LINE_FEED = 0x0A; /* LF */ + var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ + var CHAR_SPACE = 0x20; /* Space */ + var CHAR_EXCLAMATION = 0x21; /* ! */ + var CHAR_DOUBLE_QUOTE = 0x22; /* " */ + var CHAR_SHARP = 0x23; /* # */ + var CHAR_PERCENT = 0x25; /* % */ + var CHAR_AMPERSAND = 0x26; /* & */ + var CHAR_SINGLE_QUOTE = 0x27; /* ' */ + var CHAR_ASTERISK = 0x2A; /* * */ + var CHAR_COMMA = 0x2C; /* , */ + var CHAR_MINUS = 0x2D; /* - */ + var CHAR_COLON = 0x3A; /* : */ + var CHAR_EQUALS = 0x3D; /* = */ + var CHAR_GREATER_THAN = 0x3E; /* > */ + var CHAR_QUESTION = 0x3F; /* ? */ + var CHAR_COMMERCIAL_AT = 0x40; /* @ */ + var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ + var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ + var CHAR_GRAVE_ACCENT = 0x60; /* ` */ + var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ + var CHAR_VERTICAL_LINE = 0x7C; /* | */ + var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + + var ESCAPE_SEQUENCES = {}; + + ESCAPE_SEQUENCES[0x00] = '\\0'; + ESCAPE_SEQUENCES[0x07] = '\\a'; + ESCAPE_SEQUENCES[0x08] = '\\b'; + ESCAPE_SEQUENCES[0x09] = '\\t'; + ESCAPE_SEQUENCES[0x0A] = '\\n'; + ESCAPE_SEQUENCES[0x0B] = '\\v'; + ESCAPE_SEQUENCES[0x0C] = '\\f'; + ESCAPE_SEQUENCES[0x0D] = '\\r'; + ESCAPE_SEQUENCES[0x1B] = '\\e'; + ESCAPE_SEQUENCES[0x22] = '\\"'; + ESCAPE_SEQUENCES[0x5C] = '\\\\'; + ESCAPE_SEQUENCES[0x85] = '\\N'; + ESCAPE_SEQUENCES[0xA0] = '\\_'; + ESCAPE_SEQUENCES[0x2028] = '\\L'; + ESCAPE_SEQUENCES[0x2029] = '\\P'; + + var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' + ]; + + var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + + function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; + } + + function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; + } + + + var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + + function State(options) { + this.schema = options['schema'] || _default; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; + } + + // Indents every line in a string. Empty lines (\n only) are not indented. + function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; + } + + function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); + } + + function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; + } + + // [33] s-white ::= s-space | s-tab + function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; + } + + // Returns true if the character can be printed without escaping. + // From YAML 1.2: "any allowed characters known to be non-printable + // should also be escaped. [However,] This isn’t mandatory" + // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. + function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); + } + + // [34] ns-char ::= nb-char - s-white + // [27] nb-char ::= c-printable - b-char - c-byte-order-mark + // [26] b-char ::= b-line-feed | b-carriage-return + // Including s-white (for some reason, examples doesn't match specs in this aspect) + // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark + function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; + } + + // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out + // c = flow-in ⇒ ns-plain-safe-in + // c = block-key ⇒ ns-plain-safe-out + // c = flow-key ⇒ ns-plain-safe-in + // [128] ns-plain-safe-out ::= ns-char + // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator + // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) + // | ( /* An ns-char preceding */ “#” ) + // | ( “:” /* Followed by an ns-plain-safe(c) */ ) + function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' + } + + // Simplified test for values allowed as the first character in plain style. + function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; + } + + // Simplified test for values allowed as the last character in plain style. + function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; + } + + // Same as 'string'.codePointAt(pos), but works in older browsers. + function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; + } + + // Determines whether block indentation indicator is required. + function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); + } + + var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + + // Determines which scalar styles are possible and returns the preferred style. + // lineWidth = -1 => no limit. + // Pre-conditions: str.length > 0. + // Post-conditions: + // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. + // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). + // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). + function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + + // Note: line breaking/folding is implemented for only the folded style. + // NB. We drop the last trailing newline (if any) of a returned block scalar + // since the dumper adds its own newline. This always works: + // • No ending newline => unaffected; already using strip "-" chomping. + // • Ending newline => removed then restored. + // Importantly, this keeps the "+" chomp indicator from gaining an extra line. + function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string) + '"'; + default: + throw new exception('impossible error: invalid scalar style'); + } + }()); + } + + // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. + function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; + } + + // (See the note for writeScalar.) + function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; + } + + // Note: a long line without a suitable break point will exceed the width limit. + // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. + function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; + } + + // Greedy line breaking. + // Picks the longest line under the limit each time, + // otherwise settles for the shortest line over the limit. + // NB. More-indented lines *cannot* be folded, as that would add an extra \n. + function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner + } + + // Escapes a double-quoted string. + function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } + + return result; + } + + function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; + } + + function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. + } + + function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; + } + + function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new exception('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. + } + + function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; + } + + // Serializes `object` and writes it to global `result`. + // Returns true on success, or false on invalid object. + // + function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new exception('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; + } + + function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); + } + + function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } + } + + function dump$1(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; + } + + var dump_1 = dump$1; + + var dumper = { + dump: dump_1 + }; + + function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; + } + + + var Type = type; + var Schema = schema; + var FAILSAFE_SCHEMA = failsafe; + var JSON_SCHEMA = json; + var CORE_SCHEMA = core; + var DEFAULT_SCHEMA = _default; + var load = loader.load; + var loadAll = loader.loadAll; + var dump = dumper.dump; + var YAMLException = exception; + + // Re-export all types in case user wants to create custom schema + var types = { + binary: binary, + float: float, + map: map, + null: _null, + pairs: pairs, + set: set, + timestamp: timestamp, + bool: bool, + int: int, + merge: merge, + omap: omap, + seq: seq, + str: str + }; + + // Removed functions from JS-YAML 3.0.x + var safeLoad = renamed('safeLoad', 'load'); + var safeLoadAll = renamed('safeLoadAll', 'loadAll'); + var safeDump = renamed('safeDump', 'dump'); + + var jsYaml = { + Type: Type, + Schema: Schema, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA, + load: load, + loadAll: loadAll, + dump: dump, + YAMLException: YAMLException, + types: types, + safeLoad: safeLoad, + safeLoadAll: safeLoadAll, + safeDump: safeDump + }; + + exports.CORE_SCHEMA = CORE_SCHEMA; + exports.DEFAULT_SCHEMA = DEFAULT_SCHEMA; + exports.FAILSAFE_SCHEMA = FAILSAFE_SCHEMA; + exports.JSON_SCHEMA = JSON_SCHEMA; + exports.Schema = Schema; + exports.Type = Type; + exports.YAMLException = YAMLException; + exports.default = jsYaml; + exports.dump = dump; + exports.load = load; + exports.loadAll = loadAll; + exports.safeDump = safeDump; + exports.safeLoad = safeLoad; + exports.safeLoadAll = safeLoadAll; + exports.types = types; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.min.js b/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.min.js new file mode 100644 index 0000000..bdd8eef --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.min.js @@ -0,0 +1,2 @@ +/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).jsyaml={})}(this,(function(e){"use strict";function t(e){return null==e}var n={isNothing:t,isObject:function(e){return"object"==typeof e&&null!==e},toArray:function(e){return Array.isArray(e)?e:t(e)?[]:[e]},repeat:function(e,t){var n,i="";for(n=0;nl&&(t=i-l+(o=" ... ").length),n-i>l&&(n=i+l-(a=" ...").length),{str:o+e.slice(t,n).replace(/\t/g,"→")+a,pos:i-t+o.length}}function l(e,t){return n.repeat(" ",t-e.length)+e}var c=function(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),"number"!=typeof t.indent&&(t.indent=1),"number"!=typeof t.linesBefore&&(t.linesBefore=3),"number"!=typeof t.linesAfter&&(t.linesAfter=2);for(var i,r=/\r?\n|\r|\0/g,o=[0],c=[],s=-1;i=r.exec(e.buffer);)c.push(i.index),o.push(i.index+i[0].length),e.position<=i.index&&s<0&&(s=o.length-2);s<0&&(s=o.length-1);var u,p,f="",d=Math.min(e.line+t.linesAfter,c.length).toString().length,h=t.maxLength-(t.indent+d+3);for(u=1;u<=t.linesBefore&&!(s-u<0);u++)p=a(e.buffer,o[s-u],c[s-u],e.position-(o[s]-o[s-u]),h),f=n.repeat(" ",t.indent)+l((e.line-u+1).toString(),d)+" | "+p.str+"\n"+f;for(p=a(e.buffer,o[s],c[s],e.position,h),f+=n.repeat(" ",t.indent)+l((e.line+1).toString(),d)+" | "+p.str+"\n",f+=n.repeat("-",t.indent+d+3+p.pos)+"^\n",u=1;u<=t.linesAfter&&!(s+u>=c.length);u++)p=a(e.buffer,o[s+u],c[s+u],e.position-(o[s]-o[s+u]),h),f+=n.repeat(" ",t.indent)+l((e.line+u+1).toString(),d)+" | "+p.str+"\n";return f.replace(/\n$/,"")},s=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],u=["scalar","sequence","mapping"];var p=function(e,t){if(t=t||{},Object.keys(t).forEach((function(t){if(-1===s.indexOf(t))throw new o('Unknown option "'+t+'" is met in definition of "'+e+'" YAML type.')})),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=function(e){var t={};return null!==e&&Object.keys(e).forEach((function(n){e[n].forEach((function(e){t[String(e)]=n}))})),t}(t.styleAliases||null),-1===u.indexOf(this.kind))throw new o('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')};function f(e,t){var n=[];return e[t].forEach((function(e){var t=n.length;n.forEach((function(n,i){n.tag===e.tag&&n.kind===e.kind&&n.multi===e.multi&&(t=i)})),n[t]=e})),n}function d(e){return this.extend(e)}d.prototype.extend=function(e){var t=[],n=[];if(e instanceof p)n.push(e);else if(Array.isArray(e))n=n.concat(e);else{if(!e||!Array.isArray(e.implicit)&&!Array.isArray(e.explicit))throw new o("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");e.implicit&&(t=t.concat(e.implicit)),e.explicit&&(n=n.concat(e.explicit))}t.forEach((function(e){if(!(e instanceof p))throw new o("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(e.multi)throw new o("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")})),n.forEach((function(e){if(!(e instanceof p))throw new o("Specified list of YAML types (or a single Type object) contains a non-Type object.")}));var i=Object.create(d.prototype);return i.implicit=(this.implicit||[]).concat(t),i.explicit=(this.explicit||[]).concat(n),i.compiledImplicit=f(i,"implicit"),i.compiledExplicit=f(i,"explicit"),i.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function i(e){e.multi?(n.multi[e.kind].push(e),n.multi.fallback.push(e)):n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),x=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var I=/^[-+]?[0-9]+e/;var S=new p("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!x.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,"+-".indexOf(t[0])>=0&&(t=t.slice(1)),".inf"===t?1===n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||n.isNegativeZero(e))},represent:function(e,t){var i;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(n.isNegativeZero(e))return"-0.0";return i=e.toString(10),I.test(i)?i.replace("e",".e"):i},defaultStyle:"lowercase"}),O=b.extend({implicit:[A,v,C,S]}),j=O,T=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),N=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");var F=new p("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(e){return null!==e&&(null!==T.exec(e)||null!==N.exec(e))},construct:function(e){var t,n,i,r,o,a,l,c,s=0,u=null;if(null===(t=T.exec(e))&&(t=N.exec(e)),null===t)throw new Error("Date resolve error");if(n=+t[1],i=+t[2]-1,r=+t[3],!t[4])return new Date(Date.UTC(n,i,r));if(o=+t[4],a=+t[5],l=+t[6],t[7]){for(s=t[7].slice(0,3);s.length<3;)s+="0";s=+s}return t[9]&&(u=6e4*(60*+t[10]+ +(t[11]||0)),"-"===t[9]&&(u=-u)),c=new Date(Date.UTC(n,i,r,o,a,l,s)),u&&c.setTime(c.getTime()-u),c},instanceOf:Date,represent:function(e){return e.toISOString()}});var E=new p("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(e){return"<<"===e||null===e}}),M="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";var L=new p("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i=0,r=e.length,o=M;for(n=0;n64)){if(t<0)return!1;i+=6}return i%8==0},construct:function(e){var t,n,i=e.replace(/[\r\n=]/g,""),r=i.length,o=M,a=0,l=[];for(t=0;t>16&255),l.push(a>>8&255),l.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0===(n=r%4*6)?(l.push(a>>16&255),l.push(a>>8&255),l.push(255&a)):18===n?(l.push(a>>10&255),l.push(a>>2&255)):12===n&&l.push(a>>4&255),new Uint8Array(l)},predicate:function(e){return"[object Uint8Array]"===Object.prototype.toString.call(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=M;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0===(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2===n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1===n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}}),_=Object.prototype.hasOwnProperty,D=Object.prototype.toString;var U=new p("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(e){if(null===e)return!0;var t,n,i,r,o,a=[],l=e;for(t=0,n=l.length;t>10),56320+(e-65536&1023))}for(var ie=new Array(256),re=new Array(256),oe=0;oe<256;oe++)ie[oe]=te(oe)?1:0,re[oe]=te(oe);function ae(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||K,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function le(e,t){var n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=c(n),new o(t,n)}function ce(e,t){throw le(e,t)}function se(e,t){e.onWarning&&e.onWarning.call(null,le(e,t))}var ue={YAML:function(e,t,n){var i,r,o;null!==e.version&&ce(e,"duplication of %YAML directive"),1!==n.length&&ce(e,"YAML directive accepts exactly one argument"),null===(i=/^([0-9]+)\.([0-9]+)$/.exec(n[0]))&&ce(e,"ill-formed argument of the YAML directive"),r=parseInt(i[1],10),o=parseInt(i[2],10),1!==r&&ce(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=o<2,1!==o&&2!==o&&se(e,"unsupported YAML version of the document")},TAG:function(e,t,n){var i,r;2!==n.length&&ce(e,"TAG directive accepts exactly two arguments"),i=n[0],r=n[1],G.test(i)||ce(e,"ill-formed tag handle (first argument) of the TAG directive"),P.call(e.tagMap,i)&&ce(e,'there is a previously declared suffix for "'+i+'" tag handle'),V.test(r)||ce(e,"ill-formed tag prefix (second argument) of the TAG directive");try{r=decodeURIComponent(r)}catch(t){ce(e,"tag prefix is malformed: "+r)}e.tagMap[i]=r}};function pe(e,t,n,i){var r,o,a,l;if(t1&&(e.result+=n.repeat("\n",t-1))}function be(e,t){var n,i,r=e.tag,o=e.anchor,a=[],l=!1;if(-1!==e.firstTabInLine)return!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);0!==i&&(-1!==e.firstTabInLine&&(e.position=e.firstTabInLine,ce(e,"tab characters must not be used in indentation")),45===i)&&z(e.input.charCodeAt(e.position+1));)if(l=!0,e.position++,ge(e,!0,-1)&&e.lineIndent<=t)a.push(null),i=e.input.charCodeAt(e.position);else if(n=e.line,we(e,t,3,!1,!0),a.push(e.result),ge(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==i)ce(e,"bad indentation of a sequence entry");else if(e.lineIndentt?g=1:e.lineIndent===t?g=0:e.lineIndentt?g=1:e.lineIndent===t?g=0:e.lineIndentt)&&(y&&(a=e.line,l=e.lineStart,c=e.position),we(e,t,4,!0,r)&&(y?g=e.result:m=e.result),y||(de(e,f,d,h,g,m,a,l,c),h=g=m=null),ge(e,!0,-1),s=e.input.charCodeAt(e.position)),(e.line===o||e.lineIndent>t)&&0!==s)ce(e,"bad indentation of a mapping entry");else if(e.lineIndent=0))break;0===o?ce(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):u?ce(e,"repeat of an indentation width identifier"):(p=t+o-1,u=!0)}if(Q(a)){do{a=e.input.charCodeAt(++e.position)}while(Q(a));if(35===a)do{a=e.input.charCodeAt(++e.position)}while(!J(a)&&0!==a)}for(;0!==a;){for(he(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!u||e.lineIndentp&&(p=e.lineIndent),J(a))f++;else{if(e.lineIndent0){for(r=a,o=0;r>0;r--)(a=ee(l=e.input.charCodeAt(++e.position)))>=0?o=(o<<4)+a:ce(e,"expected hexadecimal character");e.result+=ne(o),e.position++}else ce(e,"unknown escape sequence");n=i=e.position}else J(l)?(pe(e,n,i,!0),ye(e,ge(e,!1,t)),n=i=e.position):e.position===e.lineStart&&me(e)?ce(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}ce(e,"unexpected end of the stream within a double quoted scalar")}(e,d)?y=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!z(i)&&!X(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&ce(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),P.call(e.anchorMap,n)||ce(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],ge(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,l,c,s,u,p=e.kind,f=e.result;if(z(u=e.input.charCodeAt(e.position))||X(u)||35===u||38===u||42===u||33===u||124===u||62===u||39===u||34===u||37===u||64===u||96===u)return!1;if((63===u||45===u)&&(z(i=e.input.charCodeAt(e.position+1))||n&&X(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==u;){if(58===u){if(z(i=e.input.charCodeAt(e.position+1))||n&&X(i))break}else if(35===u){if(z(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&me(e)||n&&X(u))break;if(J(u)){if(l=e.line,c=e.lineStart,s=e.lineIndent,ge(e,!1,-1),e.lineIndent>=t){a=!0,u=e.input.charCodeAt(e.position);continue}e.position=o,e.line=l,e.lineStart=c,e.lineIndent=s;break}}a&&(pe(e,r,o,!1),ye(e,e.line-l),r=o=e.position,a=!1),Q(u)||(o=e.position+1),u=e.input.charCodeAt(++e.position)}return pe(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,d,1===i)&&(y=!0,null===e.tag&&(e.tag="?")):(y=!0,null===e.tag&&null===e.anchor||ce(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===g&&(y=c&&be(e,h))),null===e.tag)null!==e.anchor&&(e.anchorMap[e.anchor]=e.result);else if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&ce(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),s=0,u=e.implicitTypes.length;s"),null!==e.result&&f.kind!==e.kind&&ce(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+f.kind+'", not "'+e.kind+'"'),f.resolve(e.result,e.tag)?(e.result=f.construct(e.result,e.tag),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):ce(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||y}function ke(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);0!==(r=e.input.charCodeAt(e.position))&&(ge(e,!0,-1),r=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==r));){for(a=!0,r=e.input.charCodeAt(++e.position),t=e.position;0!==r&&!z(r);)r=e.input.charCodeAt(++e.position);for(i=[],(n=e.input.slice(t,e.position)).length<1&&ce(e,"directive name must not be less than one character in length");0!==r;){for(;Q(r);)r=e.input.charCodeAt(++e.position);if(35===r){do{r=e.input.charCodeAt(++e.position)}while(0!==r&&!J(r));break}if(J(r))break;for(t=e.position;0!==r&&!z(r);)r=e.input.charCodeAt(++e.position);i.push(e.input.slice(t,e.position))}0!==r&&he(e),P.call(ue,n)?ue[n](e,n,i):se(e,'unknown document directive "'+n+'"')}ge(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,ge(e,!0,-1)):a&&ce(e,"directives end mark is expected"),we(e,e.lineIndent-1,4,!1,!0),ge(e,!0,-1),e.checkLineBreaks&&H.test(e.input.slice(o,e.position))&&se(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&me(e)?46===e.input.charCodeAt(e.position)&&(e.position+=3,ge(e,!0,-1)):e.position=55296&&i<=56319&&t+1=56320&&n<=57343?1024*(i-55296)+n-56320+65536:i}function Re(e){return/^\n* /.test(e)}function Be(e,t,n,i,r,o,a,l){var c,s,u=0,p=null,f=!1,d=!1,h=-1!==i,g=-1,m=De(s=Ye(e,0))&&s!==Oe&&!_e(s)&&45!==s&&63!==s&&58!==s&&44!==s&&91!==s&&93!==s&&123!==s&&125!==s&&35!==s&&38!==s&&42!==s&&33!==s&&124!==s&&61!==s&&62!==s&&39!==s&&34!==s&&37!==s&&64!==s&&96!==s&&function(e){return!_e(e)&&58!==e}(Ye(e,e.length-1));if(t||a)for(c=0;c=65536?c+=2:c++){if(!De(u=Ye(e,c)))return 5;m=m&&qe(u,p,l),p=u}else{for(c=0;c=65536?c+=2:c++){if(10===(u=Ye(e,c)))f=!0,h&&(d=d||c-g-1>i&&" "!==e[g+1],g=c);else if(!De(u))return 5;m=m&&qe(u,p,l),p=u}d=d||h&&c-g-1>i&&" "!==e[g+1]}return f||d?n>9&&Re(e)?5:a?2===o?5:2:d?4:3:!m||a||r(e)?2===o?5:2:1}function Ke(e,t,n,i,r){e.dump=function(){if(0===t.length)return 2===e.quotingType?'""':"''";if(!e.noCompatMode&&(-1!==Te.indexOf(t)||Ne.test(t)))return 2===e.quotingType?'"'+t+'"':"'"+t+"'";var a=e.indent*Math.max(1,n),l=-1===e.lineWidth?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-a),c=i||e.flowLevel>-1&&n>=e.flowLevel;switch(Be(t,c,e.indent,l,(function(t){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+Pe(t,e.indent)+We(Me(function(e,t){var n,i,r=/(\n+)([^\n]*)/g,o=(l=e.indexOf("\n"),l=-1!==l?l:e.length,r.lastIndex=l,He(e.slice(0,l),t)),a="\n"===e[0]||" "===e[0];var l;for(;i=r.exec(e);){var c=i[1],s=i[2];n=" "===s[0],o+=c+(a||n||""===s?"":"\n")+He(s,t),a=n}return o}(t,l),a));case 5:return'"'+function(e){for(var t,n="",i=0,r=0;r=65536?r+=2:r++)i=Ye(e,r),!(t=je[i])&&De(i)?(n+=e[r],i>=65536&&(n+=e[r+1])):n+=t||Fe(i);return n}(t)+'"';default:throw new o("impossible error: invalid scalar style")}}()}function Pe(e,t){var n=Re(e)?String(t):"",i="\n"===e[e.length-1];return n+(i&&("\n"===e[e.length-2]||"\n"===e)?"+":i?"":"-")+"\n"}function We(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function He(e,t){if(""===e||" "===e[0])return e;for(var n,i,r=/ [^ ]/g,o=0,a=0,l=0,c="";n=r.exec(e);)(l=n.index)-o>t&&(i=a>o?a:l,c+="\n"+e.slice(o,i),o=i+1),a=l;return c+="\n",e.length-o>t&&a>o?c+=e.slice(o,a)+"\n"+e.slice(a+1):c+=e.slice(o),c.slice(1)}function $e(e,t,n,i){var r,o,a,l="",c=e.tag;for(r=0,o=n.length;r tag resolver accepts not "'+s+'" style');i=c.represent[s](t,s)}e.dump=i}return!0}return!1}function Ve(e,t,n,i,r,a,l){e.tag=null,e.dump=n,Ge(e,n,!1)||Ge(e,n,!0);var c,s=Ie.call(e.dump),u=i;i&&(i=e.flowLevel<0||e.flowLevel>t);var p,f,d="[object Object]"===s||"[object Array]"===s;if(d&&(f=-1!==(p=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||f||2!==e.indent&&t>0)&&(r=!1),f&&e.usedDuplicates[p])e.dump="*ref_"+p;else{if(d&&f&&!e.usedDuplicates[p]&&(e.usedDuplicates[p]=!0),"[object Object]"===s)i&&0!==Object.keys(e.dump).length?(!function(e,t,n,i){var r,a,l,c,s,u,p="",f=e.tag,d=Object.keys(n);if(!0===e.sortKeys)d.sort();else if("function"==typeof e.sortKeys)d.sort(e.sortKeys);else if(e.sortKeys)throw new o("sortKeys must be a boolean or a function");for(r=0,a=d.length;r1024)&&(e.dump&&10===e.dump.charCodeAt(0)?u+="?":u+="? "),u+=e.dump,s&&(u+=Le(e,t)),Ve(e,t+1,c,!0,s)&&(e.dump&&10===e.dump.charCodeAt(0)?u+=":":u+=": ",p+=u+=e.dump));e.tag=f,e.dump=p||"{}"}(e,t,e.dump,r),f&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,n){var i,r,o,a,l,c="",s=e.tag,u=Object.keys(n);for(i=0,r=u.length;i1024&&(l+="? "),l+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),Ve(e,t,a,!1,!1)&&(c+=l+=e.dump));e.tag=s,e.dump="{"+c+"}"}(e,t,e.dump),f&&(e.dump="&ref_"+p+" "+e.dump));else if("[object Array]"===s)i&&0!==e.dump.length?(e.noArrayIndent&&!l&&t>0?$e(e,t-1,e.dump,r):$e(e,t,e.dump,r),f&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,n){var i,r,o,a="",l=e.tag;for(i=0,r=n.length;i",e.dump=c+" "+e.dump)}return!0}function Ze(e,t){var n,i,r=[],o=[];for(Je(e,r,o),n=0,i=o.length;n maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; +} + + +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} + + +function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); +} + + +var snippet = makeSnippet; + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type$1(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type = Type$1; + +/*eslint-disable max-len*/ + + + + + +function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema$1(definition) { + return this.extend(definition); +} + + +Schema$1.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new exception('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type$1.loadKind && type$1.loadKind !== 'scalar') { + throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type$1.multi) { + throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema$1.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; +}; + + +var schema = Schema$1; + +var str = new type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var seq = new type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var map = new type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] +}); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +var _null = new type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool = new type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +var int = new type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +var float = new type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +var json = failsafe.extend({ + implicit: [ + _null, + bool, + int, + float + ] +}); + +var core = json; + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +var timestamp = new type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +var merge = new type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +/*eslint-disable no-bitwise*/ + + + + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} + +var binary = new type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; +var _toString$2 = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString$2.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty$3.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +var omap = new type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +var _toString$1 = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString$1.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +var pairs = new type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$2.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +var set = new type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +var _default = core.extend({ + implicit: [ + timestamp, + merge + ], + explicit: [ + binary, + omap, + pairs, + set + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + + + + + + + +var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State$1(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || _default; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = snippet(mark); + + return new exception(message, mark); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$1.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty$1.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$1.call(overridableKeys, keyNode) && + _hasOwnProperty$1.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State$1(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll$1(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load$1(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception('expected a single document in the stream, but found more'); +} + + +var loadAll_1 = loadAll$1; +var load_1 = load$1; + +var loader = { + loadAll: loadAll_1, + load: load_1 +}; + +/*eslint-disable no-use-before-define*/ + + + + + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + + +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + +function State(options) { + this.schema = options['schema'] || _default; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string) + '"'; + default: + throw new exception('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new exception('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new exception('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump$1(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; +} + +var dump_1 = dump$1; + +var dumper = { + dump: dump_1 +}; + +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} + + +var Type = type; +var Schema = schema; +var FAILSAFE_SCHEMA = failsafe; +var JSON_SCHEMA = json; +var CORE_SCHEMA = core; +var DEFAULT_SCHEMA = _default; +var load = loader.load; +var loadAll = loader.loadAll; +var dump = dumper.dump; +var YAMLException = exception; + +// Re-export all types in case user wants to create custom schema +var types = { + binary: binary, + float: float, + map: map, + null: _null, + pairs: pairs, + set: set, + timestamp: timestamp, + bool: bool, + int: int, + merge: merge, + omap: omap, + seq: seq, + str: str +}; + +// Removed functions from JS-YAML 3.0.x +var safeLoad = renamed('safeLoad', 'load'); +var safeLoadAll = renamed('safeLoadAll', 'loadAll'); +var safeDump = renamed('safeDump', 'dump'); + +var jsYaml = { + Type: Type, + Schema: Schema, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA, + load: load, + loadAll: loadAll, + dump: dump, + YAMLException: YAMLException, + types: types, + safeLoad: safeLoad, + safeLoadAll: safeLoadAll, + safeDump: safeDump +}; + +export default jsYaml; +export { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types }; diff --git a/node_modules/eslint/node_modules/js-yaml/index.js b/node_modules/eslint/node_modules/js-yaml/index.js new file mode 100644 index 0000000..bcb7eba --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/index.js @@ -0,0 +1,47 @@ +'use strict'; + + +var loader = require('./lib/loader'); +var dumper = require('./lib/dumper'); + + +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} + + +module.exports.Type = require('./lib/type'); +module.exports.Schema = require('./lib/schema'); +module.exports.FAILSAFE_SCHEMA = require('./lib/schema/failsafe'); +module.exports.JSON_SCHEMA = require('./lib/schema/json'); +module.exports.CORE_SCHEMA = require('./lib/schema/core'); +module.exports.DEFAULT_SCHEMA = require('./lib/schema/default'); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.dump = dumper.dump; +module.exports.YAMLException = require('./lib/exception'); + +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: require('./lib/type/binary'), + float: require('./lib/type/float'), + map: require('./lib/type/map'), + null: require('./lib/type/null'), + pairs: require('./lib/type/pairs'), + set: require('./lib/type/set'), + timestamp: require('./lib/type/timestamp'), + bool: require('./lib/type/bool'), + int: require('./lib/type/int'), + merge: require('./lib/type/merge'), + omap: require('./lib/type/omap'), + seq: require('./lib/type/seq'), + str: require('./lib/type/str') +}; + +// Removed functions from JS-YAML 3.0.x +module.exports.safeLoad = renamed('safeLoad', 'load'); +module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); +module.exports.safeDump = renamed('safeDump', 'dump'); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/common.js b/node_modules/eslint/node_modules/js-yaml/lib/common.js new file mode 100644 index 0000000..25ef7d8 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/common.js @@ -0,0 +1,59 @@ +'use strict'; + + +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; +} + + +function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; diff --git a/node_modules/eslint/node_modules/js-yaml/lib/dumper.js b/node_modules/eslint/node_modules/js-yaml/lib/dumper.js new file mode 100644 index 0000000..f357a6a --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/dumper.js @@ -0,0 +1,965 @@ +'use strict'; + +/*eslint-disable no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var DEFAULT_SCHEMA = require('./schema/default'); + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + + +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + +function State(options) { + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; +} + +module.exports.dump = dump; diff --git a/node_modules/eslint/node_modules/js-yaml/lib/exception.js b/node_modules/eslint/node_modules/js-yaml/lib/exception.js new file mode 100644 index 0000000..7f62daa --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/exception.js @@ -0,0 +1,55 @@ +// YAML error class. http://stackoverflow.com/questions/8458984 +// +'use strict'; + + +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; + + if (!exception.mark) return message; + + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } + + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } + + return message + ' ' + where; +} + + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; + + +module.exports = YAMLException; diff --git a/node_modules/eslint/node_modules/js-yaml/lib/loader.js b/node_modules/eslint/node_modules/js-yaml/lib/loader.js new file mode 100644 index 0000000..39f13f5 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/loader.js @@ -0,0 +1,1727 @@ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var makeSnippet = require('./snippet'); +var DEFAULT_SCHEMA = require('./schema/default'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = makeSnippet(mark); + + return new YAMLException(message, mark); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; diff --git a/node_modules/eslint/node_modules/js-yaml/lib/schema.js b/node_modules/eslint/node_modules/js-yaml/lib/schema.js new file mode 100644 index 0000000..65b41f4 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/schema.js @@ -0,0 +1,121 @@ +'use strict'; + +/*eslint-disable max-len*/ + +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + return this.extend(definition); +} + + +Schema.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof Type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type.multi) { + throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; +}; + + +module.exports = Schema; diff --git a/node_modules/eslint/node_modules/js-yaml/lib/schema/core.js b/node_modules/eslint/node_modules/js-yaml/lib/schema/core.js new file mode 100644 index 0000000..608b26d --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/schema/core.js @@ -0,0 +1,11 @@ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +module.exports = require('./json'); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/schema/default.js b/node_modules/eslint/node_modules/js-yaml/lib/schema/default.js new file mode 100644 index 0000000..3af0520 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/schema/default.js @@ -0,0 +1,22 @@ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +module.exports = require('./core').extend({ + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/schema/failsafe.js b/node_modules/eslint/node_modules/js-yaml/lib/schema/failsafe.js new file mode 100644 index 0000000..b7a33eb --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/schema/failsafe.js @@ -0,0 +1,17 @@ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/schema/json.js b/node_modules/eslint/node_modules/js-yaml/lib/schema/json.js new file mode 100644 index 0000000..b73df78 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/schema/json.js @@ -0,0 +1,19 @@ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +module.exports = require('./failsafe').extend({ + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/snippet.js b/node_modules/eslint/node_modules/js-yaml/lib/snippet.js new file mode 100644 index 0000000..00e2133 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/snippet.js @@ -0,0 +1,101 @@ +'use strict'; + + +var common = require('./common'); + + +// get snippet for a single line, respecting maxLength +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; +} + + +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} + + +function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); +} + + +module.exports = makeSnippet; diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type.js b/node_modules/eslint/node_modules/js-yaml/lib/type.js new file mode 100644 index 0000000..5e57877 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type.js @@ -0,0 +1,66 @@ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/binary.js b/node_modules/eslint/node_modules/js-yaml/lib/type/binary.js new file mode 100644 index 0000000..e152351 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/binary.js @@ -0,0 +1,125 @@ +'use strict'; + +/*eslint-disable no-bitwise*/ + + +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/bool.js b/node_modules/eslint/node_modules/js-yaml/lib/type/bool.js new file mode 100644 index 0000000..cb77459 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/bool.js @@ -0,0 +1,35 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/float.js b/node_modules/eslint/node_modules/js-yaml/lib/type/float.js new file mode 100644 index 0000000..74d77ec --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/float.js @@ -0,0 +1,97 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/int.js b/node_modules/eslint/node_modules/js-yaml/lib/type/int.js new file mode 100644 index 0000000..3fe3a44 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/int.js @@ -0,0 +1,156 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/map.js b/node_modules/eslint/node_modules/js-yaml/lib/type/map.js new file mode 100644 index 0000000..f327bee --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/map.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/merge.js b/node_modules/eslint/node_modules/js-yaml/lib/type/merge.js new file mode 100644 index 0000000..ae08a86 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/merge.js @@ -0,0 +1,12 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/null.js b/node_modules/eslint/node_modules/js-yaml/lib/type/null.js new file mode 100644 index 0000000..315ca4e --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/null.js @@ -0,0 +1,35 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/omap.js b/node_modules/eslint/node_modules/js-yaml/lib/type/omap.js new file mode 100644 index 0000000..b2b5323 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/omap.js @@ -0,0 +1,44 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/pairs.js b/node_modules/eslint/node_modules/js-yaml/lib/type/pairs.js new file mode 100644 index 0000000..74b5240 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/pairs.js @@ -0,0 +1,53 @@ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/seq.js b/node_modules/eslint/node_modules/js-yaml/lib/type/seq.js new file mode 100644 index 0000000..be8f77f --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/seq.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/set.js b/node_modules/eslint/node_modules/js-yaml/lib/type/set.js new file mode 100644 index 0000000..f885a32 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/set.js @@ -0,0 +1,29 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/str.js b/node_modules/eslint/node_modules/js-yaml/lib/type/str.js new file mode 100644 index 0000000..27acc10 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/str.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); diff --git a/node_modules/eslint/node_modules/js-yaml/lib/type/timestamp.js b/node_modules/eslint/node_modules/js-yaml/lib/type/timestamp.js new file mode 100644 index 0000000..8fa9c58 --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/lib/type/timestamp.js @@ -0,0 +1,88 @@ +'use strict'; + +var Type = require('../type'); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); diff --git a/node_modules/eslint/node_modules/js-yaml/package.json b/node_modules/eslint/node_modules/js-yaml/package.json new file mode 100644 index 0000000..17574da --- /dev/null +++ b/node_modules/eslint/node_modules/js-yaml/package.json @@ -0,0 +1,66 @@ +{ + "name": "js-yaml", + "version": "4.1.0", + "description": "YAML 1.2 parser and serializer", + "keywords": [ + "yaml", + "parser", + "serializer", + "pyyaml" + ], + "author": "Vladimir Zapparov ", + "contributors": [ + "Aleksey V Zapparov (http://www.ixti.net/)", + "Vitaly Puzrin (https://github.com/puzrin)", + "Martin Grenfell (http://got-ravings.blogspot.com)" + ], + "license": "MIT", + "repository": "nodeca/js-yaml", + "files": [ + "index.js", + "lib/", + "bin/", + "dist/" + ], + "bin": { + "js-yaml": "bin/js-yaml.js" + }, + "module": "./dist/js-yaml.mjs", + "exports": { + ".": { + "import": "./dist/js-yaml.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "lint": "eslint .", + "test": "npm run lint && mocha", + "coverage": "npm run lint && nyc mocha && nyc report --reporter html", + "demo": "npm run lint && node support/build_demo.js", + "gh-demo": "npm run demo && gh-pages -d demo -f", + "browserify": "rollup -c support/rollup.config.js", + "prepublishOnly": "npm run gh-demo" + }, + "unpkg": "dist/js-yaml.min.js", + "jsdelivr": "dist/js-yaml.min.js", + "dependencies": { + "argparse": "^2.0.1" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^17.0.0", + "@rollup/plugin-node-resolve": "^11.0.0", + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "codemirror": "^5.13.4", + "eslint": "^7.0.0", + "fast-check": "^2.8.0", + "gh-pages": "^3.1.0", + "mocha": "^8.2.1", + "nyc": "^15.1.0", + "rollup": "^2.34.1", + "rollup-plugin-node-polyfills": "^0.2.1", + "rollup-plugin-terser": "^7.0.2", + "shelljs": "^0.8.4" + } +} diff --git a/node_modules/eslint/node_modules/locate-path/index.d.ts b/node_modules/eslint/node_modules/locate-path/index.d.ts new file mode 100644 index 0000000..a714f1d --- /dev/null +++ b/node_modules/eslint/node_modules/locate-path/index.d.ts @@ -0,0 +1,83 @@ +declare namespace locatePath { + interface Options { + /** + Current working directory. + + @default process.cwd() + */ + readonly cwd?: string; + + /** + Type of path to match. + + @default 'file' + */ + readonly type?: 'file' | 'directory'; + + /** + Allow symbolic links to match if they point to the requested path type. + + @default true + */ + readonly allowSymlinks?: boolean; + } + + interface AsyncOptions extends Options { + /** + Number of concurrently pending promises. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `paths` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +declare const locatePath: { + /** + Synchronously get the first path that exists on disk of multiple paths. + + @param paths - Paths to check. + @returns The first path that exists or `undefined` if none exists. + */ + sync: ( + paths: Iterable, + options?: locatePath.Options + ) => string | undefined; + + /** + Get the first path that exists on disk of multiple paths. + + @param paths - Paths to check. + @returns The first path that exists or `undefined` if none exists. + + @example + ``` + import locatePath = require('locate-path'); + + const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' + ]; + + (async () => { + console(await locatePath(files)); + //=> 'rainbow' + })(); + ``` + */ + (paths: Iterable, options?: locatePath.AsyncOptions): Promise< + string | undefined + >; +}; + +export = locatePath; diff --git a/node_modules/eslint/node_modules/locate-path/index.js b/node_modules/eslint/node_modules/locate-path/index.js new file mode 100644 index 0000000..a6358e5 --- /dev/null +++ b/node_modules/eslint/node_modules/locate-path/index.js @@ -0,0 +1,68 @@ +'use strict'; +const path = require('path'); +const fs = require('fs'); +const {promisify} = require('util'); +const pLocate = require('p-locate'); + +const fsStat = promisify(fs.stat); +const fsLStat = promisify(fs.lstat); + +const typeMappings = { + directory: 'isDirectory', + file: 'isFile' +}; + +function checkType({type}) { + if (type in typeMappings) { + return; + } + + throw new Error(`Invalid type specified: ${type}`); +} + +const matchType = (type, stat) => type === undefined || stat[typeMappings[type]](); + +module.exports = async (paths, options) => { + options = { + cwd: process.cwd(), + type: 'file', + allowSymlinks: true, + ...options + }; + + checkType(options); + + const statFn = options.allowSymlinks ? fsStat : fsLStat; + + return pLocate(paths, async path_ => { + try { + const stat = await statFn(path.resolve(options.cwd, path_)); + return matchType(options.type, stat); + } catch { + return false; + } + }, options); +}; + +module.exports.sync = (paths, options) => { + options = { + cwd: process.cwd(), + allowSymlinks: true, + type: 'file', + ...options + }; + + checkType(options); + + const statFn = options.allowSymlinks ? fs.statSync : fs.lstatSync; + + for (const path_ of paths) { + try { + const stat = statFn(path.resolve(options.cwd, path_)); + + if (matchType(options.type, stat)) { + return path_; + } + } catch {} + } +}; diff --git a/node_modules/eslint/node_modules/locate-path/license b/node_modules/eslint/node_modules/locate-path/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/eslint/node_modules/locate-path/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/eslint/node_modules/locate-path/package.json b/node_modules/eslint/node_modules/locate-path/package.json new file mode 100644 index 0000000..08bea50 --- /dev/null +++ b/node_modules/eslint/node_modules/locate-path/package.json @@ -0,0 +1,46 @@ +{ + "name": "locate-path", + "version": "6.0.0", + "description": "Get the first path that exists on disk of multiple paths", + "license": "MIT", + "repository": "sindresorhus/locate-path", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "locate", + "path", + "paths", + "file", + "files", + "exists", + "find", + "finder", + "search", + "searcher", + "array", + "iterable", + "iterator" + ], + "dependencies": { + "p-locate": "^5.0.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.13.1", + "xo": "^0.32.1" + } +} diff --git a/node_modules/eslint/node_modules/locate-path/readme.md b/node_modules/eslint/node_modules/locate-path/readme.md new file mode 100644 index 0000000..1002bcd --- /dev/null +++ b/node_modules/eslint/node_modules/locate-path/readme.md @@ -0,0 +1,125 @@ +# locate-path [![Build Status](https://travis-ci.com/sindresorhus/locate-path.svg?branch=master)](https://travis-ci.com/github/sindresorhus/locate-path) + +> Get the first path that exists on disk of multiple paths + +## Install + +``` +$ npm install locate-path +``` + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const locatePath = require('locate-path'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + console(await locatePath(files)); + //=> 'rainbow' +})(); +``` + +## API + +### locatePath(paths, options?) + +Returns a `Promise` for the first path that exists or `undefined` if none exists. + +#### paths + +Type: `Iterable` + +Paths to check. + +#### options + +Type: `object` + +##### concurrency + +Type: `number`\ +Default: `Infinity`\ +Minimum: `1` + +Number of concurrently pending promises. + +##### preserveOrder + +Type: `boolean`\ +Default: `true` + +Preserve `paths` order when searching. + +Disable this to improve performance if you don't care about the order. + +##### cwd + +Type: `string`\ +Default: `process.cwd()` + +Current working directory. + +##### type + +Type: `string`\ +Default: `'file'`\ +Values: `'file' | 'directory'` + +The type of paths that can match. + +##### allowSymlinks + +Type: `boolean`\ +Default: `true` + +Allow symbolic links to match if they point to the chosen path type. + +### locatePath.sync(paths, options?) + +Returns the first path that exists or `undefined` if none exists. + +#### paths + +Type: `Iterable` + +Paths to check. + +#### options + +Type: `object` + +##### cwd + +Same as above. + +##### type + +Same as above. + +##### allowSymlinks + +Same as above. + +## Related + +- [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/eslint/node_modules/p-limit/index.d.ts b/node_modules/eslint/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000..f348d7f --- /dev/null +++ b/node_modules/eslint/node_modules/p-limit/index.d.ts @@ -0,0 +1,42 @@ +declare namespace pLimit { + interface Limit { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + } +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +declare function pLimit(concurrency: number): pLimit.Limit; + +export = pLimit; diff --git a/node_modules/eslint/node_modules/p-limit/index.js b/node_modules/eslint/node_modules/p-limit/index.js new file mode 100644 index 0000000..c2ae52d --- /dev/null +++ b/node_modules/eslint/node_modules/p-limit/index.js @@ -0,0 +1,71 @@ +'use strict'; +const Queue = require('yocto-queue'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, ...args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, ...args) => { + queue.enqueue(run.bind(null, fn, resolve, ...args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, ...args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.size + }, + clearQueue: { + value: () => { + queue.clear(); + } + } + }); + + return generator; +}; + +module.exports = pLimit; diff --git a/node_modules/eslint/node_modules/p-limit/license b/node_modules/eslint/node_modules/p-limit/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/eslint/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/eslint/node_modules/p-limit/package.json b/node_modules/eslint/node_modules/p-limit/package.json new file mode 100644 index 0000000..7651473 --- /dev/null +++ b/node_modules/eslint/node_modules/p-limit/package.json @@ -0,0 +1,52 @@ +{ + "name": "p-limit", + "version": "3.1.0", + "description": "Run multiple promise-returning & async functions with limited concurrency", + "license": "MIT", + "repository": "sindresorhus/p-limit", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.4.0", + "in-range": "^2.0.0", + "random-int": "^2.0.1", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + } +} diff --git a/node_modules/eslint/node_modules/p-limit/readme.md b/node_modules/eslint/node_modules/p-limit/readme.md new file mode 100644 index 0000000..b283c1e --- /dev/null +++ b/node_modules/eslint/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/eslint/node_modules/p-locate/index.d.ts b/node_modules/eslint/node_modules/p-locate/index.d.ts new file mode 100644 index 0000000..38c7e57 --- /dev/null +++ b/node_modules/eslint/node_modules/p-locate/index.d.ts @@ -0,0 +1,53 @@ +declare namespace pLocate { + interface Options { + /** + Number of concurrently pending promises returned by `tester`. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `input` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +/** +Get the first fulfilled promise that satisfies the provided testing function. + +@param input - An iterable of promises/values to test. +@param tester - This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. +@returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +@example +``` +import pathExists = require('path-exists'); +import pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` +*/ +declare function pLocate( + input: Iterable | ValueType>, + tester: (element: ValueType) => PromiseLike | boolean, + options?: pLocate.Options +): Promise; + +export = pLocate; diff --git a/node_modules/eslint/node_modules/p-locate/index.js b/node_modules/eslint/node_modules/p-locate/index.js new file mode 100644 index 0000000..641c3dd --- /dev/null +++ b/node_modules/eslint/node_modules/p-locate/index.js @@ -0,0 +1,50 @@ +'use strict'; +const pLimit = require('p-limit'); + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +const pLocate = async (iterable, tester, options) => { + options = { + concurrency: Infinity, + preserveOrder: true, + ...options + }; + + const limit = pLimit(options.concurrency); + + // Start all the promises concurrently with optional limit + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently + const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +}; + +module.exports = pLocate; diff --git a/node_modules/eslint/node_modules/p-locate/license b/node_modules/eslint/node_modules/p-locate/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/eslint/node_modules/p-locate/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/eslint/node_modules/p-locate/package.json b/node_modules/eslint/node_modules/p-locate/package.json new file mode 100644 index 0000000..2d5e447 --- /dev/null +++ b/node_modules/eslint/node_modules/p-locate/package.json @@ -0,0 +1,54 @@ +{ + "name": "p-locate", + "version": "5.0.0", + "description": "Get the first fulfilled promise that satisfies the provided testing function", + "license": "MIT", + "repository": "sindresorhus/p-locate", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "locate", + "find", + "finder", + "search", + "searcher", + "test", + "array", + "collection", + "iterable", + "iterator", + "race", + "fulfilled", + "fastest", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-limit": "^3.0.2" + }, + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.1.0", + "in-range": "^2.0.0", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.32.1" + } +} diff --git a/node_modules/eslint/node_modules/p-locate/readme.md b/node_modules/eslint/node_modules/p-locate/readme.md new file mode 100644 index 0000000..be85ec1 --- /dev/null +++ b/node_modules/eslint/node_modules/p-locate/readme.md @@ -0,0 +1,93 @@ +# p-locate [![Build Status](https://travis-ci.com/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.com/github/sindresorhus/p-locate) + +> Get the first fulfilled promise that satisfies the provided testing function + +Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). + +## Install + +``` +$ npm install p-locate +``` + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const pathExists = require('path-exists'); +const pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` + +*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* + +## API + +### pLocate(input, tester, options?) + +Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +#### input + +Type: `Iterable` + +An iterable of promises/values to test. + +#### tester(element) + +Type: `Function` + +This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + +#### options + +Type: `object` + +##### concurrency + +Type: `number`\ +Default: `Infinity`\ +Minimum: `1` + +Number of concurrently pending promises returned by `tester`. + +##### preserveOrder + +Type: `boolean`\ +Default: `true` + +Preserve `input` order when searching. + +Disable this to improve performance if you don't care about the order. + +## Related + +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently +- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/eslint/package.json b/node_modules/eslint/package.json new file mode 100644 index 0000000..661e8fc --- /dev/null +++ b/node_modules/eslint/package.json @@ -0,0 +1,172 @@ +{ + "name": "eslint", + "version": "8.47.0", + "author": "Nicholas C. Zakas ", + "description": "An AST-based pattern checker for JavaScript.", + "bin": { + "eslint": "./bin/eslint.js" + }, + "main": "./lib/api.js", + "exports": { + "./package.json": "./package.json", + ".": "./lib/api.js", + "./use-at-your-own-risk": "./lib/unsupported-api.js" + }, + "scripts": { + "build:docs:update-links": "node tools/fetch-docs-links.js", + "build:site": "node Makefile.js gensite", + "build:webpack": "node Makefile.js webpack", + "build:readme": "node tools/update-readme.js", + "lint": "node Makefile.js lint", + "lint:docs:js": "node Makefile.js lintDocsJS", + "lint:fix": "node Makefile.js lint -- fix", + "lint:fix:docs:js": "node Makefile.js lintDocsJS -- fix", + "release:generate:alpha": "node Makefile.js generatePrerelease -- alpha", + "release:generate:beta": "node Makefile.js generatePrerelease -- beta", + "release:generate:latest": "node Makefile.js generateRelease", + "release:generate:rc": "node Makefile.js generatePrerelease -- rc", + "release:publish": "node Makefile.js publishRelease", + "test": "node Makefile.js test", + "test:cli": "mocha", + "test:fuzz": "node Makefile.js fuzz", + "test:performance": "node Makefile.js perf" + }, + "gitHooks": { + "pre-commit": "lint-staged" + }, + "lint-staged": { + "*.js": "eslint --fix", + "*.md": "markdownlint --fix", + "lib/rules/*.js": [ + "node tools/update-eslint-all.js", + "git add packages/js/src/configs/eslint-all.js" + ], + "docs/src/rules/*.md": [ + "node tools/fetch-docs-links.js", + "git add docs/src/_data/further_reading_links.json" + ], + "docs/**/*.svg": "npx svgo -r --multipass" + }, + "files": [ + "LICENSE", + "README.md", + "bin", + "conf", + "lib", + "messages" + ], + "repository": "eslint/eslint", + "funding": "https://opencollective.com/eslint", + "homepage": "https://eslint.org", + "bugs": "https://github.com/eslint/eslint/issues/", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.2", + "@eslint/js": "^8.47.0", + "@humanwhocodes/config-array": "^0.11.10", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "devDependencies": { + "@babel/core": "^7.4.3", + "@babel/preset-env": "^7.4.3", + "babel-loader": "^8.0.5", + "c8": "^7.12.0", + "chai": "^4.0.1", + "cheerio": "^0.22.0", + "common-tags": "^1.8.0", + "core-js": "^3.1.3", + "ejs": "^3.0.2", + "eslint": "file:.", + "eslint-config-eslint": "file:packages/eslint-config-eslint", + "eslint-plugin-eslint-comments": "^3.2.0", + "eslint-plugin-eslint-plugin": "^5.1.0", + "eslint-plugin-internal-rules": "file:tools/internal-rules", + "eslint-plugin-jsdoc": "^46.2.5", + "eslint-plugin-n": "^16.0.0", + "eslint-plugin-unicorn": "^42.0.0", + "eslint-release": "^3.2.0", + "eslump": "^3.0.0", + "esprima": "^4.0.1", + "fast-glob": "^3.2.11", + "fs-teardown": "^0.1.3", + "glob": "^7.1.6", + "got": "^11.8.3", + "gray-matter": "^4.0.3", + "karma": "^6.1.1", + "karma-chrome-launcher": "^3.1.0", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-webpack": "^5.0.0", + "lint-staged": "^11.0.0", + "load-perf": "^0.2.0", + "markdownlint": "^0.25.1", + "markdownlint-cli": "^0.31.1", + "marked": "^4.0.8", + "memfs": "^3.0.1", + "metascraper": "^5.25.7", + "metascraper-description": "^5.25.7", + "metascraper-image": "^5.29.3", + "metascraper-logo": "^5.25.7", + "metascraper-logo-favicon": "^5.25.7", + "metascraper-title": "^5.25.7", + "mocha": "^8.3.2", + "mocha-junit-reporter": "^2.0.0", + "node-polyfill-webpack-plugin": "^1.0.3", + "npm-license": "^0.3.3", + "pirates": "^4.0.5", + "progress": "^2.0.3", + "proxyquire": "^2.0.1", + "puppeteer": "^13.7.0", + "recast": "^0.20.4", + "regenerator-runtime": "^0.13.2", + "semver": "^7.5.3", + "shelljs": "^0.8.2", + "sinon": "^11.0.0", + "webpack": "^5.23.0", + "webpack-cli": "^4.5.0", + "yorkie": "^2.0.0" + }, + "keywords": [ + "ast", + "lint", + "javascript", + "ecmascript", + "espree" + ], + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } +} diff --git a/node_modules/espree/LICENSE b/node_modules/espree/LICENSE new file mode 100644 index 0000000..b18469f --- /dev/null +++ b/node_modules/espree/LICENSE @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) Open JS Foundation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/espree/README.md b/node_modules/espree/README.md new file mode 100644 index 0000000..87ace4c --- /dev/null +++ b/node_modules/espree/README.md @@ -0,0 +1,244 @@ +[![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) +[![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) +[![Build Status](https://github.com/eslint/espree/workflows/CI/badge.svg)](https://github.com/eslint/espree/actions) +[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) + +# Espree + +Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. + +## Usage + +Install: + +``` +npm i espree +``` + +To use in an ESM file: + +```js +import * as espree from "espree"; + +const ast = espree.parse(code); +``` + +To use in a Common JS file: + +```js +const espree = require("espree"); + +const ast = espree.parse(code); +``` + +## API + +### `parse()` + +`parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. + +- `code` [string]() - the code which needs to be parsed. +- `options (Optional)` [Object]() - read more about this [here](#options). + +```js +import * as espree from "espree"; + +const ast = espree.parse(code); +``` + +**Example :** + +```js +const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); +console.log(ast); +``` + +
Output +

+ +``` +Node { + type: 'Program', + start: 0, + end: 15, + body: [ + Node { + type: 'VariableDeclaration', + start: 0, + end: 15, + declarations: [Array], + kind: 'let' + } + ], + sourceType: 'script' +} +``` + +

+
+ +### `tokenize()` + +`tokenize` returns the tokens of a given code. It takes two parameters. + +- `code` [string]() - the code which needs to be parsed. +- `options (Optional)` [Object]() - read more about this [here](#options). + +Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array + +**Example :** + +```js +import * as espree from "espree"; + +const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); +console.log(tokens); +``` + +
Output +

+ +``` +Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, +Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, +Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, +Token { type: 'String', value: '"bar"', start: 10, end: 15 } +``` + +

+
+ +### `version` + +Returns the current `espree` version + +### `VisitorKeys` + +Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/eslint-visitor-keys) + +### `latestEcmaVersion` + +Returns the latest ECMAScript supported by `espree` + +### `supportedEcmaVersions` + +Returns an array of all supported ECMAScript versions + +## Options + +```js +const options = { + // attach range information to each node + range: false, + + // attach line/column location information to each node + loc: false, + + // create a top-level comments array containing all comments + comment: false, + + // create a top-level tokens array containing all tokens + tokens: false, + + // Set to 3, 5 (the default), 6, 7, 8, 9, 10, 11, 12, 13, 14 or 15 to specify the version of ECMAScript syntax you want to use. + // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), 2022 (same as 13), 2023 (same as 14) or 2024 (same as 15) to use the year-based naming. + // You can also set "latest" to use the most recently supported version. + ecmaVersion: 3, + + allowReserved: true, // only allowed when ecmaVersion is 3 + + // specify which type of script you're parsing ("script", "module", or "commonjs") + sourceType: "script", + + // specify additional language features + ecmaFeatures: { + + // enable JSX parsing + jsx: false, + + // enable return in global scope (set to true automatically when sourceType is "commonjs") + globalReturn: false, + + // enable implied strict mode (if ecmaVersion >= 5) + impliedStrict: false + } +} +``` + +## Esprima Compatibility Going Forward + +The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. + +Espree may also deviate from Esprima in the interface it exposes. + +## Contributing + +Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues). + +Espree is licensed under a permissive BSD 2-clause license. + +## Security Policy + +We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). + +## Build Commands + +* `npm test` - run all linting and tests +* `npm run lint` - run all linting + +## Differences from Espree 2.x + +* The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. +* Trailing whitespace no longer is counted as part of a node. +* `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. +* The `esparse` and `esvalidate` binary scripts have been removed. +* There is no `tolerant` option. We will investigate adding this back in the future. + +## Known Incompatibilities + +In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. + +### Esprima 1.2.2 + +* Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. +* Espree does not parse `let` and `const` declarations by default. +* Error messages returned for parsing errors are different. +* There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. + +### Esprima 2.x + +* Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. + +## Frequently Asked Questions + +### Why another parser + +[ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. + +We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. + +With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. + +### Have you tried working with Esprima? + +Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. + +### Why don't you just use Acorn? + +Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. + +We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. + +### What ECMAScript features do you support? + +Espree supports all ECMAScript 2023 features and partially supports ECMAScript 2024 features. + +Because ECMAScript 2024 is still under development, we are implementing features as they are finalized. Currently, Espree supports: + +* [RegExp v flag with set notation + properties of strings](https://github.com/tc39/proposal-regexp-v-flag) + +See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. + +### How do you determine which experimental features to support? + +In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. diff --git a/node_modules/espree/dist/espree.cjs b/node_modules/espree/dist/espree.cjs new file mode 100644 index 0000000..3fa2870 --- /dev/null +++ b/node_modules/espree/dist/espree.cjs @@ -0,0 +1,883 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var acorn = require('acorn'); +var jsx = require('acorn-jsx'); +var visitorKeys = require('eslint-visitor-keys'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var acorn__namespace = /*#__PURE__*/_interopNamespace(acorn); +var jsx__default = /*#__PURE__*/_interopDefaultLegacy(jsx); +var visitorKeys__namespace = /*#__PURE__*/_interopNamespace(visitorKeys); + +/** + * @fileoverview Translates tokens between Acorn format and Esprima format. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + + +// Esprima Token Types +const Token = { + Boolean: "Boolean", + EOF: "", + Identifier: "Identifier", + PrivateIdentifier: "PrivateIdentifier", + Keyword: "Keyword", + Null: "Null", + Numeric: "Numeric", + Punctuator: "Punctuator", + String: "String", + RegularExpression: "RegularExpression", + Template: "Template", + JSXIdentifier: "JSXIdentifier", + JSXText: "JSXText" +}; + +/** + * Converts part of a template into an Esprima token. + * @param {AcornToken[]} tokens The Acorn tokens representing the template. + * @param {string} code The source code. + * @returns {EsprimaToken} The Esprima equivalent of the template token. + * @private + */ +function convertTemplatePart(tokens, code) { + const firstToken = tokens[0], + lastTemplateToken = tokens[tokens.length - 1]; + + const token = { + type: Token.Template, + value: code.slice(firstToken.start, lastTemplateToken.end) + }; + + if (firstToken.loc) { + token.loc = { + start: firstToken.loc.start, + end: lastTemplateToken.loc.end + }; + } + + if (firstToken.range) { + token.start = firstToken.range[0]; + token.end = lastTemplateToken.range[1]; + token.range = [token.start, token.end]; + } + + return token; +} + +/** + * Contains logic to translate Acorn tokens into Esprima tokens. + * @param {Object} acornTokTypes The Acorn token types. + * @param {string} code The source code Acorn is parsing. This is necessary + * to correct the "value" property of some tokens. + * @constructor + */ +function TokenTranslator(acornTokTypes, code) { + + // token types + this._acornTokTypes = acornTokTypes; + + // token buffer for templates + this._tokens = []; + + // track the last curly brace + this._curlyBrace = null; + + // the source code + this._code = code; + +} + +TokenTranslator.prototype = { + constructor: TokenTranslator, + + /** + * Translates a single Esprima token to a single Acorn token. This may be + * inaccurate due to how templates are handled differently in Esprima and + * Acorn, but should be accurate for all other tokens. + * @param {AcornToken} token The Acorn token to translate. + * @param {Object} extra Espree extra object. + * @returns {EsprimaToken} The Esprima version of the token. + */ + translate(token, extra) { + + const type = token.type, + tt = this._acornTokTypes; + + if (type === tt.name) { + token.type = Token.Identifier; + + // TODO: See if this is an Acorn bug + if (token.value === "static") { + token.type = Token.Keyword; + } + + if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) { + token.type = Token.Keyword; + } + + } else if (type === tt.privateId) { + token.type = Token.PrivateIdentifier; + + } else if (type === tt.semi || type === tt.comma || + type === tt.parenL || type === tt.parenR || + type === tt.braceL || type === tt.braceR || + type === tt.dot || type === tt.bracketL || + type === tt.colon || type === tt.question || + type === tt.bracketR || type === tt.ellipsis || + type === tt.arrow || type === tt.jsxTagStart || + type === tt.incDec || type === tt.starstar || + type === tt.jsxTagEnd || type === tt.prefix || + type === tt.questionDot || + (type.binop && !type.keyword) || + type.isAssign) { + + token.type = Token.Punctuator; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.jsxName) { + token.type = Token.JSXIdentifier; + } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) { + token.type = Token.JSXText; + } else if (type.keyword) { + if (type.keyword === "true" || type.keyword === "false") { + token.type = Token.Boolean; + } else if (type.keyword === "null") { + token.type = Token.Null; + } else { + token.type = Token.Keyword; + } + } else if (type === tt.num) { + token.type = Token.Numeric; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.string) { + + if (extra.jsxAttrValueToken) { + extra.jsxAttrValueToken = false; + token.type = Token.JSXText; + } else { + token.type = Token.String; + } + + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.regexp) { + token.type = Token.RegularExpression; + const value = token.value; + + token.regex = { + flags: value.flags, + pattern: value.pattern + }; + token.value = `/${value.pattern}/${value.flags}`; + } + + return token; + }, + + /** + * Function to call during Acorn's onToken handler. + * @param {AcornToken} token The Acorn token. + * @param {Object} extra The Espree extra object. + * @returns {void} + */ + onToken(token, extra) { + + const tt = this._acornTokTypes, + tokens = extra.tokens, + templateTokens = this._tokens; + + /** + * Flushes the buffered template tokens and resets the template + * tracking. + * @returns {void} + * @private + */ + const translateTemplateTokens = () => { + tokens.push(convertTemplatePart(this._tokens, this._code)); + this._tokens = []; + }; + + if (token.type === tt.eof) { + + // might be one last curlyBrace + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + return; + } + + if (token.type === tt.backQuote) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + templateTokens.push(token); + + // it's the end + if (templateTokens.length > 1) { + translateTemplateTokens(); + } + + return; + } + if (token.type === tt.dollarBraceL) { + templateTokens.push(token); + translateTemplateTokens(); + return; + } + if (token.type === tt.braceR) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + // store new curly for later + this._curlyBrace = token; + return; + } + if (token.type === tt.template || token.type === tt.invalidTemplate) { + if (this._curlyBrace) { + templateTokens.push(this._curlyBrace); + this._curlyBrace = null; + } + + templateTokens.push(token); + return; + } + + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + tokens.push(this.translate(token, extra)); + } +}; + +/** + * @fileoverview A collection of methods for processing Espree's options. + * @author Kai Cataldo + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SUPPORTED_VERSIONS = [ + 3, + 5, + 6, // 2015 + 7, // 2016 + 8, // 2017 + 9, // 2018 + 10, // 2019 + 11, // 2020 + 12, // 2021 + 13, // 2022 + 14, // 2023 + 15 // 2024 +]; + +/** + * Get the latest ECMAScript version supported by Espree. + * @returns {number} The latest ECMAScript version. + */ +function getLatestEcmaVersion() { + return SUPPORTED_VERSIONS[SUPPORTED_VERSIONS.length - 1]; +} + +/** + * Get the list of ECMAScript versions supported by Espree. + * @returns {number[]} An array containing the supported ECMAScript versions. + */ +function getSupportedEcmaVersions() { + return [...SUPPORTED_VERSIONS]; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {(number|"latest")} ecmaVersion ECMAScript version from the initial config + * @throws {Error} throws an error if the ecmaVersion is invalid. + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(ecmaVersion = 5) { + + let version = ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion; + + if (typeof version !== "number") { + throw new Error(`ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`); + } + + // Calculate ECMAScript edition number from official year version starting with + // ES2015, which corresponds with ES6 (or a difference of 2009). + if (version >= 2015) { + version -= 2009; + } + + if (!SUPPORTED_VERSIONS.includes(version)) { + throw new Error("Invalid ecmaVersion."); + } + + return version; +} + +/** + * Normalize sourceType from the initial config + * @param {string} sourceType to normalize + * @throws {Error} throw an error if sourceType is invalid + * @returns {string} normalized sourceType + */ +function normalizeSourceType(sourceType = "script") { + if (sourceType === "script" || sourceType === "module") { + return sourceType; + } + + if (sourceType === "commonjs") { + return "script"; + } + + throw new Error("Invalid sourceType."); +} + +/** + * Normalize parserOptions + * @param {Object} options the parser options to normalize + * @throws {Error} throw an error if found invalid option. + * @returns {Object} normalized options + */ +function normalizeOptions(options) { + const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); + const sourceType = normalizeSourceType(options.sourceType); + const ranges = options.range === true; + const locations = options.loc === true; + + if (ecmaVersion !== 3 && options.allowReserved) { + + // a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed + throw new Error("`allowReserved` is only supported when ecmaVersion is 3"); + } + if (typeof options.allowReserved !== "undefined" && typeof options.allowReserved !== "boolean") { + throw new Error("`allowReserved`, when present, must be `true` or `false`"); + } + const allowReserved = ecmaVersion === 3 ? (options.allowReserved || "never") : false; + const ecmaFeatures = options.ecmaFeatures || {}; + const allowReturnOutsideFunction = options.sourceType === "commonjs" || + Boolean(ecmaFeatures.globalReturn); + + if (sourceType === "module" && ecmaVersion < 6) { + throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options."); + } + + return Object.assign({}, options, { + ecmaVersion, + sourceType, + ranges, + locations, + allowReserved, + allowReturnOutsideFunction + }); +} + +/* eslint no-param-reassign: 0 -- stylistic choice */ + + +const STATE = Symbol("espree's internal state"); +const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode"); + + +/** + * Converts an Acorn comment to a Esprima comment. + * @param {boolean} block True if it's a block comment, false if not. + * @param {string} text The text of the comment. + * @param {int} start The index at which the comment starts. + * @param {int} end The index at which the comment ends. + * @param {Location} startLoc The location at which the comment starts. + * @param {Location} endLoc The location at which the comment ends. + * @param {string} code The source code being parsed. + * @returns {Object} The comment object. + * @private + */ +function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code) { + let type; + + if (block) { + type = "Block"; + } else if (code.slice(start, start + 2) === "#!") { + type = "Hashbang"; + } else { + type = "Line"; + } + + const comment = { + type, + value: text + }; + + if (typeof start === "number") { + comment.start = start; + comment.end = end; + comment.range = [start, end]; + } + + if (typeof startLoc === "object") { + comment.loc = { + start: startLoc, + end: endLoc + }; + } + + return comment; +} + +var espree = () => Parser => { + const tokTypes = Object.assign({}, Parser.acorn.tokTypes); + + if (Parser.acornJsx) { + Object.assign(tokTypes, Parser.acornJsx.tokTypes); + } + + return class Espree extends Parser { + constructor(opts, code) { + if (typeof opts !== "object" || opts === null) { + opts = {}; + } + if (typeof code !== "string" && !(code instanceof String)) { + code = String(code); + } + + // save original source type in case of commonjs + const originalSourceType = opts.sourceType; + const options = normalizeOptions(opts); + const ecmaFeatures = options.ecmaFeatures || {}; + const tokenTranslator = + options.tokens === true + ? new TokenTranslator(tokTypes, code) + : null; + + /* + * Data that is unique to Espree and is not represented internally + * in Acorn. + * + * For ES2023 hashbangs, Espree will call `onComment()` during the + * constructor, so we must define state before having access to + * `this`. + */ + const state = { + originalSourceType: originalSourceType || options.sourceType, + tokens: tokenTranslator ? [] : null, + comments: options.comment === true ? [] : null, + impliedStrict: ecmaFeatures.impliedStrict === true && options.ecmaVersion >= 5, + ecmaVersion: options.ecmaVersion, + jsxAttrValueToken: false, + lastToken: null, + templateElements: [] + }; + + // Initialize acorn parser. + super({ + + // do not use spread, because we don't want to pass any unknown options to acorn + ecmaVersion: options.ecmaVersion, + sourceType: options.sourceType, + ranges: options.ranges, + locations: options.locations, + allowReserved: options.allowReserved, + + // Truthy value is true for backward compatibility. + allowReturnOutsideFunction: options.allowReturnOutsideFunction, + + // Collect tokens + onToken(token) { + if (tokenTranslator) { + + // Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state. + tokenTranslator.onToken(token, state); + } + if (token.type !== tokTypes.eof) { + state.lastToken = token; + } + }, + + // Collect comments + onComment(block, text, start, end, startLoc, endLoc) { + if (state.comments) { + const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code); + + state.comments.push(comment); + } + } + }, code); + + /* + * We put all of this data into a symbol property as a way to avoid + * potential naming conflicts with future versions of Acorn. + */ + this[STATE] = state; + } + + tokenize() { + do { + this.next(); + } while (this.type !== tokTypes.eof); + + // Consume the final eof token + this.next(); + + const extra = this[STATE]; + const tokens = extra.tokens; + + if (extra.comments) { + tokens.comments = extra.comments; + } + + return tokens; + } + + finishNode(...args) { + const result = super.finishNode(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + finishNodeAt(...args) { + const result = super.finishNodeAt(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + parse() { + const extra = this[STATE]; + const program = super.parse(); + + program.sourceType = extra.originalSourceType; + + if (extra.comments) { + program.comments = extra.comments; + } + if (extra.tokens) { + program.tokens = extra.tokens; + } + + /* + * Adjust opening and closing position of program to match Esprima. + * Acorn always starts programs at range 0 whereas Esprima starts at the + * first AST node's start (the only real difference is when there's leading + * whitespace or leading comments). Acorn also counts trailing whitespace + * as part of the program whereas Esprima only counts up to the last token. + */ + if (program.body.length) { + const [firstNode] = program.body; + + if (program.range) { + program.range[0] = firstNode.range[0]; + } + if (program.loc) { + program.loc.start = firstNode.loc.start; + } + program.start = firstNode.start; + } + if (extra.lastToken) { + if (program.range) { + program.range[1] = extra.lastToken.range[1]; + } + if (program.loc) { + program.loc.end = extra.lastToken.loc.end; + } + program.end = extra.lastToken.end; + } + + + /* + * https://github.com/eslint/espree/issues/349 + * Ensure that template elements have correct range information. + * This is one location where Acorn produces a different value + * for its start and end properties vs. the values present in the + * range property. In order to avoid confusion, we set the start + * and end properties to the values that are present in range. + * This is done here, instead of in finishNode(), because Acorn + * uses the values of start and end internally while parsing, making + * it dangerous to change those values while parsing is ongoing. + * By waiting until the end of parsing, we can safely change these + * values without affect any other part of the process. + */ + this[STATE].templateElements.forEach(templateElement => { + const startOffset = -1; + const endOffset = templateElement.tail ? 1 : 2; + + templateElement.start += startOffset; + templateElement.end += endOffset; + + if (templateElement.range) { + templateElement.range[0] += startOffset; + templateElement.range[1] += endOffset; + } + + if (templateElement.loc) { + templateElement.loc.start.column += startOffset; + templateElement.loc.end.column += endOffset; + } + }); + + return program; + } + + parseTopLevel(node) { + if (this[STATE].impliedStrict) { + this.strict = true; + } + return super.parseTopLevel(node); + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raise(pos, message) { + const loc = Parser.acorn.getLineInfo(this.input, pos); + const err = new SyntaxError(message); + + err.index = pos; + err.lineNumber = loc.line; + err.column = loc.column + 1; // acorn uses 0-based columns + throw err; + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raiseRecoverable(pos, message) { + this.raise(pos, message); + } + + /** + * Overwrites the default unexpected method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + unexpected(pos) { + let message = "Unexpected token"; + + if (pos !== null && pos !== void 0) { + this.pos = pos; + + if (this.options.locations) { + while (this.pos < this.lineStart) { + this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; + --this.curLine; + } + } + + this.nextToken(); + } + + if (this.end > this.start) { + message += ` ${this.input.slice(this.start, this.end)}`; + } + + this.raise(this.start, message); + } + + /* + * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX + * uses regular tt.string without any distinction between this and regular JS + * strings. As such, we intercept an attempt to read a JSX string and set a flag + * on extra so that when tokens are converted, the next token will be switched + * to JSXText via onToken. + */ + jsx_readString(quote) { // eslint-disable-line camelcase -- required by API + const result = super.jsx_readString(quote); + + if (this.type === tokTypes.string) { + this[STATE].jsxAttrValueToken = true; + } + return result; + } + + /** + * Performs last-minute Esprima-specific compatibility checks and fixes. + * @param {ASTNode} result The node to check. + * @returns {ASTNode} The finished node. + */ + [ESPRIMA_FINISH_NODE](result) { + + // Acorn doesn't count the opening and closing backticks as part of templates + // so we have to adjust ranges/locations appropriately. + if (result.type === "TemplateElement") { + + // save template element references to fix start/end later + this[STATE].templateElements.push(result); + } + + if (result.type.includes("Function") && !result.generator) { + result.generator = false; + } + + return result; + } + }; +}; + +const version$1 = "9.6.1"; + +/* eslint-disable jsdoc/no-multi-asterisks -- needed to preserve original formatting of licences */ + + +// To initialize lazily. +const parsers = { + _regular: null, + _jsx: null, + + get regular() { + if (this._regular === null) { + this._regular = acorn__namespace.Parser.extend(espree()); + } + return this._regular; + }, + + get jsx() { + if (this._jsx === null) { + this._jsx = acorn__namespace.Parser.extend(jsx__default["default"](), espree()); + } + return this._jsx; + }, + + get(options) { + const useJsx = Boolean( + options && + options.ecmaFeatures && + options.ecmaFeatures.jsx + ); + + return useJsx ? this.jsx : this.regular; + } +}; + +//------------------------------------------------------------------------------ +// Tokenizer +//------------------------------------------------------------------------------ + +/** + * Tokenizes the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {Token[]} An array of tokens. + * @throws {SyntaxError} If the input code is invalid. + * @private + */ +function tokenize(code, options) { + const Parser = parsers.get(options); + + // Ensure to collect tokens. + if (!options || options.tokens !== true) { + options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice + } + + return new Parser(options, code).tokenize(); +} + +//------------------------------------------------------------------------------ +// Parser +//------------------------------------------------------------------------------ + +/** + * Parses the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {ASTNode} The "Program" AST node. + * @throws {SyntaxError} If the input code is invalid. + */ +function parse(code, options) { + const Parser = parsers.get(options); + + return new Parser(options, code).parse(); +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +const version = version$1; +const name = "espree"; + +/* istanbul ignore next */ +const VisitorKeys = (function() { + return visitorKeys__namespace.KEYS; +}()); + +// Derive node types from VisitorKeys +/* istanbul ignore next */ +const Syntax = (function() { + let key, + types = {}; + + if (typeof Object.create === "function") { + types = Object.create(null); + } + + for (key in VisitorKeys) { + if (Object.hasOwnProperty.call(VisitorKeys, key)) { + types[key] = key; + } + } + + if (typeof Object.freeze === "function") { + Object.freeze(types); + } + + return types; +}()); + +const latestEcmaVersion = getLatestEcmaVersion(); + +const supportedEcmaVersions = getSupportedEcmaVersions(); + +exports.Syntax = Syntax; +exports.VisitorKeys = VisitorKeys; +exports.latestEcmaVersion = latestEcmaVersion; +exports.name = name; +exports.parse = parse; +exports.supportedEcmaVersions = supportedEcmaVersions; +exports.tokenize = tokenize; +exports.version = version; diff --git a/node_modules/espree/espree.js b/node_modules/espree/espree.js new file mode 100644 index 0000000..e9b1118 --- /dev/null +++ b/node_modules/espree/espree.js @@ -0,0 +1,177 @@ +/* eslint-disable jsdoc/no-multi-asterisks -- needed to preserve original formatting of licences */ + +/** + * @fileoverview Main Espree file that converts Acorn into Esprima output. + * + * This file contains code from the following MIT-licensed projects: + * 1. Acorn + * 2. Babylon + * 3. Babel-ESLint + * + * This file also contains code from Esprima, which is BSD licensed. + * + * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS) + * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS) + * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie + * + * 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 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. + * + * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved. + * + * 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 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. + */ + +/* eslint-enable jsdoc/no-multi-asterisks -- needed to preserve original formatting of licences */ + +import * as acorn from "acorn"; +import jsx from "acorn-jsx"; +import espree from "./lib/espree.js"; +import espreeVersion from "./lib/version.js"; +import * as visitorKeys from "eslint-visitor-keys"; +import { getLatestEcmaVersion, getSupportedEcmaVersions } from "./lib/options.js"; + + +// To initialize lazily. +const parsers = { + _regular: null, + _jsx: null, + + get regular() { + if (this._regular === null) { + this._regular = acorn.Parser.extend(espree()); + } + return this._regular; + }, + + get jsx() { + if (this._jsx === null) { + this._jsx = acorn.Parser.extend(jsx(), espree()); + } + return this._jsx; + }, + + get(options) { + const useJsx = Boolean( + options && + options.ecmaFeatures && + options.ecmaFeatures.jsx + ); + + return useJsx ? this.jsx : this.regular; + } +}; + +//------------------------------------------------------------------------------ +// Tokenizer +//------------------------------------------------------------------------------ + +/** + * Tokenizes the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {Token[]} An array of tokens. + * @throws {SyntaxError} If the input code is invalid. + * @private + */ +export function tokenize(code, options) { + const Parser = parsers.get(options); + + // Ensure to collect tokens. + if (!options || options.tokens !== true) { + options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice + } + + return new Parser(options, code).tokenize(); +} + +//------------------------------------------------------------------------------ +// Parser +//------------------------------------------------------------------------------ + +/** + * Parses the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {ASTNode} The "Program" AST node. + * @throws {SyntaxError} If the input code is invalid. + */ +export function parse(code, options) { + const Parser = parsers.get(options); + + return new Parser(options, code).parse(); +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export const version = espreeVersion; +export const name = "espree"; + +/* istanbul ignore next */ +export const VisitorKeys = (function() { + return visitorKeys.KEYS; +}()); + +// Derive node types from VisitorKeys +/* istanbul ignore next */ +export const Syntax = (function() { + let key, + types = {}; + + if (typeof Object.create === "function") { + types = Object.create(null); + } + + for (key in VisitorKeys) { + if (Object.hasOwnProperty.call(VisitorKeys, key)) { + types[key] = key; + } + } + + if (typeof Object.freeze === "function") { + Object.freeze(types); + } + + return types; +}()); + +export const latestEcmaVersion = getLatestEcmaVersion(); + +export const supportedEcmaVersions = getSupportedEcmaVersions(); diff --git a/node_modules/espree/lib/espree.js b/node_modules/espree/lib/espree.js new file mode 100644 index 0000000..2be1b56 --- /dev/null +++ b/node_modules/espree/lib/espree.js @@ -0,0 +1,349 @@ +/* eslint no-param-reassign: 0 -- stylistic choice */ + +import TokenTranslator from "./token-translator.js"; +import { normalizeOptions } from "./options.js"; + + +const STATE = Symbol("espree's internal state"); +const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode"); + + +/** + * Converts an Acorn comment to a Esprima comment. + * @param {boolean} block True if it's a block comment, false if not. + * @param {string} text The text of the comment. + * @param {int} start The index at which the comment starts. + * @param {int} end The index at which the comment ends. + * @param {Location} startLoc The location at which the comment starts. + * @param {Location} endLoc The location at which the comment ends. + * @param {string} code The source code being parsed. + * @returns {Object} The comment object. + * @private + */ +function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code) { + let type; + + if (block) { + type = "Block"; + } else if (code.slice(start, start + 2) === "#!") { + type = "Hashbang"; + } else { + type = "Line"; + } + + const comment = { + type, + value: text + }; + + if (typeof start === "number") { + comment.start = start; + comment.end = end; + comment.range = [start, end]; + } + + if (typeof startLoc === "object") { + comment.loc = { + start: startLoc, + end: endLoc + }; + } + + return comment; +} + +export default () => Parser => { + const tokTypes = Object.assign({}, Parser.acorn.tokTypes); + + if (Parser.acornJsx) { + Object.assign(tokTypes, Parser.acornJsx.tokTypes); + } + + return class Espree extends Parser { + constructor(opts, code) { + if (typeof opts !== "object" || opts === null) { + opts = {}; + } + if (typeof code !== "string" && !(code instanceof String)) { + code = String(code); + } + + // save original source type in case of commonjs + const originalSourceType = opts.sourceType; + const options = normalizeOptions(opts); + const ecmaFeatures = options.ecmaFeatures || {}; + const tokenTranslator = + options.tokens === true + ? new TokenTranslator(tokTypes, code) + : null; + + /* + * Data that is unique to Espree and is not represented internally + * in Acorn. + * + * For ES2023 hashbangs, Espree will call `onComment()` during the + * constructor, so we must define state before having access to + * `this`. + */ + const state = { + originalSourceType: originalSourceType || options.sourceType, + tokens: tokenTranslator ? [] : null, + comments: options.comment === true ? [] : null, + impliedStrict: ecmaFeatures.impliedStrict === true && options.ecmaVersion >= 5, + ecmaVersion: options.ecmaVersion, + jsxAttrValueToken: false, + lastToken: null, + templateElements: [] + }; + + // Initialize acorn parser. + super({ + + // do not use spread, because we don't want to pass any unknown options to acorn + ecmaVersion: options.ecmaVersion, + sourceType: options.sourceType, + ranges: options.ranges, + locations: options.locations, + allowReserved: options.allowReserved, + + // Truthy value is true for backward compatibility. + allowReturnOutsideFunction: options.allowReturnOutsideFunction, + + // Collect tokens + onToken(token) { + if (tokenTranslator) { + + // Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state. + tokenTranslator.onToken(token, state); + } + if (token.type !== tokTypes.eof) { + state.lastToken = token; + } + }, + + // Collect comments + onComment(block, text, start, end, startLoc, endLoc) { + if (state.comments) { + const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code); + + state.comments.push(comment); + } + } + }, code); + + /* + * We put all of this data into a symbol property as a way to avoid + * potential naming conflicts with future versions of Acorn. + */ + this[STATE] = state; + } + + tokenize() { + do { + this.next(); + } while (this.type !== tokTypes.eof); + + // Consume the final eof token + this.next(); + + const extra = this[STATE]; + const tokens = extra.tokens; + + if (extra.comments) { + tokens.comments = extra.comments; + } + + return tokens; + } + + finishNode(...args) { + const result = super.finishNode(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + finishNodeAt(...args) { + const result = super.finishNodeAt(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + parse() { + const extra = this[STATE]; + const program = super.parse(); + + program.sourceType = extra.originalSourceType; + + if (extra.comments) { + program.comments = extra.comments; + } + if (extra.tokens) { + program.tokens = extra.tokens; + } + + /* + * Adjust opening and closing position of program to match Esprima. + * Acorn always starts programs at range 0 whereas Esprima starts at the + * first AST node's start (the only real difference is when there's leading + * whitespace or leading comments). Acorn also counts trailing whitespace + * as part of the program whereas Esprima only counts up to the last token. + */ + if (program.body.length) { + const [firstNode] = program.body; + + if (program.range) { + program.range[0] = firstNode.range[0]; + } + if (program.loc) { + program.loc.start = firstNode.loc.start; + } + program.start = firstNode.start; + } + if (extra.lastToken) { + if (program.range) { + program.range[1] = extra.lastToken.range[1]; + } + if (program.loc) { + program.loc.end = extra.lastToken.loc.end; + } + program.end = extra.lastToken.end; + } + + + /* + * https://github.com/eslint/espree/issues/349 + * Ensure that template elements have correct range information. + * This is one location where Acorn produces a different value + * for its start and end properties vs. the values present in the + * range property. In order to avoid confusion, we set the start + * and end properties to the values that are present in range. + * This is done here, instead of in finishNode(), because Acorn + * uses the values of start and end internally while parsing, making + * it dangerous to change those values while parsing is ongoing. + * By waiting until the end of parsing, we can safely change these + * values without affect any other part of the process. + */ + this[STATE].templateElements.forEach(templateElement => { + const startOffset = -1; + const endOffset = templateElement.tail ? 1 : 2; + + templateElement.start += startOffset; + templateElement.end += endOffset; + + if (templateElement.range) { + templateElement.range[0] += startOffset; + templateElement.range[1] += endOffset; + } + + if (templateElement.loc) { + templateElement.loc.start.column += startOffset; + templateElement.loc.end.column += endOffset; + } + }); + + return program; + } + + parseTopLevel(node) { + if (this[STATE].impliedStrict) { + this.strict = true; + } + return super.parseTopLevel(node); + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raise(pos, message) { + const loc = Parser.acorn.getLineInfo(this.input, pos); + const err = new SyntaxError(message); + + err.index = pos; + err.lineNumber = loc.line; + err.column = loc.column + 1; // acorn uses 0-based columns + throw err; + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raiseRecoverable(pos, message) { + this.raise(pos, message); + } + + /** + * Overwrites the default unexpected method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + unexpected(pos) { + let message = "Unexpected token"; + + if (pos !== null && pos !== void 0) { + this.pos = pos; + + if (this.options.locations) { + while (this.pos < this.lineStart) { + this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; + --this.curLine; + } + } + + this.nextToken(); + } + + if (this.end > this.start) { + message += ` ${this.input.slice(this.start, this.end)}`; + } + + this.raise(this.start, message); + } + + /* + * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX + * uses regular tt.string without any distinction between this and regular JS + * strings. As such, we intercept an attempt to read a JSX string and set a flag + * on extra so that when tokens are converted, the next token will be switched + * to JSXText via onToken. + */ + jsx_readString(quote) { // eslint-disable-line camelcase -- required by API + const result = super.jsx_readString(quote); + + if (this.type === tokTypes.string) { + this[STATE].jsxAttrValueToken = true; + } + return result; + } + + /** + * Performs last-minute Esprima-specific compatibility checks and fixes. + * @param {ASTNode} result The node to check. + * @returns {ASTNode} The finished node. + */ + [ESPRIMA_FINISH_NODE](result) { + + // Acorn doesn't count the opening and closing backticks as part of templates + // so we have to adjust ranges/locations appropriately. + if (result.type === "TemplateElement") { + + // save template element references to fix start/end later + this[STATE].templateElements.push(result); + } + + if (result.type.includes("Function") && !result.generator) { + result.generator = false; + } + + return result; + } + }; +}; diff --git a/node_modules/espree/lib/features.js b/node_modules/espree/lib/features.js new file mode 100644 index 0000000..31467d2 --- /dev/null +++ b/node_modules/espree/lib/features.js @@ -0,0 +1,27 @@ +/** + * @fileoverview The list of feature flags supported by the parser and their default + * settings. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export default { + + // React JSX parsing + jsx: false, + + // allow return statement in global scope + globalReturn: false, + + // allow implied strict mode + impliedStrict: false +}; diff --git a/node_modules/espree/lib/options.js b/node_modules/espree/lib/options.js new file mode 100644 index 0000000..1460ac2 --- /dev/null +++ b/node_modules/espree/lib/options.js @@ -0,0 +1,123 @@ +/** + * @fileoverview A collection of methods for processing Espree's options. + * @author Kai Cataldo + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SUPPORTED_VERSIONS = [ + 3, + 5, + 6, // 2015 + 7, // 2016 + 8, // 2017 + 9, // 2018 + 10, // 2019 + 11, // 2020 + 12, // 2021 + 13, // 2022 + 14, // 2023 + 15 // 2024 +]; + +/** + * Get the latest ECMAScript version supported by Espree. + * @returns {number} The latest ECMAScript version. + */ +export function getLatestEcmaVersion() { + return SUPPORTED_VERSIONS[SUPPORTED_VERSIONS.length - 1]; +} + +/** + * Get the list of ECMAScript versions supported by Espree. + * @returns {number[]} An array containing the supported ECMAScript versions. + */ +export function getSupportedEcmaVersions() { + return [...SUPPORTED_VERSIONS]; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {(number|"latest")} ecmaVersion ECMAScript version from the initial config + * @throws {Error} throws an error if the ecmaVersion is invalid. + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(ecmaVersion = 5) { + + let version = ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion; + + if (typeof version !== "number") { + throw new Error(`ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`); + } + + // Calculate ECMAScript edition number from official year version starting with + // ES2015, which corresponds with ES6 (or a difference of 2009). + if (version >= 2015) { + version -= 2009; + } + + if (!SUPPORTED_VERSIONS.includes(version)) { + throw new Error("Invalid ecmaVersion."); + } + + return version; +} + +/** + * Normalize sourceType from the initial config + * @param {string} sourceType to normalize + * @throws {Error} throw an error if sourceType is invalid + * @returns {string} normalized sourceType + */ +function normalizeSourceType(sourceType = "script") { + if (sourceType === "script" || sourceType === "module") { + return sourceType; + } + + if (sourceType === "commonjs") { + return "script"; + } + + throw new Error("Invalid sourceType."); +} + +/** + * Normalize parserOptions + * @param {Object} options the parser options to normalize + * @throws {Error} throw an error if found invalid option. + * @returns {Object} normalized options + */ +export function normalizeOptions(options) { + const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); + const sourceType = normalizeSourceType(options.sourceType); + const ranges = options.range === true; + const locations = options.loc === true; + + if (ecmaVersion !== 3 && options.allowReserved) { + + // a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed + throw new Error("`allowReserved` is only supported when ecmaVersion is 3"); + } + if (typeof options.allowReserved !== "undefined" && typeof options.allowReserved !== "boolean") { + throw new Error("`allowReserved`, when present, must be `true` or `false`"); + } + const allowReserved = ecmaVersion === 3 ? (options.allowReserved || "never") : false; + const ecmaFeatures = options.ecmaFeatures || {}; + const allowReturnOutsideFunction = options.sourceType === "commonjs" || + Boolean(ecmaFeatures.globalReturn); + + if (sourceType === "module" && ecmaVersion < 6) { + throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options."); + } + + return Object.assign({}, options, { + ecmaVersion, + sourceType, + ranges, + locations, + allowReserved, + allowReturnOutsideFunction + }); +} diff --git a/node_modules/espree/lib/token-translator.js b/node_modules/espree/lib/token-translator.js new file mode 100644 index 0000000..2a915fb --- /dev/null +++ b/node_modules/espree/lib/token-translator.js @@ -0,0 +1,263 @@ +/** + * @fileoverview Translates tokens between Acorn format and Esprima format. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + + +// Esprima Token Types +const Token = { + Boolean: "Boolean", + EOF: "", + Identifier: "Identifier", + PrivateIdentifier: "PrivateIdentifier", + Keyword: "Keyword", + Null: "Null", + Numeric: "Numeric", + Punctuator: "Punctuator", + String: "String", + RegularExpression: "RegularExpression", + Template: "Template", + JSXIdentifier: "JSXIdentifier", + JSXText: "JSXText" +}; + +/** + * Converts part of a template into an Esprima token. + * @param {AcornToken[]} tokens The Acorn tokens representing the template. + * @param {string} code The source code. + * @returns {EsprimaToken} The Esprima equivalent of the template token. + * @private + */ +function convertTemplatePart(tokens, code) { + const firstToken = tokens[0], + lastTemplateToken = tokens[tokens.length - 1]; + + const token = { + type: Token.Template, + value: code.slice(firstToken.start, lastTemplateToken.end) + }; + + if (firstToken.loc) { + token.loc = { + start: firstToken.loc.start, + end: lastTemplateToken.loc.end + }; + } + + if (firstToken.range) { + token.start = firstToken.range[0]; + token.end = lastTemplateToken.range[1]; + token.range = [token.start, token.end]; + } + + return token; +} + +/** + * Contains logic to translate Acorn tokens into Esprima tokens. + * @param {Object} acornTokTypes The Acorn token types. + * @param {string} code The source code Acorn is parsing. This is necessary + * to correct the "value" property of some tokens. + * @constructor + */ +function TokenTranslator(acornTokTypes, code) { + + // token types + this._acornTokTypes = acornTokTypes; + + // token buffer for templates + this._tokens = []; + + // track the last curly brace + this._curlyBrace = null; + + // the source code + this._code = code; + +} + +TokenTranslator.prototype = { + constructor: TokenTranslator, + + /** + * Translates a single Esprima token to a single Acorn token. This may be + * inaccurate due to how templates are handled differently in Esprima and + * Acorn, but should be accurate for all other tokens. + * @param {AcornToken} token The Acorn token to translate. + * @param {Object} extra Espree extra object. + * @returns {EsprimaToken} The Esprima version of the token. + */ + translate(token, extra) { + + const type = token.type, + tt = this._acornTokTypes; + + if (type === tt.name) { + token.type = Token.Identifier; + + // TODO: See if this is an Acorn bug + if (token.value === "static") { + token.type = Token.Keyword; + } + + if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) { + token.type = Token.Keyword; + } + + } else if (type === tt.privateId) { + token.type = Token.PrivateIdentifier; + + } else if (type === tt.semi || type === tt.comma || + type === tt.parenL || type === tt.parenR || + type === tt.braceL || type === tt.braceR || + type === tt.dot || type === tt.bracketL || + type === tt.colon || type === tt.question || + type === tt.bracketR || type === tt.ellipsis || + type === tt.arrow || type === tt.jsxTagStart || + type === tt.incDec || type === tt.starstar || + type === tt.jsxTagEnd || type === tt.prefix || + type === tt.questionDot || + (type.binop && !type.keyword) || + type.isAssign) { + + token.type = Token.Punctuator; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.jsxName) { + token.type = Token.JSXIdentifier; + } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) { + token.type = Token.JSXText; + } else if (type.keyword) { + if (type.keyword === "true" || type.keyword === "false") { + token.type = Token.Boolean; + } else if (type.keyword === "null") { + token.type = Token.Null; + } else { + token.type = Token.Keyword; + } + } else if (type === tt.num) { + token.type = Token.Numeric; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.string) { + + if (extra.jsxAttrValueToken) { + extra.jsxAttrValueToken = false; + token.type = Token.JSXText; + } else { + token.type = Token.String; + } + + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.regexp) { + token.type = Token.RegularExpression; + const value = token.value; + + token.regex = { + flags: value.flags, + pattern: value.pattern + }; + token.value = `/${value.pattern}/${value.flags}`; + } + + return token; + }, + + /** + * Function to call during Acorn's onToken handler. + * @param {AcornToken} token The Acorn token. + * @param {Object} extra The Espree extra object. + * @returns {void} + */ + onToken(token, extra) { + + const tt = this._acornTokTypes, + tokens = extra.tokens, + templateTokens = this._tokens; + + /** + * Flushes the buffered template tokens and resets the template + * tracking. + * @returns {void} + * @private + */ + const translateTemplateTokens = () => { + tokens.push(convertTemplatePart(this._tokens, this._code)); + this._tokens = []; + }; + + if (token.type === tt.eof) { + + // might be one last curlyBrace + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + return; + } + + if (token.type === tt.backQuote) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + templateTokens.push(token); + + // it's the end + if (templateTokens.length > 1) { + translateTemplateTokens(); + } + + return; + } + if (token.type === tt.dollarBraceL) { + templateTokens.push(token); + translateTemplateTokens(); + return; + } + if (token.type === tt.braceR) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + // store new curly for later + this._curlyBrace = token; + return; + } + if (token.type === tt.template || token.type === tt.invalidTemplate) { + if (this._curlyBrace) { + templateTokens.push(this._curlyBrace); + this._curlyBrace = null; + } + + templateTokens.push(token); + return; + } + + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + tokens.push(this.translate(token, extra)); + } +}; + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export default TokenTranslator; diff --git a/node_modules/espree/lib/version.js b/node_modules/espree/lib/version.js new file mode 100644 index 0000000..dc73f77 --- /dev/null +++ b/node_modules/espree/lib/version.js @@ -0,0 +1,3 @@ +const version = "9.6.1"; + +export default version; diff --git a/node_modules/espree/node_modules/.bin/acorn b/node_modules/espree/node_modules/.bin/acorn new file mode 120000 index 0000000..cf76760 --- /dev/null +++ b/node_modules/espree/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/node_modules/espree/node_modules/acorn/CHANGELOG.md b/node_modules/espree/node_modules/acorn/CHANGELOG.md new file mode 100644 index 0000000..12464cf --- /dev/null +++ b/node_modules/espree/node_modules/acorn/CHANGELOG.md @@ -0,0 +1,844 @@ +## 8.10.0 (2023-07-05) + +### New features + +Add a `checkPrivateFields` option that disables strict checking of private property use. + +## 8.9.0 (2023-06-16) + +### Bug fixes + +Forbid dynamic import after `new`, even when part of a member expression. + +### New features + +Add Unicode properties for ES2023. + +Add support for the `v` flag to regular expressions. + +## 8.8.2 (2023-01-23) + +### Bug fixes + +Fix a bug that caused `allowHashBang` to be set to false when not provided, even with `ecmaVersion >= 14`. + +Fix an exception when passing no option object to `parse` or `new Parser`. + +Fix incorrect parse error on `if (0) let\n[astral identifier char]`. + +## 8.8.1 (2022-10-24) + +### Bug fixes + +Make type for `Comment` compatible with estree types. + +## 8.8.0 (2022-07-21) + +### Bug fixes + +Allow parentheses around spread args in destructuring object assignment. + +Fix an issue where the tree contained `directive` properties in when parsing with a language version that doesn't support them. + +### New features + +Support hashbang comments by default in ECMAScript 2023 and later. + +## 8.7.1 (2021-04-26) + +### Bug fixes + +Stop handling `"use strict"` directives in ECMAScript versions before 5. + +Fix an issue where duplicate quoted export names in `export *` syntax were incorrectly checked. + +Add missing type for `tokTypes`. + +## 8.7.0 (2021-12-27) + +### New features + +Support quoted export names. + +Upgrade to Unicode 14. + +Add support for Unicode 13 properties in regular expressions. + +### Bug fixes + +Use a loop to find line breaks, because the existing regexp search would overrun the end of the searched range and waste a lot of time in minified code. + +## 8.6.0 (2021-11-18) + +### Bug fixes + +Fix a bug where an object literal with multiple `__proto__` properties would incorrectly be accepted if a later property value held an assigment. + +### New features + +Support class private fields with the `in` operator. + +## 8.5.0 (2021-09-06) + +### Bug fixes + +Improve context-dependent tokenization in a number of corner cases. + +Fix location tracking after a 0x2028 or 0x2029 character in a string literal (which before did not increase the line number). + +Fix an issue where arrow function bodies in for loop context would inappropriately consume `in` operators. + +Fix wrong end locations stored on SequenceExpression nodes. + +Implement restriction that `for`/`of` loop LHS can't start with `let`. + +### New features + +Add support for ES2022 class static blocks. + +Allow multiple input files to be passed to the CLI tool. + +## 8.4.1 (2021-06-24) + +### Bug fixes + +Fix a bug where `allowAwaitOutsideFunction` would allow `await` in class field initializers, and setting `ecmaVersion` to 13 or higher would allow top-level await in non-module sources. + +## 8.4.0 (2021-06-11) + +### New features + +A new option, `allowSuperOutsideMethod`, can be used to suppress the error when `super` is used in the wrong context. + +## 8.3.0 (2021-05-31) + +### New features + +Default `allowAwaitOutsideFunction` to true for ECMAScript 2022 an higher. + +Add support for the `d` ([indices](https://github.com/tc39/proposal-regexp-match-indices)) regexp flag. + +## 8.2.4 (2021-05-04) + +### Bug fixes + +Fix spec conformity in corner case 'for await (async of ...)'. + +## 8.2.3 (2021-05-04) + +### Bug fixes + +Fix an issue where the library couldn't parse 'for (async of ...)'. + +Fix a bug in UTF-16 decoding that would read characters incorrectly in some circumstances. + +## 8.2.2 (2021-04-29) + +### Bug fixes + +Fix a bug where a class field initialized to an async arrow function wouldn't allow await inside it. Same issue existed for generator arrow functions with yield. + +## 8.2.1 (2021-04-24) + +### Bug fixes + +Fix a regression introduced in 8.2.0 where static or async class methods with keyword names fail to parse. + +## 8.2.0 (2021-04-24) + +### New features + +Add support for ES2022 class fields and private methods. + +## 8.1.1 (2021-04-12) + +### Various + +Stop shipping source maps in the NPM package. + +## 8.1.0 (2021-03-09) + +### Bug fixes + +Fix a spurious error in nested destructuring arrays. + +### New features + +Expose `allowAwaitOutsideFunction` in CLI interface. + +Make `allowImportExportAnywhere` also apply to `import.meta`. + +## 8.0.5 (2021-01-25) + +### Bug fixes + +Adjust package.json to work with Node 12.16.0 and 13.0-13.6. + +## 8.0.4 (2020-10-05) + +### Bug fixes + +Make `await x ** y` an error, following the spec. + +Fix potentially exponential regular expression. + +## 8.0.3 (2020-10-02) + +### Bug fixes + +Fix a wasteful loop during `Parser` creation when setting `ecmaVersion` to `"latest"`. + +## 8.0.2 (2020-09-30) + +### Bug fixes + +Make the TypeScript types reflect the current allowed values for `ecmaVersion`. + +Fix another regexp/division tokenizer issue. + +## 8.0.1 (2020-08-12) + +### Bug fixes + +Provide the correct value in the `version` export. + +## 8.0.0 (2020-08-12) + +### Bug fixes + +Disallow expressions like `(a = b) = c`. + +Make non-octal escape sequences a syntax error in strict mode. + +### New features + +The package can now be loaded directly as an ECMAScript module in node 13+. + +Update to the set of Unicode properties from ES2021. + +### Breaking changes + +The `ecmaVersion` option is now required. For the moment, omitting it will still work with a warning, but that will change in a future release. + +Some changes to method signatures that may be used by plugins. + +## 7.4.0 (2020-08-03) + +### New features + +Add support for logical assignment operators. + +Add support for numeric separators. + +## 7.3.1 (2020-06-11) + +### Bug fixes + +Make the string in the `version` export match the actual library version. + +## 7.3.0 (2020-06-11) + +### Bug fixes + +Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail. + +### New features + +Add support for optional chaining (`?.`). + +## 7.2.0 (2020-05-09) + +### Bug fixes + +Fix precedence issue in parsing of async arrow functions. + +### New features + +Add support for nullish coalescing. + +Add support for `import.meta`. + +Support `export * as ...` syntax. + +Upgrade to Unicode 13. + +## 6.4.1 (2020-03-09) + +### Bug fixes + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.1 (2020-03-01) + +### Bug fixes + +Treat `\8` and `\9` as invalid escapes in template strings. + +Allow unicode escapes in property names that are keywords. + +Don't error on an exponential operator expression as argument to `await`. + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.0 (2019-09-24) + +### Bug fixes + +Disallow trailing object literal commas when ecmaVersion is less than 5. + +### New features + +Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on. + +## 7.0.0 (2019-08-13) + +### Breaking changes + +Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression). + +Makes 10 (ES2019) the default value for the `ecmaVersion` option. + +## 6.3.0 (2019-08-12) + +### New features + +`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard. + +## 6.2.1 (2019-07-21) + +### Bug fixes + +Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such. + +Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances. + +## 6.2.0 (2019-07-04) + +### Bug fixes + +Improve valid assignment checking in `for`/`in` and `for`/`of` loops. + +Disallow binding `let` in patterns. + +### New features + +Support bigint syntax with `ecmaVersion` >= 11. + +Support dynamic `import` syntax with `ecmaVersion` >= 11. + +Upgrade to Unicode version 12. + +## 6.1.1 (2019-02-27) + +### Bug fixes + +Fix bug that caused parsing default exports of with names to fail. + +## 6.1.0 (2019-02-08) + +### Bug fixes + +Fix scope checking when redefining a `var` as a lexical binding. + +### New features + +Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins. + +## 6.0.7 (2019-02-04) + +### Bug fixes + +Check that exported bindings are defined. + +Don't treat `\u180e` as a whitespace character. + +Check for duplicate parameter names in methods. + +Don't allow shorthand properties when they are generators or async methods. + +Forbid binding `await` in async arrow function's parameter list. + +## 6.0.6 (2019-01-30) + +### Bug fixes + +The content of class declarations and expressions is now always parsed in strict mode. + +Don't allow `let` or `const` to bind the variable name `let`. + +Treat class declarations as lexical. + +Don't allow a generator function declaration as the sole body of an `if` or `else`. + +Ignore `"use strict"` when after an empty statement. + +Allow string line continuations with special line terminator characters. + +Treat `for` bodies as part of the `for` scope when checking for conflicting bindings. + +Fix bug with parsing `yield` in a `for` loop initializer. + +Implement special cases around scope checking for functions. + +## 6.0.5 (2019-01-02) + +### Bug fixes + +Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type. + +Don't treat `let` as a keyword when the next token is `{` on the next line. + +Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on. + +## 6.0.4 (2018-11-05) + +### Bug fixes + +Further improvements to tokenizing regular expressions in corner cases. + +## 6.0.3 (2018-11-04) + +### Bug fixes + +Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression. + +Remove stray symlink in the package tarball. + +## 6.0.2 (2018-09-26) + +### Bug fixes + +Fix bug where default expressions could fail to parse inside an object destructuring assignment expression. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix wrong value in `version` export. + +## 6.0.0 (2018-09-14) + +### Bug fixes + +Better handle variable-redefinition checks for catch bindings and functions directly under if statements. + +Forbid `new.target` in top-level arrow functions. + +Fix issue with parsing a regexp after `yield` in some contexts. + +### New features + +The package now comes with TypeScript definitions. + +### Breaking changes + +The default value of the `ecmaVersion` option is now 9 (2018). + +Plugins work differently, and will have to be rewritten to work with this version. + +The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`). + +## 5.7.3 (2018-09-10) + +### Bug fixes + +Fix failure to tokenize regexps after expressions like `x.of`. + +Better error message for unterminated template literals. + +## 5.7.2 (2018-08-24) + +### Bug fixes + +Properly handle `allowAwaitOutsideFunction` in for statements. + +Treat function declarations at the top level of modules like let bindings. + +Don't allow async function declarations as the only statement under a label. + +## 5.7.0 (2018-06-15) + +### New features + +Upgraded to Unicode 11. + +## 5.6.0 (2018-05-31) + +### New features + +Allow U+2028 and U+2029 in string when ECMAVersion >= 10. + +Allow binding-less catch statements when ECMAVersion >= 10. + +Add `allowAwaitOutsideFunction` option for parsing top-level `await`. + +## 5.5.3 (2018-03-08) + +### Bug fixes + +A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps. + +## 5.5.2 (2018-03-08) + +### Bug fixes + +A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix misleading error message for octal escapes in template strings. + +## 5.5.0 (2018-02-27) + +### New features + +The identifier character categorization is now based on Unicode version 10. + +Acorn will now validate the content of regular expressions, including new ES9 features. + +## 5.4.0 (2018-02-01) + +### Bug fixes + +Disallow duplicate or escaped flags on regular expressions. + +Disallow octal escapes in strings in strict mode. + +### New features + +Add support for async iteration. + +Add support for object spread and rest. + +## 5.3.0 (2017-12-28) + +### Bug fixes + +Fix parsing of floating point literals with leading zeroes in loose mode. + +Allow duplicate property names in object patterns. + +Don't allow static class methods named `prototype`. + +Disallow async functions directly under `if` or `else`. + +Parse right-hand-side of `for`/`of` as an assignment expression. + +Stricter parsing of `for`/`in`. + +Don't allow unicode escapes in contextual keywords. + +### New features + +Parsing class members was factored into smaller methods to allow plugins to hook into it. + +## 5.2.1 (2017-10-30) + +### Bug fixes + +Fix a token context corruption bug. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +Fix token context tracking for `class` and `function` in property-name position. + +Make sure `%*` isn't parsed as a valid operator. + +Allow shorthand properties `get` and `set` to be followed by default values. + +Disallow `super` when not in callee or object position. + +### New features + +Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements. + +## 5.1.2 (2017-09-04) + +### Bug fixes + +Disable parsing of legacy HTML-style comments in modules. + +Fix parsing of async methods whose names are keywords. + +## 5.1.1 (2017-07-06) + +### Bug fixes + +Fix problem with disambiguating regexp and division after a class. + +## 5.1.0 (2017-07-05) + +### Bug fixes + +Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`. + +Parse zero-prefixed numbers with non-octal digits as decimal. + +Allow object/array patterns in rest parameters. + +Don't error when `yield` is used as a property name. + +Allow `async` as a shorthand object property. + +### New features + +Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9. + +## 5.0.3 (2017-04-01) + +### Bug fixes + +Fix spurious duplicate variable definition errors for named functions. + +## 5.0.2 (2017-03-30) + +### Bug fixes + +A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error. + +## 5.0.0 (2017-03-28) + +### Bug fixes + +Raise an error for duplicated lexical bindings. + +Fix spurious error when an assignement expression occurred after a spread expression. + +Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions. + +Allow labels in front or `var` declarations, even in strict mode. + +### Breaking changes + +Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`. + +## 4.0.11 (2017-02-07) + +### Bug fixes + +Allow all forms of member expressions to be parenthesized as lvalue. + +## 4.0.10 (2017-02-07) + +### Bug fixes + +Don't expect semicolons after default-exported functions or classes, even when they are expressions. + +Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode. + +## 4.0.9 (2017-02-06) + +### Bug fixes + +Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again. + +## 4.0.8 (2017-02-03) + +### Bug fixes + +Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet. + +## 4.0.7 (2017-02-02) + +### Bug fixes + +Accept invalidly rejected code like `(x).y = 2` again. + +Don't raise an error when a function _inside_ strict code has a non-simple parameter list. + +## 4.0.6 (2017-02-02) + +### Bug fixes + +Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check. + +## 4.0.5 (2017-02-02) + +### Bug fixes + +Disallow parenthesized pattern expressions. + +Allow keywords as export names. + +Don't allow the `async` keyword to be parenthesized. + +Properly raise an error when a keyword contains a character escape. + +Allow `"use strict"` to appear after other string literal expressions. + +Disallow labeled declarations. + +## 4.0.4 (2016-12-19) + +### Bug fixes + +Fix crash when `export` was followed by a keyword that can't be +exported. + +## 4.0.3 (2016-08-16) + +### Bug fixes + +Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode. + +Properly parse properties named `async` in ES2017 mode. + +Fix bug where reserved words were broken in ES2017 mode. + +## 4.0.2 (2016-08-11) + +### Bug fixes + +Don't ignore period or 'e' characters after octal numbers. + +Fix broken parsing for call expressions in default parameter values of arrow functions. + +## 4.0.1 (2016-08-08) + +### Bug fixes + +Fix false positives in duplicated export name errors. + +## 4.0.0 (2016-08-07) + +### Breaking changes + +The default `ecmaVersion` option value is now 7. + +A number of internal method signatures changed, so plugins might need to be updated. + +### Bug fixes + +The parser now raises errors on duplicated export names. + +`arguments` and `eval` can now be used in shorthand properties. + +Duplicate parameter names in non-simple argument lists now always produce an error. + +### New features + +The `ecmaVersion` option now also accepts year-style version numbers +(2015, etc). + +Support for `async`/`await` syntax when `ecmaVersion` is >= 8. + +Support for trailing commas in call expressions when `ecmaVersion` is >= 8. + +## 3.3.0 (2016-07-25) + +### Bug fixes + +Fix bug in tokenizing of regexp operator after a function declaration. + +Fix parser crash when parsing an array pattern with a hole. + +### New features + +Implement check against complex argument lists in functions that enable strict mode in ES7. + +## 3.2.0 (2016-06-07) + +### Bug fixes + +Improve handling of lack of unicode regexp support in host +environment. + +Properly reject shorthand properties whose name is a keyword. + +### New features + +Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object. + +## 3.1.0 (2016-04-18) + +### Bug fixes + +Properly tokenize the division operator directly after a function expression. + +Allow trailing comma in destructuring arrays. + +## 3.0.4 (2016-02-25) + +### Fixes + +Allow update expressions as left-hand-side of the ES7 exponential operator. + +## 3.0.2 (2016-02-10) + +### Fixes + +Fix bug that accidentally made `undefined` a reserved word when parsing ES7. + +## 3.0.0 (2016-02-10) + +### Breaking changes + +The default value of the `ecmaVersion` option is now 6 (used to be 5). + +Support for comprehension syntax (which was dropped from the draft spec) has been removed. + +### Fixes + +`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code. + +A parenthesized class or function expression after `export default` is now parsed correctly. + +### New features + +When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`). + +The identifier character ranges are now based on Unicode 8.0.0. + +Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled. + +## 2.7.0 (2016-01-04) + +### Fixes + +Stop allowing rest parameters in setters. + +Disallow `y` rexexp flag in ES5. + +Disallow `\00` and `\000` escapes in strict mode. + +Raise an error when an import name is a reserved word. + +## 2.6.2 (2015-11-10) + +### Fixes + +Don't crash when no options object is passed. + +## 2.6.0 (2015-11-09) + +### Fixes + +Add `await` as a reserved word in module sources. + +Disallow `yield` in a parameter default value for a generator. + +Forbid using a comma after a rest pattern in an array destructuring. + +### New features + +Support parsing stdin in command-line tool. + +## 2.5.0 (2015-10-27) + +### Fixes + +Fix tokenizer support in the command-line tool. + +Stop allowing `new.target` outside of functions. + +Remove legacy `guard` and `guardedHandler` properties from try nodes. + +Stop allowing multiple `__proto__` properties on an object literal in strict mode. + +Don't allow rest parameters to be non-identifier patterns. + +Check for duplicate paramter names in arrow functions. diff --git a/node_modules/espree/node_modules/acorn/LICENSE b/node_modules/espree/node_modules/acorn/LICENSE new file mode 100644 index 0000000..9d71cc6 --- /dev/null +++ b/node_modules/espree/node_modules/acorn/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2012-2022 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/espree/node_modules/acorn/README.md b/node_modules/espree/node_modules/acorn/README.md new file mode 100644 index 0000000..b62d02b --- /dev/null +++ b/node_modules/espree/node_modules/acorn/README.md @@ -0,0 +1,278 @@ +# Acorn + +A tiny, fast JavaScript parser written in JavaScript. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). For questions +and discussion, please use the +[Tern discussion forum](https://discuss.ternjs.net). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +**parse**`(input, options)` is the main interface to the library. The +`input` parameter is a string, `options` must be an object setting +some of the options listed below. The return value will be an abstract +syntax tree object as specified by the [ESTree +spec](https://github.com/estree/estree). + +```javascript +let acorn = require("acorn"); +console.log(acorn.parse("1 + 1", {ecmaVersion: 2020})); +``` + +When encountering a syntax error, the parser will raise a +`SyntaxError` object with a meaningful message. The error object will +have a `pos` property that indicates the string offset at which the +error occurred, and a `loc` object that contains a `{line, column}` +object referring to that same position. + +Options are provided by in a second argument, which should be an +object containing any of these fields (only `ecmaVersion` is +required): + +- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be + either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019), + 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` (the + latest the library supports). This influences support for strict + mode, the set of reserved words, and support for new syntax + features. + + **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being + implemented by Acorn. Other proposed new features must be + implemented through plugins. + +- **sourceType**: Indicate the mode the code should be parsed in. Can be + either `"script"` or `"module"`. This influences global strict mode + and parsing of `import` and `export` declarations. + + **NOTE**: If set to `"module"`, then static `import` / `export` syntax + will be valid, even if `ecmaVersion` is less than 6. + +- **onInsertedSemicolon**: If given a callback, that callback will be + called whenever a missing semicolon is inserted by the parser. The + callback will be given the character offset of the point where the + semicolon is inserted as argument, and if `locations` is on, also a + `{line, column}` object representing this position. + +- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing + commas. + +- **allowReserved**: If `false`, using a reserved word will generate + an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher + versions. When given the value `"never"`, reserved words and + keywords can also not be used as property names (as in Internet + Explorer's old parser). + +- **allowReturnOutsideFunction**: By default, a return statement at + the top level raises an error. Set this to `true` to accept such + code. + +- **allowImportExportEverywhere**: By default, `import` and `export` + declarations can only appear at a program's top level. Setting this + option to `true` allows them anywhere where a statement is allowed, + and also allows `import.meta` expressions to appear in scripts + (when `sourceType` is not `"module"`). + +- **allowAwaitOutsideFunction**: If `false`, `await` expressions can + only appear inside `async` functions. Defaults to `true` in modules + for `ecmaVersion` 2022 and later, `false` for lower versions. + Setting this option to `true` allows to have top-level `await` + expressions. They are still not allowed in non-`async` functions, + though. + +- **allowSuperOutsideMethod**: By default, `super` outside a method + raises an error. Set this to `true` to accept such code. + +- **allowHashBang**: When this is enabled, if the code starts with the + characters `#!` (as in a shellscript), the first line will be + treated as a comment. Defaults to true when `ecmaVersion` >= 2023. + +- **checkPrivateFields**: By default, the parser will verify that + private properties are only used in places where they are valid and + have been declared. Set this to false to turn such checks off. + +- **locations**: When `true`, each node has a `loc` object attached + with `start` and `end` subobjects, each of which contains the + one-based line and zero-based column numbers in `{line, column}` + form. Default is `false`. + +- **onToken**: If a function is passed for this option, each found + token will be passed in same format as tokens returned from + `tokenizer().getToken()`. + + If array is passed, each found token is pushed to it. + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **onComment**: If a function is passed for this option, whenever a + comment is encountered the function will be called with the + following parameters: + + - `block`: `true` if the comment is a block comment, false if it + is a line comment. + - `text`: The content of the comment. + - `start`: Character offset of the start of the comment. + - `end`: Character offset of the end of the comment. + + When the `locations` options is on, the `{line, column}` locations + of the comment’s start and end are passed as two additional + parameters. + + If array is passed for this option, each found comment is pushed + to it as object in Esprima format: + + ```javascript + { + "type": "Line" | "Block", + "value": "comment text", + "start": Number, + "end": Number, + // If `locations` option is on: + "loc": { + "start": {line: Number, column: Number} + "end": {line: Number, column: Number} + }, + // If `ranges` option is on: + "range": [Number, Number] + } + ``` + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **ranges**: Nodes have their start and end characters offsets + recorded in `start` and `end` properties (directly on the node, + rather than the `loc` object, which holds line/column data. To also + add a + [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) + `range` property holding a `[start, end]` array with the same + numbers, set the `ranges` option to `true`. + +- **program**: It is possible to parse multiple files into a single + AST by passing the tree produced by parsing the first file as the + `program` option in subsequent parses. This will add the toplevel + forms of the parsed file to the "Program" (top) node of an existing + parse tree. + +- **sourceFile**: When the `locations` option is `true`, you can pass + this option to add a `source` attribute in every node’s `loc` + object. Note that the contents of this option are not examined or + processed in any way; you are free to use whatever format you + choose. + +- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property + will be added (regardless of the `location` option) directly to the + nodes, rather than the `loc` object. + +- **preserveParens**: If this option is `true`, parenthesized expressions + are represented by (non-standard) `ParenthesizedExpression` nodes + that have a single `expression` property containing the expression + inside parentheses. + +**parseExpressionAt**`(input, offset, options)` will parse a single +expression in a string, and return its AST. It will not complain if +there is more of the string left after the expression. + +**tokenizer**`(input, options)` returns an object with a `getToken` +method that can be called repeatedly to get the next token, a `{start, +end, type, value}` object (with added `loc` property when the +`locations` option is enabled and `range` property when the `ranges` +option is enabled). When the token's type is `tokTypes.eof`, you +should stop calling the method, since it will keep returning that same +token forever. + +In ES6 environment, returned result can be used as any other +protocol-compliant iterable: + +```javascript +for (let token of acorn.tokenizer(str)) { + // iterate over the tokens +} + +// transform code to array of tokens: +var tokens = [...acorn.tokenizer(str)]; +``` + +**tokTypes** holds an object mapping names to the token type objects +that end up in the `type` properties of tokens. + +**getLineInfo**`(input, offset)` can be used to get a `{line, +column}` object for a given program string and offset. + +### The `Parser` class + +Instances of the **`Parser`** class contain all the state and logic +that drives a parse. It has static methods `parse`, +`parseExpressionAt`, and `tokenizer` that match the top-level +functions by the same name. + +When extending the parser with plugins, you need to call these methods +on the extended version of the class. To extend a parser with plugins, +you can use its static `extend` method. + +```javascript +var acorn = require("acorn"); +var jsx = require("acorn-jsx"); +var JSXParser = acorn.Parser.extend(jsx()); +JSXParser.parse("foo()", {ecmaVersion: 2020}); +``` + +The `extend` method takes any number of plugin values, and returns a +new `Parser` class that includes the extra parser logic provided by +the plugins. + +## Command line interface + +The `bin/acorn` utility can be used to parse a file from the command +line. It accepts as arguments its input file and the following +options: + +- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version + to parse. Default is version 9. + +- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. + +- `--locations`: Attaches a "loc" object to each node with "start" and + "end" subobjects, each of which contains the one-based line and + zero-based column numbers in `{line, column}` form. + +- `--allow-hash-bang`: If the code starts with the characters #! (as + in a shellscript), the first line will be treated as a comment. + +- `--allow-await-outside-function`: Allows top-level `await` expressions. + See the `allowAwaitOutsideFunction` option for more information. + +- `--compact`: No whitespace is used in the AST output. + +- `--silent`: Do not output the AST, just return the exit status. + +- `--help`: Print the usage information and quit. + +The utility spits out the syntax tree as JSON data. + +## Existing plugins + + - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) diff --git a/node_modules/espree/node_modules/acorn/bin/acorn b/node_modules/espree/node_modules/acorn/bin/acorn new file mode 100755 index 0000000..3ef3c12 --- /dev/null +++ b/node_modules/espree/node_modules/acorn/bin/acorn @@ -0,0 +1,4 @@ +#!/usr/bin/env node +"use strict" + +require("../dist/bin.js") diff --git a/node_modules/espree/node_modules/acorn/dist/acorn.d.mts b/node_modules/espree/node_modules/acorn/dist/acorn.d.mts new file mode 100644 index 0000000..49ae59f --- /dev/null +++ b/node_modules/espree/node_modules/acorn/dist/acorn.d.mts @@ -0,0 +1,26 @@ +export { + Node, + Parser, + Position, + SourceLocation, + TokContext, + Token, + TokenType, + defaultOptions, + getLineInfo, + isIdentifierChar, + isIdentifierStart, + isNewLine, + lineBreak, + lineBreakG, + parse, + parseExpressionAt, + tokContexts, + tokTypes, + tokenizer, + version, + AbstractToken, + Comment, + Options, + ecmaVersion, +} from "./acorn.js"; diff --git a/node_modules/espree/node_modules/acorn/dist/acorn.d.ts b/node_modules/espree/node_modules/acorn/dist/acorn.d.ts new file mode 100644 index 0000000..5b26741 --- /dev/null +++ b/node_modules/espree/node_modules/acorn/dist/acorn.d.ts @@ -0,0 +1,292 @@ +export as namespace acorn +export = acorn + +declare namespace acorn { + function parse(input: string, options: Options): Node + + function parseExpressionAt(input: string, pos: number, options: Options): Node + + function tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + + type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 'latest' + + interface Options { + ecmaVersion: ecmaVersion + sourceType?: 'script' | 'module' + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + allowReserved?: boolean | 'never' + allowReturnOutsideFunction?: boolean + allowImportExportEverywhere?: boolean + allowAwaitOutsideFunction?: boolean + allowSuperOutsideMethod?: boolean + allowHashBang?: boolean + locations?: boolean + onToken?: ((token: Token) => any) | Token[] + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, + endLoc?: Position + ) => void) | Comment[] + ranges?: boolean + program?: Node + sourceFile?: string + directSourceFile?: string + preserveParens?: boolean + } + + class Parser { + // state.js + lineStart: number; + options: Options; + curLine: number; + start: number; + end: number; + input: string; + type: TokenType; + + // state.js + constructor(options: Options, input: string, startPos?: number) + parse(this: Parser): Node + + // tokenize.js + next(): void; + nextToken(): void; + + // statement.js + parseTopLevel(node: Node): Node; + + // node.js + finishNode(node: Node, type: string): Node; + finishNodeAt(node: Node, type: string, pos: number, loc: Position): Node; + + // location.js + raise(pos: number, message: string) : void; + raiseRecoverable?(pos: number, message: string) : void; + + // parseutils.js + unexpected(pos: number) : void; + + // index.js + static acorn: typeof acorn; + + // state.js + static parse(this: typeof Parser, input: string, options: Options): Node + static parseExpressionAt(this: typeof Parser, input: string, pos: number, options: Options): Node + static tokenizer(this: typeof Parser, input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + static extend(this: typeof Parser, ...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser + } + + interface Position { line: number; column: number; offset: number } + + const defaultOptions: Options + + function getLineInfo(input: string, offset: number): Position + + class SourceLocation { + start: Position + end: Position + source?: string | null + constructor(p: Parser, start: Position, end: Position) + } + + class Node { + type: string + start: number + end: number + loc?: SourceLocation + sourceFile?: string + range?: [number, number] + constructor(parser: Parser, pos: number, loc?: SourceLocation) + } + + class TokenType { + label: string + keyword: string + beforeExpr: boolean + startsExpr: boolean + isLoop: boolean + isAssign: boolean + prefix: boolean + postfix: boolean + binop: number + updateContext?: (prevType: TokenType) => void + constructor(label: string, conf?: any) + } + + const tokTypes: { + num: TokenType + regexp: TokenType + string: TokenType + name: TokenType + privateId: TokenType + eof: TokenType + bracketL: TokenType + bracketR: TokenType + braceL: TokenType + braceR: TokenType + parenL: TokenType + parenR: TokenType + comma: TokenType + semi: TokenType + colon: TokenType + dot: TokenType + question: TokenType + questionDot: TokenType + arrow: TokenType + template: TokenType + invalidTemplate: TokenType + ellipsis: TokenType + backQuote: TokenType + dollarBraceL: TokenType + eq: TokenType + assign: TokenType + incDec: TokenType + prefix: TokenType + logicalOR: TokenType + logicalAND: TokenType + bitwiseOR: TokenType + bitwiseXOR: TokenType + bitwiseAND: TokenType + equality: TokenType + relational: TokenType + bitShift: TokenType + plusMin: TokenType + modulo: TokenType + star: TokenType + slash: TokenType + starstar: TokenType + coalesce: TokenType + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType + } + + class TokContext { + constructor(token: string, isExpr: boolean, preserveSpace: boolean, override?: (p: Parser) => void) + } + + const tokContexts: { + b_stat: TokContext + b_expr: TokContext + b_tmpl: TokContext + p_stat: TokContext + p_expr: TokContext + q_tmpl: TokContext + f_expr: TokContext + f_stat: TokContext + f_expr_gen: TokContext + f_gen: TokContext + } + + function isIdentifierStart(code: number, astral?: boolean): boolean + + function isIdentifierChar(code: number, astral?: boolean): boolean + + interface AbstractToken { + } + + interface Comment extends AbstractToken { + type: 'Line' | 'Block' + value: string + start: number + end: number + loc?: SourceLocation + range?: [number, number] + } + + class Token { + type: TokenType + value: any + start: number + end: number + loc?: SourceLocation + range?: [number, number] + constructor(p: Parser) + } + + function isNewLine(code: number): boolean + + const lineBreak: RegExp + + const lineBreakG: RegExp + + const version: string + + const nonASCIIwhitespace: RegExp + + const keywordTypes: { + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType + } +} diff --git a/node_modules/espree/node_modules/acorn/dist/acorn.js b/node_modules/espree/node_modules/acorn/dist/acorn.js new file mode 100644 index 0000000..62e1aa6 --- /dev/null +++ b/node_modules/espree/node_modules/acorn/dist/acorn.js @@ -0,0 +1,5990 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.acorn = {})); +})(this, (function (exports) { 'use strict'; + + // This file was generated. Do not modify manually! + var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + + // This file was generated. Do not modify manually! + var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191]; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + + // These are a run-length and offset encoded representation of the + // >0xffff code points that are a valid part of identifiers. The + // offset starts at 0x10000, and each pair of numbers represents an + // offset to the next range, and then a size of the range. + + // Reserved word lists for various dialects of the language + + var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" + }; + + // And the keywords + + var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + + var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" + }; + + var keywordRelationalOperator = /^in(stanceof)?$/; + + // ## Character categories + + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + // This has a complexity linear to the value of the code. The + // assumption is that looking up astral identifier characters is + // rare. + function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } + return false + } + + // Test whether a given character code starts an identifier. + + function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) + } + + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) + } + + // ## Token types + + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. + + // All token type variables start with an underscore, to make them + // easy to recognize. + + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // The `startsExpr` property is used to check if the token ends a + // `yield` expression. It is set on all token types that either can + // directly start an expression (like a quotation mark) or can + // continue an expression (like the body of a string). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; + }; + + function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) + } + var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; + + // Map keyword names to token types. + + var keywords = {}; + + // Succinct definitions of keyword token types + function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords[name] = new TokenType(name, options) + } + + var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) + }; + + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. + + var lineBreak = /\r\n?|\n|\u2028|\u2029/; + var lineBreakG = new RegExp(lineBreak.source, "g"); + + function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 + } + + function nextLineBreak(code, from, end) { + if ( end === void 0 ) end = code.length; + + for (var i = from; i < end; i++) { + var next = code.charCodeAt(i); + if (isNewLine(next)) + { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } + } + return -1 + } + + var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + + var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + + var ref = Object.prototype; + var hasOwnProperty = ref.hasOwnProperty; + var toString = ref.toString; + + var hasOwn = Object.hasOwn || (function (obj, propName) { return ( + hasOwnProperty.call(obj, propName) + ); }); + + var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" + ); }); + + function wordsRegexp(words) { + return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") + } + + function codePointToString(code) { + // UTF-16 Decoding + if (code <= 0xFFFF) { return String.fromCharCode(code) } + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) + } + + var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; + + // These are used when `options.locations` is on, for the + // `startLoc` and `endLoc` properties. + + var Position = function Position(line, col) { + this.line = line; + this.column = col; + }; + + Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) + }; + + var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } + }; + + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + var nextBreak = nextLineBreak(input, cur, offset); + if (nextBreak < 0) { return new Position(line, offset - cur) } + ++line; + cur = nextBreak; + } + } + + // A second argument must be given to configure the parser process. + // These options are recognized (only `ecmaVersion` is required): + + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + // (the latest version the library supports). This influences + // support for strict mode, the set of reserved words, and support + // for new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called + // when a semicolon is automatically inserted. It will be passed + // the position of the comma as an offset, and if `locations` is + // enabled, it is given the location as a `{line, column}` object + // as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file is + // allowed and treated as a line comment. Enabled by default when + // `ecmaVersion` >= 2023. + allowHashBang: false, + // By default, the parser will verify that private properties are + // only used in places where they are valid and have been declared. + // Set this to false to turn such checks off. + checkPrivateFields: true, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false + }; + + // Interpret and default an options object + + var warnedAboutEcmaVersion = false; + + function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (!opts || opts.allowHashBang == null) + { options.allowHashBang = options.ecmaVersion >= 14; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options + } + + function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } + } + + // Each scope gets a bitset that may contain these flags + var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128, + SCOPE_CLASS_STATIC_BLOCK = 256, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; + + function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + } + + // Used in checkLVal* and declareName to determine the type of a binding + var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + + var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types$1.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; + + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; + }; + + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; + + Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) + }; + + prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; + + prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; + + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; + + prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } + if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction + }; + + prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod + }; + + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + + prototypeAccessors.allowNewDotTarget.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit + }; + + prototypeAccessors.inClassStaticBlock.get = function () { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 + }; + + Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls + }; + + Parser.parse = function parse (input, options) { + return new this(options, input).parse() + }; + + Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() + }; + + Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) + }; + + Object.defineProperties( Parser.prototype, prototypeAccessors ); + + var pp$9 = Parser.prototype; + + // ## Parser utilities + + var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; + pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { return false } + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; + + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } + }; + + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. + + pp$9.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } + }; + + // Tests whether parsed token is a contextual keyword. + + pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc + }; + + // Consumes contextual keyword if possible. + + pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true + }; + + // Asserts that following token is given contextual keyword. + + pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } + }; + + // Test whether a semicolon can be inserted at the current position. + + pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || + this.type === types$1.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } + }; + + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. + + pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } + }; + + pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } + }; + + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. + + pp$9.expect = function(type) { + this.eat(type) || this.unexpected(); + }; + + // Raise an unexpected token error. + + pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); + }; + + var DestructuringErrors = function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; + }; + + pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } + }; + + pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } + }; + + pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } + }; + + pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" + }; + + var pp$8 = Parser.prototype; + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + pp$8.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") + }; + + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92) { return true } // '[', '/' + if (context) { return false } + + if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false + }; + + // check 'async [no LineTerminator here] function' + // - 'async /*foo*/ function' is OK. + // - 'async /*\n*/ function' is invalid. + pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) + }; + + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo)`, where looking at the previous token + // does not help. + + pp$8.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types$1._debugger: return this.parseDebuggerStatement(node) + case types$1._do: return this.parseDoStatement(node) + case types$1._for: return this.parseForStatement(node) + case types$1._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types$1._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types$1._if: return this.parseIfStatement(node) + case types$1._return: return this.parseReturnStatement(node) + case types$1._switch: return this.parseSwitchStatement(node) + case types$1._throw: return this.parseThrowStatement(node) + case types$1._try: return this.parseTryStatement(node) + case types$1._const: case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types$1._while: return this.parseWhileStatement(node) + case types$1._with: return this.parseWithStatement(node) + case types$1.braceL: return this.parseBlock(true, node) + case types$1.semi: return this.parseEmptyStatement(node) + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } + + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } + }; + + pp$8.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types$1.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") + }; + + pp$8.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") + }; + + pp$8.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types$1.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") + }; + + // Disambiguating between a `for` and a `for`/`in` or `for`/`of` + // loop is non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in` or `of`. When there is no init + // part (semicolon immediately after the opening parenthesis), it + // is a regular `for` loop. + + pp$8.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; + + pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) + }; + + pp$8.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") + }; + + pp$8.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") + }; + + pp$8.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types$1.braceR;) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") + }; + + pp$8.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") + }; + + // Reused empty array added for node fields that are always empty. + + var empty$1 = []; + + pp$8.parseCatchClauseParam = function() { + var param = this.parseBindingAtom(); + var simple = param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + + return param + }; + + pp$8.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseCatchClauseParam(); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") + }; + + pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + }; + + pp$8.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") + }; + + pp$8.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") + }; + + pp$8.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") + }; + + pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") + }; + + pp$8.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") + }; + + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). + + pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") + }; + + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + pp$8.parseFor = function(node, init) { + node.init = init; + this.expect(types$1.semi); + node.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") + }; + + // Parse a `for`/`in` and `for`/`of` loop, which are almost + // same from parser's perspective. + + pp$8.parseForIn = function(node, init) { + var isForIn = this.type === types$1._in; + this.next(); + + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") + }; + + // Parse a list of variable declarations. + + pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { break } + } + return node + }; + + pp$8.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); + }; + + var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + + // Parse a function declaration or literal (depending on the + // `statement & FUNC_STATEMENT`). + + // Remove `allowExpressionBody` for 7.0.0, as it is only called with false + pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types$1.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") + }; + + pp$8.parseFunctionParams = function(node) { + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + }; + + // Parse a class declaration or literal (depending on the + // `isStatement` parameter). + + pp$8.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; + + pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + + if (this.eatContextual("static")) { + // Parse static init block + if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node); + return node + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + + // Parse element value + if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + + return node + }; + + pp$8.isClassElementNameStart = function() { + return ( + this.type === types$1.name || + this.type === types$1.privateId || + this.type === types$1.num || + this.type === types$1.string || + this.type === types$1.bracketL || + this.type.keyword + ) + }; + + pp$8.parseClassElementName = function(element) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } + }; + + pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } + + return this.finishNode(method, "MethodDefinition") + }; + + pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + + if (this.eat(types$1.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + + return this.finishNode(field, "PropertyDefinition") + }; + + pp$8.parseClassStaticBlock = function(node) { + node.body = []; + + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + + return this.finishNode(node, "StaticBlock") + }; + + pp$8.parseClassId = function(node, isStatement) { + if (this.type === types$1.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; + } + }; + + pp$8.parseClassSuper = function(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; + }; + + pp$8.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared + }; + + pp$8.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + if (!this.options.checkPrivateFields) { return } + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!hasOwn(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); + } + } + } + }; + + function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true + } + } + + function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) + } + + // Parses module export declaration. + + pp$8.parseExportAllDeclaration = function(node, exports) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + }; + + pp$8.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node, exports) + } + if (this.eat(types$1._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + node.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseExportDeclaration(node); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") + }; + + pp$8.parseExportDeclaration = function(node) { + return this.parseStatement(null) + }; + + pp$8.parseExportDefaultDeclaration = function() { + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync) + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + return this.parseClass(cNode, "nullableID") + } else { + var declaration = this.parseMaybeAssign(); + this.semicolon(); + return declaration + } + }; + + pp$8.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (typeof name !== "string") + { name = name.type === "Identifier" ? name.name : name.value; } + if (hasOwn(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; + }; + + pp$8.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + else if (type === "ParenthesizedExpression") + { this.checkPatternExport(exports, pat.expression); } + }; + + pp$8.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); + } + }; + + pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() + }; + + // Parses a comma-separated list of module exports. + + pp$8.parseExportSpecifier = function(exports) { + var node = this.startNode(); + node.local = this.parseModuleExportName(); + + node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; + this.checkExport( + exports, + node.exported, + node.exported.start + ); + + return this.finishNode(node, "ExportSpecifier") + }; + + pp$8.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseExportSpecifier(exports)); + } + return nodes + }; + + // Parses import declaration. + + pp$8.parseImport = function(node) { + this.next(); + + // import '...' + if (this.type === types$1.string) { + node.specifiers = empty$1; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") + }; + + // Parses a comma-separated list of module imports. + + pp$8.parseImportSpecifier = function() { + var node = this.startNode(); + node.imported = this.parseModuleExportName(); + + if (this.eatContextual("as")) { + node.local = this.parseIdent(); + } else { + this.checkUnreserved(node.imported); + node.local = node.imported; + } + this.checkLValSimple(node.local, BIND_LEXICAL); + + return this.finishNode(node, "ImportSpecifier") + }; + + pp$8.parseImportDefaultSpecifier = function() { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportDefaultSpecifier") + }; + + pp$8.parseImportNamespaceSpecifier = function() { + var node = this.startNode(); + this.next(); + this.expectContextual("as"); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportNamespaceSpecifier") + }; + + pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(types$1.comma)) { return nodes } + } + if (this.type === types$1.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseImportSpecifier()); + } + return nodes + }; + + pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral + } + return this.parseIdent(true) + }; + + // Set `ExpressionStatement#directive` property for directive prologues. + pp$8.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } + }; + pp$8.isDirectiveCandidate = function(statement) { + return ( + this.options.ecmaVersion >= 5 && + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) + }; + + var pp$7 = Parser.prototype; + + // Convert existing expression atom to assignable pattern + // if possible. + + pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node + }; + + // Convert list of expression atoms to binding list. + + pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList + }; + + // Parses spread element. + + pp$7.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") + }; + + pp$7.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") + }; + + // Parses lvalue (assignable) atom. + + pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types$1.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() + }; + + pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types$1.comma); } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types$1.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + elts.push(this.parseAssignableListItem(allowModifiers)); + } + } + return elts + }; + + pp$7.parseAssignableListItem = function(allowModifiers) { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + return elem + }; + + pp$7.parseBindingListItem = function(param) { + return param + }; + + // Parses assignment pattern around given atom if possible. + + pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") + }; + + // The following three functions all verify that a node is an lvalue — + // something that can be bound, or assigned to. In order to do so, they perform + // a variety of checks: + // + // - Check that none of the bound/assigned-to identifiers are reserved words. + // - Record name declarations for bindings in the appropriate scope. + // - Check duplicate argument names, if checkClashes is set. + // + // If a complex binding pattern is encountered (e.g., object and array + // destructuring), the entire pattern is recursively checked. + // + // There are three versions of checkLVal*() appropriate for different + // circumstances: + // + // - checkLValSimple() shall be used if the syntactic construct supports + // nothing other than identifiers and member expressions. Parenthesized + // expressions are also correctly handled. This is generally appropriate for + // constructs for which the spec says + // + // > It is a Syntax Error if AssignmentTargetType of [the production] is not + // > simple. + // + // It is also appropriate for checking if an identifier is valid and not + // defined elsewhere, like import declarations or function/class identifiers. + // + // Examples where this is used include: + // a += …; + // import a from '…'; + // where a is the node to be checked. + // + // - checkLValPattern() shall be used if the syntactic construct supports + // anything checkLValSimple() supports, as well as object and array + // destructuring patterns. This is generally appropriate for constructs for + // which the spec says + // + // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor + // > an ArrayLiteral and AssignmentTargetType of [the production] is not + // > simple. + // + // Examples where this is used include: + // (a = …); + // const a = …; + // try { … } catch (a) { … } + // where a is the node to be checked. + // + // - checkLValInnerPattern() shall be used if the syntactic construct supports + // anything checkLValPattern() supports, as well as default assignment + // patterns, rest elements, and other constructs that may appear within an + // object or array destructuring pattern. + // + // As a special case, function parameters also use checkLValInnerPattern(), + // as they also support defaults and rest constructs. + // + // These functions deliberately support both assignment and binding constructs, + // as the logic for both is exceedingly similar. If the node is the target of + // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it + // should be set to the appropriate BIND_* constant, like BIND_VAR or + // BIND_LEXICAL. + // + // If the function is called with a non-BIND_NONE bindingType, then + // additionally a checkClashes object may be specified to allow checking for + // duplicate argument names. checkClashes is ignored if the provided construct + // is an assignment (i.e., bindingType is BIND_NONE). + + pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break + + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } + }; + + pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } + }; + + pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break + + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } + }; + + // The algorithm used to determine whether a regexp can appear at a + // given point in the program is loosely based on sweet.js' approach. + // See https://github.com/mozilla/sweet.js/wiki/design + + + var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; + }; + + var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) + }; + + var pp$6 = Parser.prototype; + + pp$6.initialContext = function() { + return [types.b_stat] + }; + + pp$6.curContext = function() { + return this.context[this.context.length - 1] + }; + + pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types.f_expr || parent === types.f_stat) + { return true } + if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) + { return true } + if (prevType === types$1.braceL) + { return parent === types.b_stat } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) + { return false } + return !this.exprAllowed + }; + + pp$6.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } + } + return false + }; + + pp$6.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types$1.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } + }; + + // Used to handle egde cases when token context could not be inferred correctly during tokenization phase + + pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } + }; + + // Token-specific context update code + + types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; + }; + + types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); + this.exprAllowed = true; + }; + + types$1.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl); + this.exprAllowed = true; + }; + + types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types.p_stat : types.p_expr); + this.exprAllowed = true; + }; + + types$1.incDec.updateContext = function() { + // tokExprAllowed stays unchanged + }; + + types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && + !(prevType === types$1.semi && this.curContext() !== types.p_stat) && + !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) + { this.context.push(types.f_expr); } + else + { this.context.push(types.f_stat); } + this.exprAllowed = false; + }; + + types$1.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types.q_tmpl); } + this.exprAllowed = false; + }; + + types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index = this.context.length - 1; + if (this.context[index] === types.f_expr) + { this.context[index] = types.f_expr_gen; } + else + { this.context[index] = types.f_gen; } + } + this.exprAllowed = true; + }; + + types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; + }; + + // A recursive descent parser operates by defining functions for all + // syntactic elements, and recursively calling those, each function + // advancing the input stream and returning an AST node. Precedence + // of constructs (for example, the fact that `!x[1]` means `!(x[1])` + // instead of `(!x)[1]` is handled by the fact that the parser + // function that parses unary prefix operators is called first, and + // in turn calls the function that parses `[]` subscripts — that + // way, it'll receive the node for `x[1]` already parsed, and wraps + // *that* in the unary operator node. + // + // Acorn uses an [operator precedence parser][opp] to handle binary + // operator precedence, because it is much more compact than using + // the technique outlined above, which uses different, nesting + // functions to specify precedence, for all of the ten binary + // precedence levels that JavaScript defines. + // + // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + + + var pp$5 = Parser.prototype; + + // Check if property name clashes with already added. + // Object/class getters and setters are not allowed to clash — + // either with each other or with an init property — and in + // strict mode, init properties are also not allowed to be repeated. + + pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key.start; + } + } else { + this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; + }; + + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The optional arguments are used to + // forbid the `in` operator (in for loops initalization expressions) + // and provide reference for storing '=' operator inside shorthand + // property assignment in contexts where both object expression + // and object pattern might appear (so it's possible to raise + // delayed syntax error at correct position). + + pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types$1.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr + }; + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types$1.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types$1.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left + }; + + // Parse a ternary conditional (`?:`) operator. + + pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types$1.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") + } + return expr + }; + + // Start the precedence parser. + + pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) + }; + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left + }; + + pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { + if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") + }; + + // Parse unary operators, both prefix and postfix. + + pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types$1.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } + expr = this.parsePrivateIdent(); + // only could be private fields in 'in', such as #x in obj + if (this.type !== types$1._in) { this.unexpected(); } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } + } else { + return expr + } + }; + + function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) + ) + } + + // Parse call, dot, and `[]`-subscript expressions. + + pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result + }; + + pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; + + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element + } + + base = element; + } + }; + + pp$5.shouldParseAsyncArrow = function() { + return !this.canInsertSemicolon() && this.eat(types$1.arrow) + }; + + pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) + }; + + pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types$1.bracketL); + if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base + }; + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types$1.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) + } + } + return id + + case types$1.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types$1.num: case types$1.string: + return this.parseLiteral(this.value) + + case types$1._null: case types$1._true: case types$1._false: + node = this.startNode(); + node.value = this.type === types$1._null ? null : this.type === types$1._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types$1.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types$1.braceL: + this.overrideContext(types.b_expr); + return this.parseObj(false, refDestructuringErrors) + + case types$1._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types$1._class: + return this.parseClass(this.startNode(), false) + + case types$1._new: + return this.parseNew() + + case types$1.backQuote: + return this.parseTemplate() + + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(forNew) + } else { + return this.unexpected() + } + + default: + return this.parseExprAtomDefault() + } + }; + + pp$5.parseExprAtomDefault = function() { + this.unexpected(); + }; + + pp$5.parseExprImport = function(forNew) { + var node = this.startNode(); + + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + var meta = this.parseIdent(true); + + if (this.type === types$1.parenL && !forNew) { + return this.parseDynamicImport(node) + } else if (this.type === types$1.dot) { + node.meta = meta; + return this.parseImportMeta(node) + } else { + this.unexpected(); + } + }; + + pp$5.parseDynamicImport = function(node) { + this.next(); // skip `(` + + // Parse node.source. + node.source = this.parseMaybeAssign(); + + // Verify ending. + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + + return this.finishNode(node, "ImportExpression") + }; + + pp$5.parseImportMeta = function(node) { + this.next(); // skip `.` + + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") + }; + + pp$5.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") + }; + + pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val + }; + + pp$5.shouldParseArrow = function(exprList) { + return !this.canInsertSemicolon() + }; + + pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raiseRecoverable( + this.start, + "Comma is not permitted after the rest element" + ); + } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } + }; + + pp$5.parseParenItem = function(item) { + return item + }; + + pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) + }; + + // New's precedence is slightly tricky. It must allow its argument to + // be a `[]` or dot subscript expression, but not a call — at least, + // not without wrapping it in parentheses. Thus, it uses the noCalls + // argument to parseSubscripts to prevent it from consuming the + // argument list. + + var empty = []; + + pp$5.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + var meta = this.parseIdent(true); + if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) { + node.meta = meta; + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.allowNewDotTarget) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); + if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty; } + return this.finishNode(node, "NewExpression") + }; + + // Parse template expression. + + pp$5.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement") + }; + + pp$5.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") + }; + + pp$5.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + // Parse an object literal or binding pattern. + + pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") + }; + + pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types$1.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") + }; + + pp$5.parseGetterSetter = function(prop) { + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + }; + + pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) + { this.unexpected(); } + + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + this.parseGetterSetter(prop); + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { this.unexpected(); } + }; + + pp$5.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") + }; + + // Initialize empty function node. + + pp$5.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } + }; + + // Parse object or class method. + + pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; + + // Parse arrow function expression with given parameters. + + pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; + + // Parse function body and check parameters. + + pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); + }; + + pp$5.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true + }; + + // Checks function params for various disallowed patterns such as using "eval" + // or "arguments" and duplicate parameters. + + pp$5.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } + }; + + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types$1.comma) + { elt = null; } + else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts + }; + + pp$5.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (this.currentThisScope().inClassFieldInit && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) + { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } + }; + + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + pp$5.parseIdent = function(liberal) { + var node = this.parseIdentNode(); + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; + + pp$5.parseIdentNode = function() { + var node = this.startNode(); + if (this.type === types$1.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + } else { + this.unexpected(); + } + return node + }; + + pp$5.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types$1.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + + // For validating existence + if (this.options.checkPrivateFields) { + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + } + + return node + }; + + // Parses yield expression inside generator. + + pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types$1.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") + }; + + pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression") + }; + + var pp$4 = Parser.prototype; + + // This function is used to raise exceptions on parse errors. It + // takes an offset integer (into the current `input`) to indicate + // the location of the error, attaches the position to the end + // of the error message, and then raises a `SyntaxError` with that + // message. + + pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err + }; + + pp$4.raiseRecoverable = pp$4.raise; + + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } + }; + + var pp$3 = Parser.prototype; + + var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + // A switch to disallow the identifier reference 'arguments' + this.inClassFieldInit = false; + }; + + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + + pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; + + pp$3.exitScope = function() { + this.scopeStack.pop(); + }; + + // The spec says: + // > At the top level of a function, or script, function declarations are + // > treated like var declarations rather than like lexical declarations. + pp$3.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; + + pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break + } + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } + }; + + pp$3.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } + }; + + pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; + + pp$3.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } + }; + + // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. + pp$3.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } + } + }; + + var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } + }; + + // Start an AST node, attaching a start offset. + + var pp$2 = Parser.prototype; + + pp$2.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; + + pp$2.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) + }; + + // Finish an AST node, adding `type` and `end` properties. + + function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node + } + + pp$2.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; + + // Finish node at given position + + pp$2.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; + + pp$2.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode + }; + + // This file contains Unicode properties extracted from the ECMAScript specification. + // The lists are extracted like so: + // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + + // #table-binary-unicode-properties + var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; + var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; + var ecma11BinaryProperties = ecma10BinaryProperties; + var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; + var ecma13BinaryProperties = ecma12BinaryProperties; + var ecma14BinaryProperties = ecma13BinaryProperties; + + var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties + }; + + // #table-binary-unicode-properties-of-strings + var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; + + var unicodeBinaryPropertiesOfStrings = { + 9: "", + 10: "", + 11: "", + 12: "", + 13: "", + 14: ecma14BinaryPropertiesOfStrings + }; + + // #table-unicode-general-category-values + var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + + // #table-unicode-script-values + var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; + var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; + var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; + var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; + var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; + var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz"; + + var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues + }; + + var data = {}; + function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; + } + + for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) { + var ecmaVersion = list[i]; + + buildUnicodeData(ecmaVersion); + } + + var pp$1 = Parser.prototype; + + var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchV = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; + }; + + RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicodeSets = flags.indexOf("v") !== -1; + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + if (unicodeSets && this.parser.options.ecmaVersion >= 15) { + this.switchU = true; + this.switchV = true; + this.switchN = true; + } else { + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchV = false; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + } + }; + + RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); + }; + + // If u flag is given, this returns the code point at the index (it combines a surrogate pair). + // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). + RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c + }; + + RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 + }; + + RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.pos, forceU) + }; + + RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.nextIndex(this.pos, forceU), forceU) + }; + + RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; + + this.pos = this.nextIndex(this.pos, forceU); + }; + + RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; + + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false + }; + + RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) { + if ( forceU === void 0 ) forceU = false; + + var pos = this.pos; + for (var i = 0, list = chs; i < list.length; i += 1) { + var ch = list[i]; + + var current = this.at(pos, forceU); + if (current === -1 || current !== ch) { + return false + } + pos = this.nextIndex(pos, forceU); + } + this.pos = pos; + return true + }; + + /** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + var u = false; + var v = false; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + if (flag === "u") { u = true; } + if (flag === "v") { v = true; } + } + if (this.options.ecmaVersion >= 15 && u && v) { + this.raise(state.start, "Invalid regular expression flag"); + } + }; + + /** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern + pp$1.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction + pp$1.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this.regexp_alternative(state); + } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative + pp$1.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term + pp$1.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion + pp$1.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier + pp$1.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix + pp$1.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) + }; + pp$1.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom + pp$1.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) + }; + pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom + pp$1.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier + pp$1.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter + pp$1.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter + // But eat eager. + pp$1.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter + pp$1.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false + }; + + // GroupSpecifier :: + // [empty] + // `?` GroupName + pp$1.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } + }; + + // GroupName :: + // `<` RegExpIdentifierName `>` + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false + }; + + // RegExpIdentifierName :: + // RegExpIdentifierStart + // RegExpIdentifierName RegExpIdentifierPart + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true + } + return false + }; + + // RegExpIdentifierStart :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + pp$1.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ + } + + // RegExpIdentifierPart :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + // + // + pp$1.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape + pp$1.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false + }; + pp$1.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape + pp$1.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) + }; + pp$1.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape + pp$1.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter + pp$1.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence + pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false + }; + function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape + pp$1.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape + pp$1.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false + }; + + // Return values used by character set parsing methods, needed to + // forbid negation of sets that can match strings. + var CharSetNone = 0; // Nothing parsed + var CharSetOk = 1; // Construct parsed, cannot contain strings + var CharSetString = 2; // Construct parsed, can contain strings + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape + pp$1.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return CharSetOk + } + + var negate = false; + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + var result; + if ( + state.eat(0x7B /* { */) && + (result = this.regexp_eatUnicodePropertyValueExpression(state)) && + state.eat(0x7D /* } */) + ) { + if (negate && result === CharSetString) { state.raise("Invalid property name"); } + return result + } + state.raise("Invalid property name"); + } + + return CharSetNone + }; + + function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) + } + + // UnicodePropertyValueExpression :: + // UnicodePropertyName `=` UnicodePropertyValue + // LoneUnicodePropertyNameOrValue + pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return CharSetOk + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) + } + return CharSetNone + }; + + pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!hasOwn(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } + }; + + pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk } + if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString } + state.raise("Invalid property name"); + }; + + // UnicodePropertyName :: + // UnicodePropertyNameCharacters + pp$1.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + + function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ + } + + // UnicodePropertyValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) + } + + // LoneUnicodePropertyNameOrValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass + pp$1.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (!state.eat(0x5D /* ] */)) + { state.raise("Unterminated character class"); } + if (negate && result === CharSetString) + { state.raise("Negated character class may contain strings"); } + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassContents + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges + pp$1.regexp_classContents = function(state) { + if (state.current() === 0x5D /* ] */) { return CharSetOk } + if (state.switchV) { return this.regexp_classSetExpression(state) } + this.regexp_nonEmptyClassRanges(state); + return CharSetOk + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash + pp$1.regexp_nonEmptyClassRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash + pp$1.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape + pp$1.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) + }; + + // https://tc39.es/ecma262/#prod-ClassSetExpression + // https://tc39.es/ecma262/#prod-ClassUnion + // https://tc39.es/ecma262/#prod-ClassIntersection + // https://tc39.es/ecma262/#prod-ClassSubtraction + pp$1.regexp_classSetExpression = function(state) { + var result = CharSetOk, subResult; + if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { + if (subResult === CharSetString) { result = CharSetString; } + // https://tc39.es/ecma262/#prod-ClassIntersection + var start = state.pos; + while (state.eatChars([0x26, 0x26] /* && */)) { + if ( + state.current() !== 0x26 /* & */ && + (subResult = this.regexp_eatClassSetOperand(state)) + ) { + if (subResult !== CharSetString) { result = CharSetOk; } + continue + } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + // https://tc39.es/ecma262/#prod-ClassSubtraction + while (state.eatChars([0x2D, 0x2D] /* -- */)) { + if (this.regexp_eatClassSetOperand(state)) { continue } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + } else { + state.raise("Invalid character in character class"); + } + // https://tc39.es/ecma262/#prod-ClassUnion + for (;;) { + if (this.regexp_eatClassSetRange(state)) { continue } + subResult = this.regexp_eatClassSetOperand(state); + if (!subResult) { return result } + if (subResult === CharSetString) { result = CharSetString; } + } + }; + + // https://tc39.es/ecma262/#prod-ClassSetRange + pp$1.regexp_eatClassSetRange = function(state) { + var start = state.pos; + if (this.regexp_eatClassSetCharacter(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) { + var right = state.lastIntValue; + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + return true + } + state.pos = start; + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetOperand + pp$1.regexp_eatClassSetOperand = function(state) { + if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk } + return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) + }; + + // https://tc39.es/ecma262/#prod-NestedClass + pp$1.regexp_eatNestedClass = function(state) { + var start = state.pos; + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (state.eat(0x5D /* ] */)) { + if (negate && result === CharSetString) { + state.raise("Negated character class may contain strings"); + } + return result + } + state.pos = start; + } + if (state.eat(0x5C /* \ */)) { + var result$1 = this.regexp_eatCharacterClassEscape(state); + if (result$1) { + return result$1 + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunction + pp$1.regexp_eatClassStringDisjunction = function(state) { + var start = state.pos; + if (state.eatChars([0x5C, 0x71] /* \q */)) { + if (state.eat(0x7B /* { */)) { + var result = this.regexp_classStringDisjunctionContents(state); + if (state.eat(0x7D /* } */)) { + return result + } + } else { + // Make the same message as V8. + state.raise("Invalid escape"); + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents + pp$1.regexp_classStringDisjunctionContents = function(state) { + var result = this.regexp_classString(state); + while (state.eat(0x7C /* | */)) { + if (this.regexp_classString(state) === CharSetString) { result = CharSetString; } + } + return result + }; + + // https://tc39.es/ecma262/#prod-ClassString + // https://tc39.es/ecma262/#prod-NonEmptyClassString + pp$1.regexp_classString = function(state) { + var count = 0; + while (this.regexp_eatClassSetCharacter(state)) { count++; } + return count === 1 ? CharSetOk : CharSetString + }; + + // https://tc39.es/ecma262/#prod-ClassSetCharacter + pp$1.regexp_eatClassSetCharacter = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if ( + this.regexp_eatCharacterEscape(state) || + this.regexp_eatClassSetReservedPunctuator(state) + ) { + return true + } + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + state.pos = start; + return false + } + var ch = state.current(); + if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false } + if (isClassSetSyntaxCharacter(ch)) { return false } + state.advance(); + state.lastIntValue = ch; + return true + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator + function isClassSetReservedDoublePunctuatorCharacter(ch) { + return ( + ch === 0x21 /* ! */ || + ch >= 0x23 /* # */ && ch <= 0x26 /* & */ || + ch >= 0x2A /* * */ && ch <= 0x2C /* , */ || + ch === 0x2E /* . */ || + ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ || + ch === 0x5E /* ^ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter + function isClassSetSyntaxCharacter(ch) { + return ( + ch === 0x28 /* ( */ || + ch === 0x29 /* ) */ || + ch === 0x2D /* - */ || + ch === 0x2F /* / */ || + ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + pp$1.regexp_eatClassSetReservedPunctuator = function(state) { + var ch = state.current(); + if (isClassSetReservedPunctuator(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + function isClassSetReservedPunctuator(ch) { + return ( + ch === 0x21 /* ! */ || + ch === 0x23 /* # */ || + ch === 0x25 /* % */ || + ch === 0x26 /* & */ || + ch === 0x2C /* , */ || + ch === 0x2D /* - */ || + ch >= 0x3A /* : */ && ch <= 0x3E /* > */ || + ch === 0x40 /* @ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter + pp$1.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits + pp$1.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start + }; + function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits + pp$1.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start + }; + function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) + } + function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence + // Allows only 0-377(octal) i.e. 0-255(decimal). + pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit + pp$1.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false + }; + function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit + // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true + }; + + // Object type used to represent tokens. Note that normally, tokens + // simply exist as properties on the parser object. This is only + // used for the onToken callback and the external tokenizer. + + var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } + }; + + // ## Tokenizer + + var pp = Parser.prototype; + + // Move to the next token + + pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); + }; + + pp.getToken = function() { + this.next(); + return new Token(this) + }; + + // If we're in an ES6 environment, make parsers iterable + if (typeof Symbol !== "undefined") + { pp[Symbol.iterator] = function() { + var this$1$1 = this; + + return { + next: function () { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + } + } + } + }; } + + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). + + // Read a single token, updating the parser object's token-related + // properties. + + pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } + }; + + pp.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) + }; + + pp.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 + }; + + pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } + }; + + pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } + }; + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. + + pp.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } + } + }; + + // Called at the end of every token. Sets `end`, `val`, and + // maintains `context` and `exprAllowed`, and skips the space after + // the token, so that the next one's `start` will point at the + // right position. + + pp.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); + }; + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + pp.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types$1.ellipsis) + } else { + ++this.pos; + return this.finishToken(types$1.dot) + } + }; + + pp.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.slash, 1) + }; + + pp.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types$1.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(tokentype, size) + }; + + pp.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types$1.assign, 3) } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) + }; + + pp.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.bitwiseXOR, 1) + }; + + pp.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) + }; + + pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) +}; + +pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `' 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 && !this.isModule) { + if (this.source.slice(this.index + 1, this.index + 4) === '!--') { + this.index += 4; // ` + + + +Implementation of function.prototype.bind + +## Example + +I mainly do this for unit tests I run on phantomjs. +PhantomJS does not have Function.prototype.bind :( + +```js +Function.prototype.bind = require("function-bind") +``` + +## Installation + +`npm install function-bind` + +## Contributors + + - Raynos + +## MIT Licenced + + [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg + [travis-url]: https://travis-ci.org/Raynos/function-bind + [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg + [npm-url]: https://npmjs.org/package/function-bind + [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png + [6]: https://coveralls.io/r/Raynos/function-bind + [7]: https://gemnasium.com/Raynos/function-bind.png + [8]: https://gemnasium.com/Raynos/function-bind + [deps-svg]: https://david-dm.org/Raynos/function-bind.svg + [deps-url]: https://david-dm.org/Raynos/function-bind + [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg + [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies + [11]: https://ci.testling.com/Raynos/function-bind.png + [12]: https://ci.testling.com/Raynos/function-bind diff --git a/node_modules/function-bind/implementation.js b/node_modules/function-bind/implementation.js new file mode 100644 index 0000000..cc4daec --- /dev/null +++ b/node_modules/function-bind/implementation.js @@ -0,0 +1,52 @@ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; diff --git a/node_modules/function-bind/index.js b/node_modules/function-bind/index.js new file mode 100644 index 0000000..3bb6b96 --- /dev/null +++ b/node_modules/function-bind/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; diff --git a/node_modules/function-bind/package.json b/node_modules/function-bind/package.json new file mode 100644 index 0000000..20a1727 --- /dev/null +++ b/node_modules/function-bind/package.json @@ -0,0 +1,63 @@ +{ + "name": "function-bind", + "version": "1.1.1", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" + ], + "author": "Raynos ", + "repository": "git://github.com/Raynos/function-bind.git", + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", + "contributors": [ + { + "name": "Raynos" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, + "dependencies": {}, + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "covert": "^1.1.0", + "eslint": "^4.5.0", + "jscs": "^3.0.7", + "tape": "^4.8.0" + }, + "license": "MIT", + "scripts": { + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npm run coverage -- --quiet", + "tests-only": "node test", + "coverage": "covert test/*.js", + "lint": "npm run jscs && npm run eslint", + "jscs": "jscs *.js */*.js", + "eslint": "eslint *.js */*.js" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/function-bind/test/.eslintrc b/node_modules/function-bind/test/.eslintrc new file mode 100644 index 0000000..8a56d5b --- /dev/null +++ b/node_modules/function-bind/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-invalid-this": 0, + "no-magic-numbers": 0, + } +} diff --git a/node_modules/function-bind/test/index.js b/node_modules/function-bind/test/index.js new file mode 100644 index 0000000..2edecce --- /dev/null +++ b/node_modules/function-bind/test/index.js @@ -0,0 +1,252 @@ +// jscs:disable requireUseStrict + +var test = require('tape'); + +var functionBind = require('../implementation'); +var getCurrentContext = function () { return this; }; + +test('functionBind is a function', function (t) { + t.equal(typeof functionBind, 'function'); + t.end(); +}); + +test('non-functions', function (t) { + var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; + t.plan(nonFunctions.length); + for (var i = 0; i < nonFunctions.length; ++i) { + try { functionBind.call(nonFunctions[i]); } catch (ex) { + t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); + } + } + t.end(); +}); + +test('without a context', function (t) { + t.test('binds properly', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }) + }; + namespace.func(1, 2, 3); + st.deepEqual(args, [1, 2, 3]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('binds properly, and still supplies bound arguments', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, undefined, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.deepEqual(args, [1, 2, 3, 4, 5, 6]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('returns properly', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('called as a constructor', function (st) { + var thunkify = function (value) { + return function () { return value; }; + }; + st.test('returns object value', function (sst) { + var expectedReturnValue = [1, 2, 3]; + var Constructor = functionBind.call(thunkify(expectedReturnValue), null); + var result = new Constructor(); + sst.equal(result, expectedReturnValue); + sst.end(); + }); + + st.test('does not return primitive value', function (sst) { + var Constructor = functionBind.call(thunkify(42), null); + var result = new Constructor(); + sst.notEqual(result, 42); + sst.end(); + }); + + st.test('object from bound constructor is instance of original and bound constructor', function (sst) { + var A = function (x) { + this.name = x || 'A'; + }; + var B = functionBind.call(A, null, 'B'); + + var result = new B(); + sst.ok(result instanceof B, 'result is instance of bound constructor'); + sst.ok(result instanceof A, 'result is instance of original constructor'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('with a context', function (t) { + t.test('with no bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext) + }; + namespace.func(1, 2, 3); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); + st.end(); + }); + + t.test('with bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); + st.end(); + }); + + t.test('returns properly', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('passes the correct arguments when called as a constructor', function (st) { + var expected = { name: 'Correct' }; + var namespace = { + Func: functionBind.call(function (arg) { + return arg; + }, { name: 'Incorrect' }) + }; + var returned = new namespace.Func(expected); + st.equal(returned, expected, 'returns the right arg when called as a constructor'); + st.end(); + }); + + t.test('has the new instance\'s context when called as a constructor', function (st) { + var actualContext; + var expectedContext = { foo: 'bar' }; + var namespace = { + Func: functionBind.call(function () { + actualContext = this; + }, expectedContext) + }; + var result = new namespace.Func(); + st.equal(result instanceof namespace.Func, true); + st.notEqual(actualContext, expectedContext); + st.end(); + }); + + t.end(); +}); + +test('bound function length', function (t) { + t.test('sets a correct length without thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); +}); diff --git a/node_modules/function.prototype.name/.editorconfig b/node_modules/function.prototype.name/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/function.prototype.name/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/function.prototype.name/.eslintignore b/node_modules/function.prototype.name/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/function.prototype.name/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/function.prototype.name/.eslintrc b/node_modules/function.prototype.name/.eslintrc new file mode 100644 index 0000000..0b7dbb9 --- /dev/null +++ b/node_modules/function.prototype.name/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["IsCallable"] }], + }, +} diff --git a/node_modules/function.prototype.name/.github/FUNDING.yml b/node_modules/function.prototype.name/.github/FUNDING.yml new file mode 100644 index 0000000..6a3b00c --- /dev/null +++ b/node_modules/function.prototype.name/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/function.prototype.name +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/function.prototype.name/.nycrc b/node_modules/function.prototype.name/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/function.prototype.name/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/function.prototype.name/CHANGELOG.md b/node_modules/function.prototype.name/CHANGELOG.md new file mode 100644 index 0000000..38b3ef1 --- /dev/null +++ b/node_modules/function.prototype.name/CHANGELOG.md @@ -0,0 +1,82 @@ +1.1.5 / 2021-10-01 +================= + * [Deps] update `es-abstract` + * [meta] use `prepublishOnly` script for npm 7+ + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `tape` + * [actions] update workflows + * [actions] use `node/install` instead of `node/run`; use `codecov` action + +1.1.4 / 2021-02-22 +================= + * [readme] remove travis badge + * [meta] remove audit-level + * [meta] gitignore coverage output + * [meta] do not publish github action workflow files + * [Deps] update `call-bind`, `es-abstract`, `functions-have-names` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-strict-mode`, `tape` + * [Tests] increase coverage + * [actions] update workflows + +1.1.3 / 2020-11-27 +================= + * [Deps] update `es-abstract`, `functions-have-names`; use `call-bind` where applicable + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `make-arrow-function`, `make-generator-function`; add `aud`, `make-async-function` + * [actions] add "Allow Edits" workflow + * [actions] switch Automatic Rebase workflow to `pull_request_target` event + * [Tests] migrate tests to Github Actions + * [Tests] run `nyc` on all tests + * [Tests] add `implementation` test; run `es-shim-api` in postlint; use `tape` runner + * [Tests] only audit prod deps + +1.1.2 / 2019-12-14 +================= + * [Refactor] use `es-abstract` + * [Deps] update `functions-have-names` + * [meta] add `funding` field + * [meta] fix repo capitalization + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` + * [Tests] use shared travis-ci configs + * [actions] add automatic rebasing / merge commit blocking + +1.1.1 / 2019-07-24 +================= + * [Refactor] use `functions-have-names` + * [meta] clean up package.json scripts + * [meta] update links + * [meta] create FUNDING.yml + * [Deps] update `is-callable`, `define-properties` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `covert` + * [Tests] use `eccheck` over `editorconfig-tools` + * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops + * [Tests] up to `node` `v11.7`, `v10.15`, `v9.11`, `v8.15`, `v6.16`, `v4.9` + * [Test] remove `jscs` + +1.1.0 / 2017-12-31 +================= + * [New] add `auto` entry point + * [Deps] update `function-bind` + * [Dev Deps] update `uglify-register`, `tape`, `nsp`, `eslint`, `@ljharb/eslint-config`, `@es-shims/api` + * [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS + +1.0.3 / 2017-07-21 +================= + * [Fix] be robust against function name mangling + * [Refactor] move function name detection to separate file + +1.0.2 / 2017-07-14 +================= + * [Refactor] shim: Remove unnecessary `!functionsHaveNames` check + +1.0.1 / 2017-07-11 +================= + * [Fix] in IE 9-11, we must rely on `.call` being available (#13) + * [Fix] ensure that `Function.prototype.name` does not erase the getter + * [Deps] update `is-callable` + * [Dev Deps] add `safe-publish-latest` + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `@es-shims/api` + * [Tests] up to `node` `v8.1`; `v7.10`, `v6.11`, `v4.8`; improve matrix; newer npm fails on older nodes + * [Tests] use `Object` to avoid function name inference in node 7 + +1.0.0 / 2016-02-27 +================= + * Initial release. diff --git a/node_modules/function.prototype.name/LICENSE b/node_modules/function.prototype.name/LICENSE new file mode 100644 index 0000000..44f679a --- /dev/null +++ b/node_modules/function.prototype.name/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/function.prototype.name/README.md b/node_modules/function.prototype.name/README.md new file mode 100644 index 0000000..64aec9a --- /dev/null +++ b/node_modules/function.prototype.name/README.md @@ -0,0 +1,42 @@ +# function.prototype.name [![Version Badge][2]][1] + +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +An ES2015 spec-compliant `Function.prototype.name` shim. Invoke its "shim" method to shim Function.prototype.name if it is unavailable. +*Note*: `Function#name` requires a true ES5 environment - specifically, one with ES5 getters. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES5-supported environment and complies with the [spec](https://www.ecma-international.org/ecma-262/6.0/#sec-get-regexp.prototype.flags). + +Most common usage: + +## Example + +```js +var functionName = require('function.prototype.name'); +var assert = require('assert'); + +assert.equal(functionName(function foo() {}), 'foo'); + +functionName.shim(); +assert.equal(function foo() {}.name, 'foo'); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/function.prototype.name +[2]: https://versionbadg.es/es-shims/Function.prototype.name.svg +[5]: https://david-dm.org/es-shims/Function.prototype.name.svg +[6]: https://david-dm.org/es-shims/Function.prototype.name +[7]: https://david-dm.org/es-shims/Function.prototype.name/dev-status.svg +[8]: https://david-dm.org/es-shims/Function.prototype.name#info=devDependencies +[11]: https://nodei.co/npm/function.prototype.name.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/function.prototype.name.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/function.prototype.name.svg +[downloads-url]: https://npm-stat.com/charts.html?package=function.prototype.name diff --git a/node_modules/function.prototype.name/auto.js b/node_modules/function.prototype.name/auto.js new file mode 100644 index 0000000..8ebf606 --- /dev/null +++ b/node_modules/function.prototype.name/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/function.prototype.name/helpers/functionsHaveNames.js b/node_modules/function.prototype.name/helpers/functionsHaveNames.js new file mode 100644 index 0000000..0aa8532 --- /dev/null +++ b/node_modules/function.prototype.name/helpers/functionsHaveNames.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('functions-have-names')(); + +// TODO: semver-major, remove diff --git a/node_modules/function.prototype.name/implementation.js b/node_modules/function.prototype.name/implementation.js new file mode 100644 index 0000000..03b4989 --- /dev/null +++ b/node_modules/function.prototype.name/implementation.js @@ -0,0 +1,43 @@ +'use strict'; + +var IsCallable = require('es-abstract/2021/IsCallable'); +var functionsHaveNames = require('functions-have-names')(); +var callBound = require('call-bind/callBound'); +var $functionToString = callBound('Function.prototype.toString'); +var $stringMatch = callBound('String.prototype.match'); + +var classRegex = /^class /; + +var isClass = function isClassConstructor(fn) { + if (IsCallable(fn)) { + return false; + } + if (typeof fn !== 'function') { + return false; + } + try { + var match = $stringMatch($functionToString(fn), classRegex); + return !!match; + } catch (e) {} + return false; +}; + +var regex = /\s*function\s+([^(\s]*)\s*/; + +var functionProto = Function.prototype; + +module.exports = function getName() { + if (!isClass(this) && !IsCallable(this)) { + throw new TypeError('Function.prototype.name sham getter called on non-function'); + } + if (functionsHaveNames) { + return this.name; + } + if (this === functionProto) { + return ''; + } + var str = $functionToString(this); + var match = $stringMatch(str, regex); + var name = match && match[1]; + return name; +}; diff --git a/node_modules/function.prototype.name/index.js b/node_modules/function.prototype.name/index.js new file mode 100644 index 0000000..ee9573a --- /dev/null +++ b/node_modules/function.prototype.name/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var define = require('define-properties'); +var callBind = require('call-bind'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var bound = callBind(implementation); + +define(bound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = bound; diff --git a/node_modules/function.prototype.name/package.json b/node_modules/function.prototype.name/package.json new file mode 100644 index 0000000..300810a --- /dev/null +++ b/node_modules/function.prototype.name/package.json @@ -0,0 +1,80 @@ +{ + "name": "function.prototype.name", + "version": "1.1.5", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "An ES2015 spec-compliant `Function.prototype.name` shim", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run --silent tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "npm run eccheck", + "lint": "eslint .", + "postlint": "es-shim-api --bound", + "eccheck": "eclint check '*.js' '**/*.js'" + }, + "repository": { + "type": "git", + "url": "git://github.com/es-shims/Function.prototype.name.git" + }, + "keywords": [ + "Function.prototype.name", + "function", + "name", + "ES6", + "ES2015", + "shim", + "polyfill", + "es-shim API" + ], + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "es-abstract": "^1.19.0", + "functions-have-names": "^1.2.2" + }, + "devDependencies": { + "@es-shims/api": "^2.2.1", + "@ljharb/eslint-config": "^18.0.0", + "aud": "^1.1.5", + "eclint": "^2.8.1", + "eslint": "^7.32.0", + "for-each": "^0.3.3", + "has-strict-mode": "^1.0.1", + "make-arrow-function": "^1.2.0", + "make-async-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.1", + "uglify-register": "^1.0.1" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/9.0..latest", + "firefox/4.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/11.6..latest", + "opera/next", + "safari/5.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/function.prototype.name/polyfill.js b/node_modules/function.prototype.name/polyfill.js new file mode 100644 index 0000000..382fb9b --- /dev/null +++ b/node_modules/function.prototype.name/polyfill.js @@ -0,0 +1,7 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + return implementation; +}; diff --git a/node_modules/function.prototype.name/shim.js b/node_modules/function.prototype.name/shim.js new file mode 100644 index 0000000..587e3e9 --- /dev/null +++ b/node_modules/function.prototype.name/shim.js @@ -0,0 +1,35 @@ +'use strict'; + +var supportsDescriptors = require('define-properties').supportsDescriptors; +var functionsHaveNames = require('functions-have-names')(); +var getPolyfill = require('./polyfill'); +var defineProperty = Object.defineProperty; +var TypeErr = TypeError; + +module.exports = function shimName() { + var polyfill = getPolyfill(); + if (functionsHaveNames) { + return polyfill; + } + if (!supportsDescriptors) { + throw new TypeErr('Shimming Function.prototype.name support requires ES5 property descriptor support.'); + } + var functionProto = Function.prototype; + defineProperty(functionProto, 'name', { + configurable: true, + enumerable: false, + get: function () { + var name = polyfill.call(this); + if (this !== functionProto) { + defineProperty(this, 'name', { + configurable: true, + enumerable: false, + value: name, + writable: false + }); + } + return name; + } + }); + return polyfill; +}; diff --git a/node_modules/function.prototype.name/test/implementation.js b/node_modules/function.prototype.name/test/implementation.js new file mode 100644 index 0000000..7fdf95b --- /dev/null +++ b/node_modules/function.prototype.name/test/implementation.js @@ -0,0 +1,20 @@ +'use strict'; + +var implementation = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + /* eslint no-useless-call: 0 */ + st['throws'](function () { implementation.call(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { implementation.call(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(implementation), t); + + t.end(); +}); diff --git a/node_modules/function.prototype.name/test/index.js b/node_modules/function.prototype.name/test/index.js new file mode 100644 index 0000000..68e33af --- /dev/null +++ b/node_modules/function.prototype.name/test/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var getName = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('non-functions', function (st) { + st['throws'](function () { getName(); }, TypeError, 'undefined is not a function'); + st['throws'](function () { getName(null); }, TypeError, 'null is not a function'); + st['throws'](function () { getName(true); }, TypeError, 'true is not a function'); + st['throws'](function () { getName(false); }, TypeError, 'false is not a function'); + st['throws'](function () { getName('foo'); }, TypeError, '"foo" is not a function'); + st['throws'](function () { getName([]); }, TypeError, '[] is not a function'); + st['throws'](function () { getName({}); }, TypeError, '{} is not a function'); + st['throws'](function () { getName(/a/g); }, TypeError, '/a/g is not a function'); + st.end(); + }); + + runTests(getName, t); + + t.end(); +}); diff --git a/node_modules/function.prototype.name/test/shimmed.js b/node_modules/function.prototype.name/test/shimmed.js new file mode 100644 index 0000000..c2ed13a --- /dev/null +++ b/node_modules/function.prototype.name/test/shimmed.js @@ -0,0 +1,21 @@ +'use strict'; + +require('../auto'); + +var test = require('tape'); +var supportsDescriptors = require('define-properties').supportsDescriptors; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.test('enumerability', { skip: !supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Function.prototype, 'name'), 'Function#name is not enumerable'); + et.equal(false, isEnumerable.call(function foo() {}, 'name'), 'a function’s name is not enumerable'); + et.end(); + }); + + runTests(function (fn) { return fn.name; }, t); + + t.end(); +}); diff --git a/node_modules/function.prototype.name/test/tests.js b/node_modules/function.prototype.name/test/tests.js new file mode 100644 index 0000000..323cf41 --- /dev/null +++ b/node_modules/function.prototype.name/test/tests.js @@ -0,0 +1,60 @@ +'use strict'; + +var functionsHaveNames = require('functions-have-names')(); +var arrows = require('make-arrow-function').list(); +var generators = require('make-generator-function')(); +var asyncs = require('make-async-function').list(); +var forEach = require('for-each'); + +var foo = Object(function foo() {}); +var anon = Object(function () {}); +var evalled = Object(Function()); // eslint-disable-line no-new-func + +module.exports = function (getName, t) { + t.test('functions', function (st) { + if (functionsHaveNames) { + st.equal(getName(foo), foo.name, 'foo has name "foo"'); + st.equal(getName(anon), anon.name, 'anonymous function has name of empty string'); + st.equal(getName(evalled), evalled.name, 'eval-d function has name "anonymous" (or empty string)'); + } + st.equal(getName(foo), 'foo', 'foo has name "foo"'); + st.equal(getName(anon), '', 'anonymous function has name of empty string'); + var evalledName = getName(evalled); + st.equal(evalledName === 'anonymous' || evalledName === '', true, 'eval-d function has name "anonymous" (or empty string'); + st.end(); + }); + + t.test('arrow functions', { skip: arrows.length === 0 }, function (st) { + st.equal(true, functionsHaveNames, 'functions have names in any env with arrow functions'); + forEach(arrows, function (arrowFn) { + st.equal(getName(arrowFn), arrowFn.name, 'arrow function name matches for ' + arrowFn); + }); + st.end(); + }); + + t.test('generators', { skip: generators.length === 0 }, function (st) { + st.equal(true, functionsHaveNames, 'functions have names in any env with generator functions'); + forEach(generators, function (genFn) { + st.equal(getName(genFn), genFn.name, 'generator function name matches for ' + genFn); + }); + st.end(); + }); + + t.test('asyncs', { skip: asyncs.length === 0 }, function (st) { + st.equal(true, functionsHaveNames, 'functions have names in any env with async functions'); + forEach(asyncs, function (asyncFn) { + st.equal(getName(asyncFn), asyncFn.name, 'async function name matches for ' + asyncFn); + }); + st.end(); + }); + + t.test('Function.prototype.name', function (st) { + st.equal(getName(function before() {}), 'before', 'function prior to accessing Function.prototype has the right name'); + var protoName = getName(Function.prototype); + // on <= node v2.5, this is "Empty" - otherwise, the empty string + st.equal(protoName === '' || protoName === 'Empty', true, 'Function.prototype has the right name'); + st.equal(getName(function after() {}), 'after', 'function after accessing Function.prototype has the right name'); + + st.end(); + }); +}; diff --git a/node_modules/function.prototype.name/test/uglified.js b/node_modules/function.prototype.name/test/uglified.js new file mode 100644 index 0000000..77733ab --- /dev/null +++ b/node_modules/function.prototype.name/test/uglified.js @@ -0,0 +1,17 @@ +'use strict'; + +var test = require('tape'); +var runTests = require('./tests'); + +test('with uglify', function (t) { + /* eslint global-require: 0 */ + require('uglify-register/api').register({ + exclude: [/\/node_modules\//, /\/test\//], + uglify: { mangle: true } + }); + + var getName = require('../'); + runTests(getName, t); + + t.end(); +}); diff --git a/node_modules/functions-have-names/.editorconfig b/node_modules/functions-have-names/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/functions-have-names/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/functions-have-names/.eslintrc b/node_modules/functions-have-names/.eslintrc new file mode 100644 index 0000000..2807df7 --- /dev/null +++ b/node_modules/functions-have-names/.eslintrc @@ -0,0 +1,19 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": [2, "always"], + "id-length": 1, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "func-name-matching": 0, + }, + }, + ], +} diff --git a/node_modules/functions-have-names/.github/FUNDING.yml b/node_modules/functions-have-names/.github/FUNDING.yml new file mode 100644 index 0000000..1b81d18 --- /dev/null +++ b/node_modules/functions-have-names/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/functions-have-names +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/functions-have-names/.nycrc b/node_modules/functions-have-names/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/functions-have-names/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/functions-have-names/CHANGELOG.md b/node_modules/functions-have-names/CHANGELOG.md new file mode 100644 index 0000000..1026b70 --- /dev/null +++ b/node_modules/functions-have-names/CHANGELOG.md @@ -0,0 +1,89 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.3](https://github.com/inspect-js/functions-have-names/compare/v1.2.2...v1.2.3) - 2022-04-19 + +### Fixed + +- [Fix] in IE 9-11, the descriptor is absent [`#11`](https://github.com/inspect-js/functions-have-names/issues/11) [`#25`](https://github.com/es-shims/RegExp.prototype.flags/issues/25) + +### Commits + +- [actions] reuse common workflows [`4ed274a`](https://github.com/inspect-js/functions-have-names/commit/4ed274a2441c7fd38ff6add741c309e268550d97) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`96dfcaa`](https://github.com/inspect-js/functions-have-names/commit/96dfcaaf1c9c5305f2b66ef69f9cddf1d9d9a578) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`9e674f8`](https://github.com/inspect-js/functions-have-names/commit/9e674f85520a93235e412a3fd7671d2356c6e45b) +- [readme] add github actions/codecov badges; update URLs [`d913f5b`](https://github.com/inspect-js/functions-have-names/commit/d913f5bf38ccab32d5fbea4a044b9cd93a4b9bec) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`f61058f`](https://github.com/inspect-js/functions-have-names/commit/f61058fe1e34f2cfa9235283a4fc6c0c0172c91a) +- [actions] update codecov uploader [`3348839`](https://github.com/inspect-js/functions-have-names/commit/33488394e7cadbf499bee4775c627c1370d033d0) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`ee1a321`](https://github.com/inspect-js/functions-have-names/commit/ee1a3211a40902af59aa629e3ac41ec36360dc1b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`b8dc1a2`](https://github.com/inspect-js/functions-have-names/commit/b8dc1a277b08362bebedfeba2faca8964f68283b) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`0e825c4`](https://github.com/inspect-js/functions-have-names/commit/0e825c4ba8525b02d9acaaf2511371f76c0562ce) +- [meta] use `prepublishOnly` script for npm 7+ [`9489d66`](https://github.com/inspect-js/functions-have-names/commit/9489d666c59702ea6bafd3ff611b3eadfee6570e) + +## [v1.2.2](https://github.com/inspect-js/functions-have-names/compare/v1.2.1...v1.2.2) - 2020-12-14 + +### Commits + +- [Tests] migrate tests to Github Actions [`39bf4fe`](https://github.com/inspect-js/functions-have-names/commit/39bf4fe5ae5b3610a80ba13726f3ee00e3c49e2f) +- [meta] do not publish github action workflow files [`45ab0cb`](https://github.com/inspect-js/functions-have-names/commit/45ab0cbdc0da2efd64f5deb9810be63009bac4a0) +- [readme] add docs, fix URLs [`fad3af6`](https://github.com/inspect-js/functions-have-names/commit/fad3af61e9cbc27f47d2097614f43c62ae1022dd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`82df94a`](https://github.com/inspect-js/functions-have-names/commit/82df94ae06f05a5fa321dda9b7d902ac9fc26424) +- [Tests] run `nyc` on all tests; use `tape` runner [`8038329`](https://github.com/inspect-js/functions-have-names/commit/8038329fec493043639d9d8c779141dcb7d00c2d) +- [actions] add automatic rebasing / merge commit blocking [`49795eb`](https://github.com/inspect-js/functions-have-names/commit/49795ebf38ae3ba724ff7ac5c53598ec66ab814b) +- [actions] add "Allow Edits" workflow [`2096fe6`](https://github.com/inspect-js/functions-have-names/commit/2096fe6d67d435c0e0da25f3cfe9ff02991c41e6) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`ec1c6fe`](https://github.com/inspect-js/functions-have-names/commit/ec1c6fe209419c722d732cd512e4375c48366392) +- [Dev Deps] update `auto-changelog`; add `aud` [`79fdb23`](https://github.com/inspect-js/functions-have-names/commit/79fdb23d1ed2b4125f443be193c37330e634e654) +- [Tests] only audit prod deps [`d9ca245`](https://github.com/inspect-js/functions-have-names/commit/d9ca2455e26a45994024d1027344c268a06818bd) +- [Dev Deps] update `auto-changelog`, `tape` [`ac026d4`](https://github.com/inspect-js/functions-have-names/commit/ac026d4bda77e9820b74456fc752d2069e5b8a7f) +- [Dev Deps] update `tape` [`a8c5ee3`](https://github.com/inspect-js/functions-have-names/commit/a8c5ee3622b487938462f82698dae3ceb32da1a7) +- [Dev Deps] update `@ljharb/eslint-config` [`b25fafd`](https://github.com/inspect-js/functions-have-names/commit/b25fafd0923dcf53c3aeca92268e497ffd96ec34) + +## [v1.2.1](https://github.com/inspect-js/functions-have-names/compare/v1.2.0...v1.2.1) - 2020-01-19 + +### Commits + +- [Tests] use shared travis-ci configs [`612823a`](https://github.com/inspect-js/functions-have-names/commit/612823a064b4be4c61a1e52d1009abed4a4fc4fb) +- [Fix] IE 8 has a broken `Object.getOwnPropertyDescriptor` [`ba01c22`](https://github.com/inspect-js/functions-have-names/commit/ba01c22795162b787a698950ea34250ce68a7bb1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`; add `safe-publish-latest` [`b28d9d2`](https://github.com/inspect-js/functions-have-names/commit/b28d9d2e8bc0b758671bcaf2f7aa0d4ad4b42046) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`a62fbd6`](https://github.com/inspect-js/functions-have-names/commit/a62fbd69a34a2b1d1860acfa2afc6dcc839bc180) +- [meta] add `funding` field [`8734a94`](https://github.com/inspect-js/functions-have-names/commit/8734a940e39acdf7619eb89e358746bd278b4c90) + +## [v1.2.0](https://github.com/inspect-js/functions-have-names/compare/v1.1.1...v1.2.0) - 2019-10-20 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog` [`7e07444`](https://github.com/inspect-js/functions-have-names/commit/7e0744437789641ea462005d2e350ef476aa7141) +- [New] add `boundFunctionsHaveNames()` [`05661be`](https://github.com/inspect-js/functions-have-names/commit/05661be26c3c260bb3984e433dc9cea3fd82f9ac) + +## [v1.1.1](https://github.com/inspect-js/functions-have-names/compare/v1.1.0...v1.1.1) - 2019-07-24 + +### Commits + +- [Tests] fix linting errors [`0cb8017`](https://github.com/inspect-js/functions-have-names/commit/0cb8017203ae37d1e019bb1c99120f3f56a266a5) +- [Tests] fix tests when name is not configurable [`38a8aee`](https://github.com/inspect-js/functions-have-names/commit/38a8aeee0403bd7aa7f35da76dc433cbcdd3f85a) +- [Fix] ensure function name mangling does not break detection [`f6926ab`](https://github.com/inspect-js/functions-have-names/commit/f6926abaaebc81366f73cf0c3f874ad7e4ba16d2) + +## [v1.1.0](https://github.com/inspect-js/functions-have-names/compare/v1.0.0...v1.1.0) - 2019-07-23 + +### Commits + +- [New] add `functionsHaveConfigurableNames` function on main export [`ce73f75`](https://github.com/inspect-js/functions-have-names/commit/ce73f75891640a462326df7266d90b09519a5fca) + +## v1.0.0 - 2019-07-22 + +### Commits + +- [Tests] add travis.yml [`06ed096`](https://github.com/inspect-js/functions-have-names/commit/06ed09681a3dc067094562e8d21a31400a782add) +- Initial commit [`ced60bd`](https://github.com/inspect-js/functions-have-names/commit/ced60bd089539eb228c68fc2ad7c7bc04b959b02) +- npm init [`79088ab`](https://github.com/inspect-js/functions-have-names/commit/79088ab607e7e91a402e198ab6d1837a317c6fa9) +- add tests [`c9e8e09`](https://github.com/inspect-js/functions-have-names/commit/c9e8e09c5153797c97c324cca4b837540eddeff8) +- [Tests] add `npm run lint` [`988b924`](https://github.com/inspect-js/functions-have-names/commit/988b924a8a49ea5c0f30d5aa2b2ea9add0b39474) +- [meta] create FUNDING.yml [`2e443ef`](https://github.com/inspect-js/functions-have-names/commit/2e443ef67748214d05898b3da76f908a7e2d7488) +- [meta] add version scripts [`52005e3`](https://github.com/inspect-js/functions-have-names/commit/52005e3794fd0799db5963a5359846798cb95c14) +- implementation [`b7b4942`](https://github.com/inspect-js/functions-have-names/commit/b7b49421ef69fb5e042194a650cb4f71bb4996e4) +- Only apps should have lockfiles [`81d2e04`](https://github.com/inspect-js/functions-have-names/commit/81d2e04e7a43cbff2e46e72781bb0693dbb67800) +- [Tests] use `npx aud` [`baa92d8`](https://github.com/inspect-js/functions-have-names/commit/baa92d8aba331fe8821663bc14baf2e11685474a) diff --git a/node_modules/functions-have-names/LICENSE b/node_modules/functions-have-names/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/node_modules/functions-have-names/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/functions-have-names/README.md b/node_modules/functions-have-names/README.md new file mode 100644 index 0000000..7096260 --- /dev/null +++ b/node_modules/functions-have-names/README.md @@ -0,0 +1,40 @@ +# functions-have-names [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Does this JS environment support the `name` property on functions? + +## Example + +```js +var functionsHaveNames = require('functions-have-names'); +var assert = require('assert'); + +assert.equal(functionsHaveNames(), true); // will be `false` in IE 6-8 +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/functions-have-names +[npm-version-svg]: https://versionbadg.es/inspect-js/functions-have-names.svg +[deps-svg]: https://david-dm.org/inspect-js/functions-have-names.svg +[deps-url]: https://david-dm.org/inspect-js/functions-have-names +[dev-deps-svg]: https://david-dm.org/inspect-js/functions-have-names/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/functions-have-names#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/functions-have-names.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/functions-have-names.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/functions-have-names.svg +[downloads-url]: https://npm-stat.com/charts.html?package=functions-have-names +[codecov-image]: https://codecov.io/gh/inspect-js/functions-have-names/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/functions-have-names/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/functions-have-names +[actions-url]: https://github.com/inspect-js/functions-have-names/actions diff --git a/node_modules/functions-have-names/index.js b/node_modules/functions-have-names/index.js new file mode 100644 index 0000000..9d699dc --- /dev/null +++ b/node_modules/functions-have-names/index.js @@ -0,0 +1,31 @@ +'use strict'; + +var functionsHaveNames = function functionsHaveNames() { + return typeof function f() {}.name === 'string'; +}; + +var gOPD = Object.getOwnPropertyDescriptor; +if (gOPD) { + try { + gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + gOPD = null; + } +} + +functionsHaveNames.functionsHaveConfigurableNames = function functionsHaveConfigurableNames() { + if (!functionsHaveNames() || !gOPD) { + return false; + } + var desc = gOPD(function () {}, 'name'); + return !!desc && !!desc.configurable; +}; + +var $bind = Function.prototype.bind; + +functionsHaveNames.boundFunctionsHaveNames = function boundFunctionsHaveNames() { + return functionsHaveNames() && typeof $bind === 'function' && function f() {}.bind().name !== ''; +}; + +module.exports = functionsHaveNames; diff --git a/node_modules/functions-have-names/package.json b/node_modules/functions-have-names/package.json new file mode 100644 index 0000000..3a513cb --- /dev/null +++ b/node_modules/functions-have-names/package.json @@ -0,0 +1,55 @@ +{ + "name": "functions-have-names", + "version": "1.2.3", + "description": "Does this JS environment support the `name` property on functions?", + "main": "index.js", + "scripts": { + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/functions-have-names.git" + }, + "keywords": [ + "function", + "name", + "es5", + "names", + "functions", + "ie" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/functions-have-names/issues" + }, + "homepage": "https://github.com/inspect-js/functions-have-names#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.3" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/functions-have-names/test/index.js b/node_modules/functions-have-names/test/index.js new file mode 100644 index 0000000..0d451ce --- /dev/null +++ b/node_modules/functions-have-names/test/index.js @@ -0,0 +1,65 @@ +'use strict'; + +var test = require('tape'); + +var hasNames = require('../'); + +test('named functions', function (t) { + function f() {} // eslint-disable-line func-style + var g = function h() {}; + + t.equal(typeof hasNames, 'function', 'is a function'); + t.equal(hasNames(), f.name === 'f' && g.name === 'h', 'functions have names or not as expected'); + + t.end(); +}); + +var oDP = Object.defineProperty; +if (oDP) { + try { + oDP({}, 'a', { value: 1 }); + } catch (e) { + oDP = null; + } +} + +test('functionsHaveConfigurableNames', function (t) { + t.equal(typeof hasNames.functionsHaveConfigurableNames, 'function', 'is a function'); + + if (hasNames()) { + var fn = function f() {}; + if (oDP) { + try { + oDP(fn, 'name', { configurable: true, value: 'foo' }); + } catch (e) {} + if (fn.name === 'f') { + t.equal(hasNames.functionsHaveConfigurableNames(), false, 'function names are not configurable'); + } else if (fn.name === 'foo') { + t.equal(hasNames.functionsHaveConfigurableNames(), true, 'function names are not configurable'); + } else { + t.fail('functions have names, but something surprising has happened. Please report this!'); + } + } else { + t.equal(hasNames.functionsHaveConfigurableNames(), false, 'function names are not configurable'); + } + } else { + t.equal(hasNames.functionsHaveConfigurableNames(), false, 'functions do not have names'); + } + + t.end(); +}); + +test('boundFunctionsHaveNames', function (t) { + t.equal(typeof hasNames.boundFunctionsHaveNames, 'function', 'is a function'); + + var fn = function f() {}; + if (typeof fn.bind !== 'function') { + t.equal(hasNames.boundFunctionsHaveNames(), false, 'bound functions do not have names, because .bind does not exist'); + } else if (hasNames()) { + t.equal(hasNames.boundFunctionsHaveNames(), fn.bind().name !== '', 'bound functions have names'); + } else { + t.equal(hasNames.boundFunctionsHaveNames(), false, 'bound functions do not have names, because none do'); + } + + t.end(); +}); diff --git a/node_modules/gensync/LICENSE b/node_modules/gensync/LICENSE new file mode 100644 index 0000000..af7f781 --- /dev/null +++ b/node_modules/gensync/LICENSE @@ -0,0 +1,7 @@ +Copyright 2018 Logan Smyth + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/gensync/README.md b/node_modules/gensync/README.md new file mode 100644 index 0000000..f68ce1a --- /dev/null +++ b/node_modules/gensync/README.md @@ -0,0 +1,196 @@ +# gensync + +This module allows for developers to write common code that can share +implementation details, hiding whether an underlying request happens +synchronously or asynchronously. This is in contrast with many current Node +APIs which explicitly implement the same API twice, once with calls to +synchronous functions, and once with asynchronous functions. + +Take for example `fs.readFile` and `fs.readFileSync`, if you're writing an API +that loads a file and then performs a synchronous operation on the data, it +can be frustrating to maintain two parallel functions. + + +## Example + +```js +const fs = require("fs"); +const gensync = require("gensync"); + +const readFile = gensync({ + sync: fs.readFileSync, + errback: fs.readFile, +}); + +const myOperation = gensync(function* (filename) { + const code = yield* readFile(filename, "utf8"); + + return "// some custom prefix\n" + code; +}); + +// Load and add the prefix synchronously: +const result = myOperation.sync("./some-file.js"); + +// Load and add the prefix asynchronously with promises: +myOperation.async("./some-file.js").then(result => { + +}); + +// Load and add the prefix asynchronously with promises: +myOperation.errback("./some-file.js", (err, result) => { + +}); +``` + +This could even be exposed as your official API by doing +```js +// Using the common 'Sync' suffix for sync functions, and 'Async' suffix for +// promise-returning versions. +exports.myOperationSync = myOperation.sync; +exports.myOperationAsync = myOperation.async; +exports.myOperation = myOperation.errback; +``` +or potentially expose one of the async versions as the default, with a +`.sync` property on the function to expose the synchronous version. +```js +module.exports = myOperation.errback; +module.exports.sync = myOperation.sync; +```` + + +## API + +### gensync(generatorFnOrOptions) + +Returns a function that can be "await"-ed in another `gensync` generator +function, or executed via + +* `.sync(...args)` - Returns the computed value, or throws. +* `.async(...args)` - Returns a promise for the computed value. +* `.errback(...args, (err, result) => {})` - Calls the callback with the computed value, or error. + + +#### Passed a generator + +Wraps the generator to populate the `.sync`/`.async`/`.errback` helpers above to +allow for evaluation of the generator for the final value. + +##### Example + +```js +const readFile = function* () { + return 42; +}; + +const readFileAndMore = gensync(function* (){ + const val = yield* readFile(); + return 42 + val; +}); + +// In general cases +const code = readFileAndMore.sync("./file.js", "utf8"); +readFileAndMore.async("./file.js", "utf8").then(code => {}) +readFileAndMore.errback("./file.js", "utf8", (err, code) => {}); + +// In a generator being called indirectly with .sync/.async/.errback +const code = yield* readFileAndMore("./file.js", "utf8"); +``` + + +#### Passed an options object + +* `opts.sync` + + Example: `(...args) => 4` + + A function that will be called when `.sync()` is called on the `gensync()` + result, or when the result is passed to `yield*` in another generator that + is being run synchronously. + + Also called for `.async()` calls if no async handlers are provided. + +* `opts.async` + + Example: `async (...args) => 4` + + A function that will be called when `.async()` or `.errback()` is called on + the `gensync()` result, or when the result is passed to `yield*` in another + generator that is being run asynchronously. + +* `opts.errback` + + Example: `(...args, cb) => cb(null, 4)` + + A function that will be called when `.async()` or `.errback()` is called on + the `gensync()` result, or when the result is passed to `yield*` in another + generator that is being run asynchronously. + + This option allows for simpler compatibility with many existing Node APIs, + and also avoids introducing the extra even loop turns that promises introduce + to access the result value. + +* `opts.name` + + Example: `"readFile"` + + A string name to apply to the returned function. If no value is provided, + the name of `errback`/`async`/`sync` functions will be used, with any + `Sync` or `Async` suffix stripped off. If the callback is simply named + with ES6 inference (same name as the options property), the name is ignored. + +* `opts.arity` + + Example: `4` + + A number for the length to set on the returned function. If no value + is provided, the length will be carried over from the `sync` function's + `length` value. + +##### Example + +```js +const readFile = gensync({ + sync: fs.readFileSync, + errback: fs.readFile, +}); + +const code = readFile.sync("./file.js", "utf8"); +readFile.async("./file.js", "utf8").then(code => {}) +readFile.errback("./file.js", "utf8", (err, code) => {}); +``` + + +### gensync.all(iterable) + +`Promise.all`-like combinator that works with an iterable of generator objects +that could be passed to `yield*` within a gensync generator. + +#### Example + +```js +const loadFiles = gensync(function* () { + return yield* gensync.all([ + readFile("./one.js"), + readFile("./two.js"), + readFile("./three.js"), + ]); +}); +``` + + +### gensync.race(iterable) + +`Promise.race`-like combinator that works with an iterable of generator objects +that could be passed to `yield*` within a gensync generator. + +#### Example + +```js +const loadFiles = gensync(function* () { + return yield* gensync.race([ + readFile("./one.js"), + readFile("./two.js"), + readFile("./three.js"), + ]); +}); +``` diff --git a/node_modules/gensync/index.js b/node_modules/gensync/index.js new file mode 100644 index 0000000..ee0ea61 --- /dev/null +++ b/node_modules/gensync/index.js @@ -0,0 +1,373 @@ +"use strict"; + +// These use the global symbol registry so that multiple copies of this +// library can work together in case they are not deduped. +const GENSYNC_START = Symbol.for("gensync:v1:start"); +const GENSYNC_SUSPEND = Symbol.for("gensync:v1:suspend"); + +const GENSYNC_EXPECTED_START = "GENSYNC_EXPECTED_START"; +const GENSYNC_EXPECTED_SUSPEND = "GENSYNC_EXPECTED_SUSPEND"; +const GENSYNC_OPTIONS_ERROR = "GENSYNC_OPTIONS_ERROR"; +const GENSYNC_RACE_NONEMPTY = "GENSYNC_RACE_NONEMPTY"; +const GENSYNC_ERRBACK_NO_CALLBACK = "GENSYNC_ERRBACK_NO_CALLBACK"; + +module.exports = Object.assign( + function gensync(optsOrFn) { + let genFn = optsOrFn; + if (typeof optsOrFn !== "function") { + genFn = newGenerator(optsOrFn); + } else { + genFn = wrapGenerator(optsOrFn); + } + + return Object.assign(genFn, makeFunctionAPI(genFn)); + }, + { + all: buildOperation({ + name: "all", + arity: 1, + sync: function(args) { + const items = Array.from(args[0]); + return items.map(item => evaluateSync(item)); + }, + async: function(args, resolve, reject) { + const items = Array.from(args[0]); + + if (items.length === 0) { + Promise.resolve().then(() => resolve([])); + return; + } + + let count = 0; + const results = items.map(() => undefined); + items.forEach((item, i) => { + evaluateAsync( + item, + val => { + results[i] = val; + count += 1; + + if (count === results.length) resolve(results); + }, + reject + ); + }); + }, + }), + race: buildOperation({ + name: "race", + arity: 1, + sync: function(args) { + const items = Array.from(args[0]); + if (items.length === 0) { + throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY); + } + + return evaluateSync(items[0]); + }, + async: function(args, resolve, reject) { + const items = Array.from(args[0]); + if (items.length === 0) { + throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY); + } + + for (const item of items) { + evaluateAsync(item, resolve, reject); + } + }, + }), + } +); + +/** + * Given a generator function, return the standard API object that executes + * the generator and calls the callbacks. + */ +function makeFunctionAPI(genFn) { + const fns = { + sync: function(...args) { + return evaluateSync(genFn.apply(this, args)); + }, + async: function(...args) { + return new Promise((resolve, reject) => { + evaluateAsync(genFn.apply(this, args), resolve, reject); + }); + }, + errback: function(...args) { + const cb = args.pop(); + if (typeof cb !== "function") { + throw makeError( + "Asynchronous function called without callback", + GENSYNC_ERRBACK_NO_CALLBACK + ); + } + + let gen; + try { + gen = genFn.apply(this, args); + } catch (err) { + cb(err); + return; + } + + evaluateAsync(gen, val => cb(undefined, val), err => cb(err)); + }, + }; + return fns; +} + +function assertTypeof(type, name, value, allowUndefined) { + if ( + typeof value === type || + (allowUndefined && typeof value === "undefined") + ) { + return; + } + + let msg; + if (allowUndefined) { + msg = `Expected opts.${name} to be either a ${type}, or undefined.`; + } else { + msg = `Expected opts.${name} to be a ${type}.`; + } + + throw makeError(msg, GENSYNC_OPTIONS_ERROR); +} +function makeError(msg, code) { + return Object.assign(new Error(msg), { code }); +} + +/** + * Given an options object, return a new generator that dispatches the + * correct handler based on sync or async execution. + */ +function newGenerator({ name, arity, sync, async, errback }) { + assertTypeof("string", "name", name, true /* allowUndefined */); + assertTypeof("number", "arity", arity, true /* allowUndefined */); + assertTypeof("function", "sync", sync); + assertTypeof("function", "async", async, true /* allowUndefined */); + assertTypeof("function", "errback", errback, true /* allowUndefined */); + if (async && errback) { + throw makeError( + "Expected one of either opts.async or opts.errback, but got _both_.", + GENSYNC_OPTIONS_ERROR + ); + } + + if (typeof name !== "string") { + let fnName; + if (errback && errback.name && errback.name !== "errback") { + fnName = errback.name; + } + if (async && async.name && async.name !== "async") { + fnName = async.name.replace(/Async$/, ""); + } + if (sync && sync.name && sync.name !== "sync") { + fnName = sync.name.replace(/Sync$/, ""); + } + + if (typeof fnName === "string") { + name = fnName; + } + } + + if (typeof arity !== "number") { + arity = sync.length; + } + + return buildOperation({ + name, + arity, + sync: function(args) { + return sync.apply(this, args); + }, + async: function(args, resolve, reject) { + if (async) { + async.apply(this, args).then(resolve, reject); + } else if (errback) { + errback.call(this, ...args, (err, value) => { + if (err == null) resolve(value); + else reject(err); + }); + } else { + resolve(sync.apply(this, args)); + } + }, + }); +} + +function wrapGenerator(genFn) { + return setFunctionMetadata(genFn.name, genFn.length, function(...args) { + return genFn.apply(this, args); + }); +} + +function buildOperation({ name, arity, sync, async }) { + return setFunctionMetadata(name, arity, function*(...args) { + const resume = yield GENSYNC_START; + if (!resume) { + // Break the tail call to avoid a bug in V8 v6.X with --harmony enabled. + const res = sync.call(this, args); + return res; + } + + let result; + try { + async.call( + this, + args, + value => { + if (result) return; + + result = { value }; + resume(); + }, + err => { + if (result) return; + + result = { err }; + resume(); + } + ); + } catch (err) { + result = { err }; + resume(); + } + + // Suspend until the callbacks run. Will resume synchronously if the + // callback was already called. + yield GENSYNC_SUSPEND; + + if (result.hasOwnProperty("err")) { + throw result.err; + } + + return result.value; + }); +} + +function evaluateSync(gen) { + let value; + while (!({ value } = gen.next()).done) { + assertStart(value, gen); + } + return value; +} + +function evaluateAsync(gen, resolve, reject) { + (function step() { + try { + let value; + while (!({ value } = gen.next()).done) { + assertStart(value, gen); + + // If this throws, it is considered to have broken the contract + // established for async handlers. If these handlers are called + // synchronously, it is also considered bad behavior. + let sync = true; + let didSyncResume = false; + const out = gen.next(() => { + if (sync) { + didSyncResume = true; + } else { + step(); + } + }); + sync = false; + + assertSuspend(out, gen); + + if (!didSyncResume) { + // Callback wasn't called synchronously, so break out of the loop + // and let it call 'step' later. + return; + } + } + + return resolve(value); + } catch (err) { + return reject(err); + } + })(); +} + +function assertStart(value, gen) { + if (value === GENSYNC_START) return; + + throwError( + gen, + makeError( + `Got unexpected yielded value in gensync generator: ${JSON.stringify( + value + )}. Did you perhaps mean to use 'yield*' instead of 'yield'?`, + GENSYNC_EXPECTED_START + ) + ); +} +function assertSuspend({ value, done }, gen) { + if (!done && value === GENSYNC_SUSPEND) return; + + throwError( + gen, + makeError( + done + ? "Unexpected generator completion. If you get this, it is probably a gensync bug." + : `Expected GENSYNC_SUSPEND, got ${JSON.stringify( + value + )}. If you get this, it is probably a gensync bug.`, + GENSYNC_EXPECTED_SUSPEND + ) + ); +} + +function throwError(gen, err) { + // Call `.throw` so that users can step in a debugger to easily see which + // 'yield' passed an unexpected value. If the `.throw` call didn't throw + // back to the generator, we explicitly do it to stop the error + // from being swallowed by user code try/catches. + if (gen.throw) gen.throw(err); + throw err; +} + +function isIterable(value) { + return ( + !!value && + (typeof value === "object" || typeof value === "function") && + !value[Symbol.iterator] + ); +} + +function setFunctionMetadata(name, arity, fn) { + if (typeof name === "string") { + // This should always work on the supported Node versions, but for the + // sake of users that are compiling to older versions, we check for + // configurability so we don't throw. + const nameDesc = Object.getOwnPropertyDescriptor(fn, "name"); + if (!nameDesc || nameDesc.configurable) { + Object.defineProperty( + fn, + "name", + Object.assign(nameDesc || {}, { + configurable: true, + value: name, + }) + ); + } + } + + if (typeof arity === "number") { + const lengthDesc = Object.getOwnPropertyDescriptor(fn, "length"); + if (!lengthDesc || lengthDesc.configurable) { + Object.defineProperty( + fn, + "length", + Object.assign(lengthDesc || {}, { + configurable: true, + value: arity, + }) + ); + } + } + + return fn; +} diff --git a/node_modules/gensync/index.js.flow b/node_modules/gensync/index.js.flow new file mode 100644 index 0000000..fa22e0b --- /dev/null +++ b/node_modules/gensync/index.js.flow @@ -0,0 +1,32 @@ +// @flow + +opaque type Next = Function | void; +opaque type Yield = mixed; + +export type Gensync = { + (...args: Args): Handler, + sync(...args: Args): Return, + async(...args: Args): Promise, + // ...args: [...Args, Callback] + errback(...args: any[]): void, +}; + +export type Handler = Generator; +export type Options = { + sync(...args: Args): Return, + arity?: number, + name?: string, +} & ( + | { async?: (...args: Args) => Promise } + // ...args: [...Args, Callback] + | { errback(...args: any[]): void } +); + +declare module.exports: { + ( + Options | ((...args: Args) => Handler) + ): Gensync, + + all(Array>): Handler, + race(Array>): Handler, +}; diff --git a/node_modules/gensync/package.json b/node_modules/gensync/package.json new file mode 100644 index 0000000..07f8757 --- /dev/null +++ b/node_modules/gensync/package.json @@ -0,0 +1,37 @@ +{ + "name": "gensync", + "version": "1.0.0-beta.2", + "license": "MIT", + "description": "Allows users to use generators in order to write common functions that can be both sync or async.", + "main": "index.js", + "author": "Logan Smyth ", + "homepage": "https://github.com/loganfsmyth/gensync", + "repository": { + "type": "git", + "url": "https://github.com/loganfsmyth/gensync.git" + }, + "scripts": { + "test": "jest" + }, + "engines": { + "node": ">=6.9.0" + }, + "keywords": [ + "async", + "sync", + "generators", + "async-await", + "callbacks" + ], + "devDependencies": { + "babel-core": "^6.26.3", + "babel-preset-env": "^1.6.1", + "eslint": "^4.19.1", + "eslint-config-prettier": "^2.9.0", + "eslint-plugin-node": "^6.0.1", + "eslint-plugin-prettier": "^2.6.0", + "flow-bin": "^0.71.0", + "jest": "^22.4.3", + "prettier": "^1.12.1" + } +} diff --git a/node_modules/gensync/test/.babelrc b/node_modules/gensync/test/.babelrc new file mode 100644 index 0000000..cc7f4e9 --- /dev/null +++ b/node_modules/gensync/test/.babelrc @@ -0,0 +1,5 @@ +{ + presets: [ + ["env", { targets: { node: "current" }}], + ], +} diff --git a/node_modules/gensync/test/index.test.js b/node_modules/gensync/test/index.test.js new file mode 100644 index 0000000..ca1a269 --- /dev/null +++ b/node_modules/gensync/test/index.test.js @@ -0,0 +1,489 @@ +"use strict"; + +const promisify = require("util.promisify"); +const gensync = require("../"); + +const TEST_ERROR = new Error("TEST_ERROR"); + +const DID_ERROR = new Error("DID_ERROR"); + +const doSuccess = gensync({ + sync: () => 42, + async: () => Promise.resolve(42), +}); + +const doError = gensync({ + sync: () => { + throw DID_ERROR; + }, + async: () => Promise.reject(DID_ERROR), +}); + +function throwTestError() { + throw TEST_ERROR; +} + +async function expectResult( + fn, + arg, + { error, value, expectSync = false, syncErrback = expectSync } +) { + if (!expectSync) { + expect(() => fn.sync(arg)).toThrow(TEST_ERROR); + } else if (error) { + expect(() => fn.sync(arg)).toThrow(error); + } else { + expect(fn.sync(arg)).toBe(value); + } + + if (error) { + await expect(fn.async(arg)).rejects.toBe(error); + } else { + await expect(fn.async(arg)).resolves.toBe(value); + } + + await new Promise((resolve, reject) => { + let sync = true; + fn.errback(arg, (err, val) => { + try { + expect(err).toBe(error); + expect(val).toBe(value); + expect(sync).toBe(syncErrback); + + resolve(); + } catch (e) { + reject(e); + } + }); + sync = false; + }); +} + +describe("gensync({})", () => { + describe("option validation", () => { + test("disallow async and errback handler together", () => { + try { + gensync({ + sync: throwTestError, + async: throwTestError, + errback: throwTestError, + }); + + throwTestError(); + } catch (err) { + expect(err.message).toMatch( + /Expected one of either opts.async or opts.errback, but got _both_\./ + ); + expect(err.code).toBe("GENSYNC_OPTIONS_ERROR"); + } + }); + + test("disallow missing sync handler", () => { + try { + gensync({ + async: throwTestError, + }); + + throwTestError(); + } catch (err) { + expect(err.message).toMatch(/Expected opts.sync to be a function./); + expect(err.code).toBe("GENSYNC_OPTIONS_ERROR"); + } + }); + + test("errback callback required", () => { + const fn = gensync({ + sync: throwTestError, + async: throwTestError, + }); + + try { + fn.errback(); + + throwTestError(); + } catch (err) { + expect(err.message).toMatch(/function called without callback/); + expect(err.code).toBe("GENSYNC_ERRBACK_NO_CALLBACK"); + } + }); + }); + + describe("generator function metadata", () => { + test("automatic naming", () => { + expect( + gensync({ + sync: function readFileSync() {}, + async: () => {}, + }).name + ).toBe("readFile"); + expect( + gensync({ + sync: function readFile() {}, + async: () => {}, + }).name + ).toBe("readFile"); + expect( + gensync({ + sync: function readFileAsync() {}, + async: () => {}, + }).name + ).toBe("readFileAsync"); + + expect( + gensync({ + sync: () => {}, + async: function readFileSync() {}, + }).name + ).toBe("readFileSync"); + expect( + gensync({ + sync: () => {}, + async: function readFile() {}, + }).name + ).toBe("readFile"); + expect( + gensync({ + sync: () => {}, + async: function readFileAsync() {}, + }).name + ).toBe("readFile"); + + expect( + gensync({ + sync: () => {}, + errback: function readFileSync() {}, + }).name + ).toBe("readFileSync"); + expect( + gensync({ + sync: () => {}, + errback: function readFile() {}, + }).name + ).toBe("readFile"); + expect( + gensync({ + sync: () => {}, + errback: function readFileAsync() {}, + }).name + ).toBe("readFileAsync"); + }); + + test("explicit naming", () => { + expect( + gensync({ + name: "readFile", + sync: () => {}, + async: () => {}, + }).name + ).toBe("readFile"); + }); + + test("default arity", () => { + expect( + gensync({ + sync: function(a, b, c, d, e, f, g) { + throwTestError(); + }, + async: throwTestError, + }).length + ).toBe(7); + }); + + test("explicit arity", () => { + expect( + gensync({ + arity: 3, + sync: throwTestError, + async: throwTestError, + }).length + ).toBe(3); + }); + }); + + describe("'sync' handler", async () => { + test("success", async () => { + const fn = gensync({ + sync: (...args) => JSON.stringify(args), + }); + + await expectResult(fn, 42, { value: "[42]", expectSync: true }); + }); + + test("failure", async () => { + const fn = gensync({ + sync: (...args) => { + throw JSON.stringify(args); + }, + }); + + await expectResult(fn, 42, { error: "[42]", expectSync: true }); + }); + }); + + describe("'async' handler", async () => { + test("success", async () => { + const fn = gensync({ + sync: throwTestError, + async: (...args) => Promise.resolve(JSON.stringify(args)), + }); + + await expectResult(fn, 42, { value: "[42]" }); + }); + + test("failure", async () => { + const fn = gensync({ + sync: throwTestError, + async: (...args) => Promise.reject(JSON.stringify(args)), + }); + + await expectResult(fn, 42, { error: "[42]" }); + }); + }); + + describe("'errback' sync handler", async () => { + test("success", async () => { + const fn = gensync({ + sync: throwTestError, + errback: (...args) => args.pop()(null, JSON.stringify(args)), + }); + + await expectResult(fn, 42, { value: "[42]", syncErrback: true }); + }); + + test("failure", async () => { + const fn = gensync({ + sync: throwTestError, + errback: (...args) => args.pop()(JSON.stringify(args)), + }); + + await expectResult(fn, 42, { error: "[42]", syncErrback: true }); + }); + }); + + describe("'errback' async handler", async () => { + test("success", async () => { + const fn = gensync({ + sync: throwTestError, + errback: (...args) => + process.nextTick(() => args.pop()(null, JSON.stringify(args))), + }); + + await expectResult(fn, 42, { value: "[42]" }); + }); + + test("failure", async () => { + const fn = gensync({ + sync: throwTestError, + errback: (...args) => + process.nextTick(() => args.pop()(JSON.stringify(args))), + }); + + await expectResult(fn, 42, { error: "[42]" }); + }); + }); +}); + +describe("gensync(function* () {})", () => { + test("sync throw before body", async () => { + const fn = gensync(function*(arg = throwTestError()) {}); + + await expectResult(fn, undefined, { + error: TEST_ERROR, + syncErrback: true, + }); + }); + + test("sync throw inside body", async () => { + const fn = gensync(function*() { + throwTestError(); + }); + + await expectResult(fn, undefined, { + error: TEST_ERROR, + syncErrback: true, + }); + }); + + test("async throw inside body", async () => { + const fn = gensync(function*() { + const val = yield* doSuccess(); + throwTestError(); + }); + + await expectResult(fn, undefined, { + error: TEST_ERROR, + }); + }); + + test("error inside body", async () => { + const fn = gensync(function*() { + yield* doError(); + }); + + await expectResult(fn, undefined, { + error: DID_ERROR, + expectSync: true, + syncErrback: false, + }); + }); + + test("successful return value", async () => { + const fn = gensync(function*() { + const value = yield* doSuccess(); + + expect(value).toBe(42); + + return 84; + }); + + await expectResult(fn, undefined, { + value: 84, + expectSync: true, + syncErrback: false, + }); + }); + + test("successful final value", async () => { + const fn = gensync(function*() { + return 42; + }); + + await expectResult(fn, undefined, { + value: 42, + expectSync: true, + }); + }); + + test("yield unexpected object", async () => { + const fn = gensync(function*() { + yield {}; + }); + + try { + await fn.async(); + + throwTestError(); + } catch (err) { + expect(err.message).toMatch( + /Got unexpected yielded value in gensync generator/ + ); + expect(err.code).toBe("GENSYNC_EXPECTED_START"); + } + }); + + test("yield suspend yield", async () => { + const fn = gensync(function*() { + yield Symbol.for("gensync:v1:start"); + + // Should be "yield*" for no error. + yield {}; + }); + + try { + await fn.async(); + + throwTestError(); + } catch (err) { + expect(err.message).toMatch(/Expected GENSYNC_SUSPEND, got {}/); + expect(err.code).toBe("GENSYNC_EXPECTED_SUSPEND"); + } + }); + + test("yield suspend return", async () => { + const fn = gensync(function*() { + yield Symbol.for("gensync:v1:start"); + + // Should be "yield*" for no error. + return {}; + }); + + try { + await fn.async(); + + throwTestError(); + } catch (err) { + expect(err.message).toMatch(/Unexpected generator completion/); + expect(err.code).toBe("GENSYNC_EXPECTED_SUSPEND"); + } + }); +}); + +describe("gensync.all()", () => { + test("success", async () => { + const fn = gensync(function*() { + const result = yield* gensync.all([doSuccess(), doSuccess()]); + + expect(result).toEqual([42, 42]); + }); + + await expectResult(fn, undefined, { + value: undefined, + expectSync: true, + syncErrback: false, + }); + }); + + test("error first", async () => { + const fn = gensync(function*() { + yield* gensync.all([doError(), doSuccess()]); + }); + + await expectResult(fn, undefined, { + error: DID_ERROR, + expectSync: true, + syncErrback: false, + }); + }); + + test("error last", async () => { + const fn = gensync(function*() { + yield* gensync.all([doSuccess(), doError()]); + }); + + await expectResult(fn, undefined, { + error: DID_ERROR, + expectSync: true, + syncErrback: false, + }); + }); + + test("empty list", async () => { + const fn = gensync(function*() { + yield* gensync.all([]); + }); + + await expectResult(fn, undefined, { + value: undefined, + expectSync: true, + syncErrback: false, + }); + }); +}); + +describe("gensync.race()", () => { + test("success", async () => { + const fn = gensync(function*() { + const result = yield* gensync.race([doSuccess(), doError()]); + + expect(result).toEqual(42); + }); + + await expectResult(fn, undefined, { + value: undefined, + expectSync: true, + syncErrback: false, + }); + }); + + test("error", async () => { + const fn = gensync(function*() { + yield* gensync.race([doError(), doSuccess()]); + }); + + await expectResult(fn, undefined, { + error: DID_ERROR, + expectSync: true, + syncErrback: false, + }); + }); +}); diff --git a/node_modules/get-caller-file/LICENSE.md b/node_modules/get-caller-file/LICENSE.md new file mode 100644 index 0000000..bf3e1c0 --- /dev/null +++ b/node_modules/get-caller-file/LICENSE.md @@ -0,0 +1,6 @@ +ISC License (ISC) +Copyright 2018 Stefan Penner + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/get-caller-file/README.md b/node_modules/get-caller-file/README.md new file mode 100644 index 0000000..a7d8c07 --- /dev/null +++ b/node_modules/get-caller-file/README.md @@ -0,0 +1,41 @@ +# get-caller-file + +[![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) +[![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) + +This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. + +Inspired by http://stackoverflow.com/questions/13227489 + +*note: this relies on Node/V8 specific APIs, as such other runtimes may not work* + +## Installation + +```bash +yarn add get-caller-file +``` + +## Usage + +Given: + +```js +// ./foo.js +const getCallerFile = require('get-caller-file'); + +module.exports = function() { + return getCallerFile(); // figures out who called it +}; +``` + +```js +// index.js +const foo = require('./foo'); + +foo() // => /full/path/to/this/file/index.js +``` + + +## Options: + +* `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. diff --git a/node_modules/get-caller-file/index.d.ts b/node_modules/get-caller-file/index.d.ts new file mode 100644 index 0000000..babed69 --- /dev/null +++ b/node_modules/get-caller-file/index.d.ts @@ -0,0 +1,2 @@ +declare const _default: (position?: number) => any; +export = _default; diff --git a/node_modules/get-caller-file/index.js b/node_modules/get-caller-file/index.js new file mode 100644 index 0000000..57304f8 --- /dev/null +++ b/node_modules/get-caller-file/index.js @@ -0,0 +1,22 @@ +"use strict"; +// Call this function in a another function to find out the file from +// which that function was called from. (Inspects the v8 stack trace) +// +// Inspired by http://stackoverflow.com/questions/13227489 +module.exports = function getCallerFile(position) { + if (position === void 0) { position = 2; } + if (position >= Error.stackTraceLimit) { + throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); + } + var oldPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = new Error().stack; + Error.prepareStackTrace = oldPrepareStackTrace; + if (stack !== null && typeof stack === 'object') { + // stack[0] holds this file + // stack[1] holds where this function was called + // stack[2] holds the file we're interested in + return stack[position] ? stack[position].getFileName() : undefined; + } +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/get-caller-file/index.js.map b/node_modules/get-caller-file/index.js.map new file mode 100644 index 0000000..89c655c --- /dev/null +++ b/node_modules/get-caller-file/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA,qEAAqE;AACrE,qEAAqE;AACrE,EAAE;AACF,0DAA0D;AAE1D,iBAAS,SAAS,aAAa,CAAC,QAAY;IAAZ,yBAAA,EAAA,YAAY;IAC1C,IAAI,QAAQ,IAAI,KAAK,CAAC,eAAe,EAAE;QACrC,MAAM,IAAI,SAAS,CAAC,kGAAkG,GAAG,QAAQ,GAAG,oCAAoC,GAAG,KAAK,CAAC,eAAe,GAAG,GAAG,CAAC,CAAC;KACzM;IAED,IAAM,oBAAoB,GAAG,KAAK,CAAC,iBAAiB,CAAC;IACrD,KAAK,CAAC,iBAAiB,GAAG,UAAC,CAAC,EAAE,KAAK,IAAM,OAAA,KAAK,EAAL,CAAK,CAAC;IAC/C,IAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,KAAK,CAAC;IAChC,KAAK,CAAC,iBAAiB,GAAG,oBAAoB,CAAC;IAG/C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC/C,2BAA2B;QAC3B,gDAAgD;QAChD,8CAA8C;QAC9C,OAAO,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAE,KAAK,CAAC,QAAQ,CAAS,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;KAC7E;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/get-caller-file/package.json b/node_modules/get-caller-file/package.json new file mode 100644 index 0000000..b0dd571 --- /dev/null +++ b/node_modules/get-caller-file/package.json @@ -0,0 +1,42 @@ +{ + "name": "get-caller-file", + "version": "2.0.5", + "description": "", + "main": "index.js", + "directories": { + "test": "tests" + }, + "files": [ + "index.js", + "index.js.map", + "index.d.ts" + ], + "scripts": { + "prepare": "tsc", + "test": "mocha test", + "test:debug": "mocha test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/stefanpenner/get-caller-file.git" + }, + "author": "Stefan Penner", + "license": "ISC", + "bugs": { + "url": "https://github.com/stefanpenner/get-caller-file/issues" + }, + "homepage": "https://github.com/stefanpenner/get-caller-file#readme", + "devDependencies": { + "@types/chai": "^4.1.7", + "@types/ensure-posix-path": "^1.0.0", + "@types/mocha": "^5.2.6", + "@types/node": "^11.10.5", + "chai": "^4.1.2", + "ensure-posix-path": "^1.0.1", + "mocha": "^5.2.0", + "typescript": "^3.3.3333" + }, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } +} diff --git a/node_modules/get-intrinsic/.eslintrc b/node_modules/get-intrinsic/.eslintrc new file mode 100644 index 0000000..8376636 --- /dev/null +++ b/node_modules/get-intrinsic/.eslintrc @@ -0,0 +1,38 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "es6": true, + "es2017": true, + "es2020": true, + "es2021": true, + "es2022": true, + }, + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "id-length": 0, + "max-lines": 0, + "max-lines-per-function": [2, 90], + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "multiline-comment-style": 0, + "no-magic-numbers": 0, + "sort-keys": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "new-cap": 0, + }, + }, + ], +} diff --git a/node_modules/get-intrinsic/.github/FUNDING.yml b/node_modules/get-intrinsic/.github/FUNDING.yml new file mode 100644 index 0000000..8e8da0d --- /dev/null +++ b/node_modules/get-intrinsic/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/get-intrinsic +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/get-intrinsic/.nycrc b/node_modules/get-intrinsic/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/get-intrinsic/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/get-intrinsic/CHANGELOG.md b/node_modules/get-intrinsic/CHANGELOG.md new file mode 100644 index 0000000..37370b9 --- /dev/null +++ b/node_modules/get-intrinsic/CHANGELOG.md @@ -0,0 +1,117 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.1](https://github.com/ljharb/get-intrinsic/compare/v1.2.0...v1.2.1) - 2023-05-13 + +### Commits + +- [Fix] avoid a crash in envs without `__proto__` [`7bad8d0`](https://github.com/ljharb/get-intrinsic/commit/7bad8d061bf8721733b58b73a2565af2b6756b64) +- [Dev Deps] update `es-abstract` [`c60e6b7`](https://github.com/ljharb/get-intrinsic/commit/c60e6b7b4cf9660c7f27ed970970fd55fac48dc5) + +## [v1.2.0](https://github.com/ljharb/get-intrinsic/compare/v1.1.3...v1.2.0) - 2023-01-19 + +### Commits + +- [actions] update checkout action [`ca6b12f`](https://github.com/ljharb/get-intrinsic/commit/ca6b12f31eaacea4ea3b055e744cd61623385ffb) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `tape` [`41a3727`](https://github.com/ljharb/get-intrinsic/commit/41a3727d0026fa04273ae216a5f8e12eefd72da8) +- [Fix] ensure `Error.prototype` is undeniable [`c511e97`](https://github.com/ljharb/get-intrinsic/commit/c511e97ae99c764c4524b540dee7a70757af8da3) +- [Dev Deps] update `aud`, `es-abstract`, `tape` [`1bef8a8`](https://github.com/ljharb/get-intrinsic/commit/1bef8a8fd439ebb80863199b6189199e0851ac67) +- [Dev Deps] update `aud`, `es-abstract` [`0d41f16`](https://github.com/ljharb/get-intrinsic/commit/0d41f16bcd500bc28b7bfc98043ebf61ea081c26) +- [New] add `BigInt64Array` and `BigUint64Array` [`a6cca25`](https://github.com/ljharb/get-intrinsic/commit/a6cca25f29635889b7e9bd669baf9e04be90e48c) +- [Tests] use `gopd` [`ecf7722`](https://github.com/ljharb/get-intrinsic/commit/ecf7722240d15cfd16edda06acf63359c10fb9bd) + +## [v1.1.3](https://github.com/ljharb/get-intrinsic/compare/v1.1.2...v1.1.3) - 2022-09-12 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `tape` [`07ff291`](https://github.com/ljharb/get-intrinsic/commit/07ff291816406ebe5a12d7f16965bde0942dd688) +- [Fix] properly check for % signs [`50ac176`](https://github.com/ljharb/get-intrinsic/commit/50ac1760fe99c227e64eabde76e9c0e44cd881b5) + +## [v1.1.2](https://github.com/ljharb/get-intrinsic/compare/v1.1.1...v1.1.2) - 2022-06-08 + +### Fixed + +- [Fix] properly validate against extra % signs [`#16`](https://github.com/ljharb/get-intrinsic/issues/16) + +### Commits + +- [actions] reuse common workflows [`0972547`](https://github.com/ljharb/get-intrinsic/commit/0972547efd0abc863fe4c445a6ca7eb4f8c6901d) +- [meta] use `npmignore` to autogenerate an npmignore file [`5ba0b51`](https://github.com/ljharb/get-intrinsic/commit/5ba0b51d8d8d4f1c31d426d74abc0770fd106bad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c364492`](https://github.com/ljharb/get-intrinsic/commit/c364492af4af51333e6f81c0bf21fd3d602c3661) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es-abstract`, `object-inspect`, `tape` [`dc04dad`](https://github.com/ljharb/get-intrinsic/commit/dc04dad86f6e5608775a2640cb0db5927ae29ed9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `safe-publish-latest`, `tape` [`1c14059`](https://github.com/ljharb/get-intrinsic/commit/1c1405984e86dd2dc9366c15d8a0294a96a146a5) +- [Tests] use `mock-property` [`b396ef0`](https://github.com/ljharb/get-intrinsic/commit/b396ef05bb73b1d699811abd64b0d9b97997fdda) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c2c758d`](https://github.com/ljharb/get-intrinsic/commit/c2c758d3b90af4fef0a76910d8d3c292ec8d1d3e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`29e3c09`](https://github.com/ljharb/get-intrinsic/commit/29e3c091c2bf3e17099969847e8729d0e46896de) +- [actions] update codecov uploader [`8cbc141`](https://github.com/ljharb/get-intrinsic/commit/8cbc1418940d7a8941f3a7985cbc4ac095c5e13d) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`10b6f5c`](https://github.com/ljharb/get-intrinsic/commit/10b6f5c02593fb3680c581d696ac124e30652932) +- [readme] add github actions/codecov badges [`4e25400`](https://github.com/ljharb/get-intrinsic/commit/4e25400d9f51ae9eb059cbe22d9144e70ea214e8) +- [Tests] use `for-each` instead of `foreach` [`c05b957`](https://github.com/ljharb/get-intrinsic/commit/c05b957ad9a7bc7721af7cc9e9be1edbfe057496) +- [Dev Deps] update `es-abstract` [`29b05ae`](https://github.com/ljharb/get-intrinsic/commit/29b05aec3e7330e9ad0b8e0f685a9112c20cdd97) +- [meta] use `prepublishOnly` script for npm 7+ [`95c285d`](https://github.com/ljharb/get-intrinsic/commit/95c285da810516057d3bbfa871176031af38f05d) +- [Deps] update `has-symbols` [`593cb4f`](https://github.com/ljharb/get-intrinsic/commit/593cb4fb38e7922e40e42c183f45274b636424cd) +- [readme] fix repo URLs [`1c8305b`](https://github.com/ljharb/get-intrinsic/commit/1c8305b5365827c9b6fc785434aac0e1328ff2f5) +- [Deps] update `has-symbols` [`c7138b6`](https://github.com/ljharb/get-intrinsic/commit/c7138b6c6d73132d859471fb8c13304e1e7c8b20) +- [Dev Deps] remove unused `has-bigints` [`bd63aff`](https://github.com/ljharb/get-intrinsic/commit/bd63aff6ad8f3a986c557fcda2914187bdaab359) + +## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03 + +### Fixed + +- [meta] export `./package.json` [`#9`](https://github.com/ljharb/get-intrinsic/issues/9) + +### Commits + +- [readme] flesh out the readme; use `evalmd` [`d12f12c`](https://github.com/ljharb/get-intrinsic/commit/d12f12c15345a0a0772cc65a7c64369529abd614) +- [eslint] set up proper globals config [`5a8c098`](https://github.com/ljharb/get-intrinsic/commit/5a8c0984e3319d1ac0e64b102f8ec18b64e79f36) +- [Dev Deps] update `eslint` [`7b9a5c0`](https://github.com/ljharb/get-intrinsic/commit/7b9a5c0d31a90ca1a1234181c74988fb046701cd) + +## [v1.1.0](https://github.com/ljharb/get-intrinsic/compare/v1.0.2...v1.1.0) - 2021-01-25 + +### Fixed + +- [Refactor] delay `Function` eval until syntax-derived values are requested [`#3`](https://github.com/ljharb/get-intrinsic/issues/3) + +### Commits + +- [Tests] migrate tests to Github Actions [`2ab762b`](https://github.com/ljharb/get-intrinsic/commit/2ab762b48164aea8af37a40ba105bbc8246ab8c4) +- [meta] do not publish github action workflow files [`5e7108e`](https://github.com/ljharb/get-intrinsic/commit/5e7108e4768b244d48d9567ba4f8a6cab9c65b8e) +- [Tests] add some coverage [`01ac7a8`](https://github.com/ljharb/get-intrinsic/commit/01ac7a87ac29738567e8524cd8c9e026b1fa8cb3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `call-bind`, `es-abstract`, `tape`; add `call-bind` [`911b672`](https://github.com/ljharb/get-intrinsic/commit/911b672fbffae433a96924c6ce013585e425f4b7) +- [Refactor] rearrange evalled constructors a bit [`7e7e4bf`](https://github.com/ljharb/get-intrinsic/commit/7e7e4bf583f3799c8ac1c6c5e10d2cb553957347) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`0199968`](https://github.com/ljharb/get-intrinsic/commit/01999687a263ffce0a3cb011dfbcb761754aedbc) + +## [v1.0.2](https://github.com/ljharb/get-intrinsic/compare/v1.0.1...v1.0.2) - 2020-12-17 + +### Commits + +- [Fix] Throw for non‑existent intrinsics [`68f873b`](https://github.com/ljharb/get-intrinsic/commit/68f873b013c732a05ad6f5fc54f697e55515461b) +- [Fix] Throw for non‑existent segments in the intrinsic path [`8325dee`](https://github.com/ljharb/get-intrinsic/commit/8325deee43128f3654d3399aa9591741ebe17b21) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-bigints`, `object-inspect` [`0c227a7`](https://github.com/ljharb/get-intrinsic/commit/0c227a7d8b629166f25715fd242553892e458525) +- [meta] do not lint coverage output [`70d2419`](https://github.com/ljharb/get-intrinsic/commit/70d24199b620043cd9110fc5f426d214ebe21dc9) + +## [v1.0.1](https://github.com/ljharb/get-intrinsic/compare/v1.0.0...v1.0.1) - 2020-10-30 + +### Commits + +- [Tests] gather coverage data on every job [`d1d280d`](https://github.com/ljharb/get-intrinsic/commit/d1d280dec714e3f0519cc877dbcb193057d9cac6) +- [Fix] add missing dependencies [`5031771`](https://github.com/ljharb/get-intrinsic/commit/5031771bb1095b38be88ce7c41d5de88718e432e) +- [Tests] use `es-value-fixtures` [`af48765`](https://github.com/ljharb/get-intrinsic/commit/af48765a23c5323fb0b6b38dbf00eb5099c7bebc) + +## v1.0.0 - 2020-10-29 + +### Commits + +- Implementation [`bbce57c`](https://github.com/ljharb/get-intrinsic/commit/bbce57c6f33d05b2d8d3efa273ceeb3ee01127bb) +- Tests [`17b4f0d`](https://github.com/ljharb/get-intrinsic/commit/17b4f0d56dea6b4059b56fc30ef3ee4d9500ebc2) +- Initial commit [`3153294`](https://github.com/ljharb/get-intrinsic/commit/31532948de363b0a27dd9fd4649e7b7028ec4b44) +- npm init [`fb326c4`](https://github.com/ljharb/get-intrinsic/commit/fb326c4d2817c8419ec31de1295f06bb268a7902) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`48862fb`](https://github.com/ljharb/get-intrinsic/commit/48862fb2508c8f6a57968e6d08b7c883afc9d550) +- [meta] add `auto-changelog` [`5f28ad0`](https://github.com/ljharb/get-intrinsic/commit/5f28ad019e060a353d8028f9f2591a9cc93074a1) +- [meta] add "funding"; create `FUNDING.yml` [`c2bbdde`](https://github.com/ljharb/get-intrinsic/commit/c2bbddeba73a875be61484ee4680b129a6d4e0a1) +- [Tests] add `npm run lint` [`0a84b98`](https://github.com/ljharb/get-intrinsic/commit/0a84b98b22b7cf7a748666f705b0003a493c35fd) +- Only apps should have lockfiles [`9586c75`](https://github.com/ljharb/get-intrinsic/commit/9586c75866c1ee678e4d5d4dbbdef6997e511b05) diff --git a/node_modules/get-intrinsic/LICENSE b/node_modules/get-intrinsic/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/node_modules/get-intrinsic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-intrinsic/README.md b/node_modules/get-intrinsic/README.md new file mode 100644 index 0000000..3aa0bba --- /dev/null +++ b/node_modules/get-intrinsic/README.md @@ -0,0 +1,71 @@ +# get-intrinsic [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Get and robustly cache all JS language-level intrinsics at first require time. + +See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference. + +## Example + +```js +var GetIntrinsic = require('get-intrinsic'); +var assert = require('assert'); + +// static methods +assert.equal(GetIntrinsic('%Math.pow%'), Math.pow); +assert.equal(Math.pow(2, 3), 8); +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); +delete Math.pow; +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); + +// instance methods +var arr = [1]; +assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push); +assert.deepEqual(arr, [1]); + +arr.push(2); +assert.deepEqual(arr, [1, 2]); + +GetIntrinsic('%Array.prototype.push%').call(arr, 3); +assert.deepEqual(arr, [1, 2, 3]); + +delete Array.prototype.push; +GetIntrinsic('%Array.prototype.push%').call(arr, 4); +assert.deepEqual(arr, [1, 2, 3, 4]); + +// missing features +delete JSON.parse; // to simulate a real intrinsic that is missing in the environment +assert.throws(() => GetIntrinsic('%JSON.parse%')); +assert.equal(undefined, GetIntrinsic('%JSON.parse%', true)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/get-intrinsic +[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg +[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg +[deps-url]: https://david-dm.org/ljharb/get-intrinsic +[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic +[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic +[actions-url]: https://github.com/ljharb/get-intrinsic/actions diff --git a/node_modules/get-intrinsic/index.js b/node_modules/get-intrinsic/index.js new file mode 100644 index 0000000..c1957c9 --- /dev/null +++ b/node_modules/get-intrinsic/index.js @@ -0,0 +1,351 @@ +'use strict'; + +var undefined; + +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); +var hasProto = require('has-proto')(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('has'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; diff --git a/node_modules/get-intrinsic/package.json b/node_modules/get-intrinsic/package.json new file mode 100644 index 0000000..9c7058f --- /dev/null +++ b/node_modules/get-intrinsic/package.json @@ -0,0 +1,93 @@ +{ + "name": "get-intrinsic", + "version": "1.2.1", + "description": "Get and robustly cache all JS language-level intrinsics at first require time", + "main": "index.js", + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-intrinsic.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "intrinsic", + "getintrinsic", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-intrinsic/issues" + }, + "homepage": "https://github.com/ljharb/get-intrinsic#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.1", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.2", + "es-abstract": "^1.21.2", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "mock-property": "^1.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.3" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + }, + "testling": { + "files": "test/GetIntrinsic.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/get-intrinsic/test/GetIntrinsic.js b/node_modules/get-intrinsic/test/GetIntrinsic.js new file mode 100644 index 0000000..1cc08e0 --- /dev/null +++ b/node_modules/get-intrinsic/test/GetIntrinsic.js @@ -0,0 +1,274 @@ +'use strict'; + +var GetIntrinsic = require('../'); + +var test = require('tape'); +var forEach = require('for-each'); +var debug = require('object-inspect'); +var generatorFns = require('make-generator-function')(); +var asyncFns = require('make-async-function').list(); +var asyncGenFns = require('make-async-generator-function')(); +var mockProperty = require('mock-property'); + +var callBound = require('call-bind/callBound'); +var v = require('es-value-fixtures'); +var $gOPD = require('gopd'); +var DefinePropertyOrThrow = require('es-abstract/2021/DefinePropertyOrThrow'); + +var $isProto = callBound('%Object.prototype.isPrototypeOf%'); + +test('export', function (t) { + t.equal(typeof GetIntrinsic, 'function', 'it is a function'); + t.equal(GetIntrinsic.length, 2, 'function has length of 2'); + + t.end(); +}); + +test('throws', function (t) { + t['throws']( + function () { GetIntrinsic('not an intrinsic'); }, + SyntaxError, + 'nonexistent intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic(''); }, + TypeError, + 'empty string intrinsic throws a type error' + ); + + t['throws']( + function () { GetIntrinsic('.'); }, + SyntaxError, + '"just a dot" intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('%String'); }, + SyntaxError, + 'Leading % without trailing % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('String%'); }, + SyntaxError, + 'Trailing % without leading % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic("String['prototype]"); }, + SyntaxError, + 'Dynamic property access is disallowed for intrinsics (unterminated string)' + ); + + t['throws']( + function () { GetIntrinsic('%Proxy.prototype.undefined%'); }, + TypeError, + "Throws when middle part doesn't exist (%Proxy.prototype.undefined%)" + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%garbage%'); }, + SyntaxError, + 'Throws with extra percent signs' + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%push%'); }, + SyntaxError, + 'Throws with extra percent signs, even on an existing intrinsic' + ); + + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { GetIntrinsic(nonString); }, + TypeError, + debug(nonString) + ' is not a String' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { GetIntrinsic('%', nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach([ + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty' + ], function (objectProtoMember) { + t['throws']( + function () { GetIntrinsic(objectProtoMember); }, + SyntaxError, + debug(objectProtoMember) + ' is not an intrinsic' + ); + }); + + t.end(); +}); + +test('base intrinsics', function (t) { + t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); + t.equal(GetIntrinsic('Object'), Object, 'Object yields Object'); + t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); + t.equal(GetIntrinsic('Array'), Array, 'Array yields Array'); + + t.end(); +}); + +test('dotted paths', function (t) { + t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); + t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString'); + t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); + t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push'); + + test('underscore paths are aliases for dotted paths', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%ObjProto_toString%'); + + forEach([ + '%Object.prototype.toString%', + 'Object.prototype.toString', + '%ObjectPrototype.toString%', + 'ObjectPrototype.toString', + '%ObjProto_toString%', + 'ObjProto_toString' + ], function (name) { + DefinePropertyOrThrow(Object.prototype, 'toString', { + '[[Value]]': function toString() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString'); + }); + + DefinePropertyOrThrow(Object.prototype, 'toString', { '[[Value]]': original }); + st.end(); + }); + + test('dotted paths cache', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%Object.prototype.propertyIsEnumerable%'); + + forEach([ + '%Object.prototype.propertyIsEnumerable%', + 'Object.prototype.propertyIsEnumerable', + '%ObjectPrototype.propertyIsEnumerable%', + 'ObjectPrototype.propertyIsEnumerable' + ], function (name) { + var restore = mockProperty(Object.prototype, 'propertyIsEnumerable', { + value: function propertyIsEnumerable() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable'); + + restore(); + }); + + st.end(); + }); + + test('dotted path reports correct error', function (st) { + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsic.prototype.property%'); + }, /%NonExistentIntrinsic%/, 'The base intrinsic of %NonExistentIntrinsic.prototype.property% is %NonExistentIntrinsic%'); + + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsicPrototype.property%'); + }, /%NonExistentIntrinsicPrototype%/, 'The base intrinsic of %NonExistentIntrinsicPrototype.property% is %NonExistentIntrinsicPrototype%'); + + st.end(); + }); + + t.end(); +}); + +test('accessors', { skip: !$gOPD || typeof Map !== 'function' }, function (t) { + var actual = $gOPD(Map.prototype, 'size'); + t.ok(actual, 'Map.prototype.size has a descriptor'); + t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function'); + t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it'); + t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it'); + + t.end(); +}); + +test('generator functions', { skip: !generatorFns.length }, function (t) { + var $GeneratorFunction = GetIntrinsic('%GeneratorFunction%'); + var $GeneratorFunctionPrototype = GetIntrinsic('%Generator%'); + var $GeneratorPrototype = GetIntrinsic('%GeneratorPrototype%'); + + forEach(generatorFns, function (genFn) { + var fnName = genFn.name; + fnName = fnName ? "'" + fnName + "'" : 'genFn'; + + t.ok(genFn instanceof $GeneratorFunction, fnName + ' instanceof %GeneratorFunction%'); + t.ok($isProto($GeneratorFunctionPrototype, genFn), '%Generator% is prototype of ' + fnName); + t.ok($isProto($GeneratorPrototype, genFn.prototype), '%GeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('async functions', { skip: !asyncFns.length }, function (t) { + var $AsyncFunction = GetIntrinsic('%AsyncFunction%'); + var $AsyncFunctionPrototype = GetIntrinsic('%AsyncFunctionPrototype%'); + + forEach(asyncFns, function (asyncFn) { + var fnName = asyncFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncFn'; + + t.ok(asyncFn instanceof $AsyncFunction, fnName + ' instanceof %AsyncFunction%'); + t.ok($isProto($AsyncFunctionPrototype, asyncFn), '%AsyncFunctionPrototype% is prototype of ' + fnName); + }); + + t.end(); +}); + +test('async generator functions', { skip: asyncGenFns.length === 0 }, function (t) { + var $AsyncGeneratorFunction = GetIntrinsic('%AsyncGeneratorFunction%'); + var $AsyncGeneratorFunctionPrototype = GetIntrinsic('%AsyncGenerator%'); + var $AsyncGeneratorPrototype = GetIntrinsic('%AsyncGeneratorPrototype%'); + + forEach(asyncGenFns, function (asyncGenFn) { + var fnName = asyncGenFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncGenFn'; + + t.ok(asyncGenFn instanceof $AsyncGeneratorFunction, fnName + ' instanceof %AsyncGeneratorFunction%'); + t.ok($isProto($AsyncGeneratorFunctionPrototype, asyncGenFn), '%AsyncGenerator% is prototype of ' + fnName); + t.ok($isProto($AsyncGeneratorPrototype, asyncGenFn.prototype), '%AsyncGeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('%ThrowTypeError%', function (t) { + var $ThrowTypeError = GetIntrinsic('%ThrowTypeError%'); + + t.equal(typeof $ThrowTypeError, 'function', 'is a function'); + t['throws']( + $ThrowTypeError, + TypeError, + '%ThrowTypeError% throws a TypeError' + ); + + t.end(); +}); + +test('allowMissing', { skip: asyncGenFns.length > 0 }, function (t) { + t['throws']( + function () { GetIntrinsic('%AsyncGeneratorPrototype%'); }, + TypeError, + 'throws when missing' + ); + + t.equal( + GetIntrinsic('%AsyncGeneratorPrototype%', true), + undefined, + 'does not throw when allowMissing' + ); + + t.end(); +}); diff --git a/node_modules/get-package-type/CHANGELOG.md b/node_modules/get-package-type/CHANGELOG.md new file mode 100644 index 0000000..5f2c4cc --- /dev/null +++ b/node_modules/get-package-type/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## 0.1.0 (2020-05-19) + + +### Features + +* Initial implementation ([52863f4](https://github.com/cfware/get-package-type/commit/52863f4b2b7b287fe1adcd97331231a2911312dc)) diff --git a/node_modules/get-package-type/LICENSE b/node_modules/get-package-type/LICENSE new file mode 100644 index 0000000..971e3b7 --- /dev/null +++ b/node_modules/get-package-type/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 CFWare, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-package-type/README.md b/node_modules/get-package-type/README.md new file mode 100644 index 0000000..8e1ebf2 --- /dev/null +++ b/node_modules/get-package-type/README.md @@ -0,0 +1,32 @@ +# get-package-type [![NPM Version][npm-image]][npm-url] + +Determine the `package.json#type` which applies to a location. + +## Usage + +```js +const getPackageType = require('get-package-type'); + +(async () => { + console.log(await getPackageType('file.js')); + console.log(getPackageType.sync('file.js')); +})(); +``` + +This function does not validate the value found in `package.json#type`. Any truthy value +found will be returned. Non-truthy values will be reported as `commonjs`. + +The argument must be a filename. +```js +// This never looks at `dir1/`, first attempts to load `./package.json`. +const type1 = await getPackageType('dir1/'); + +// This attempts to load `dir1/package.json`. +const type2 = await getPackageType('dir1/index.cjs'); +``` + +The extension of the filename does not effect the result. The primary use case for this +module is to determine if `myapp.config.js` should be loaded with `require` or `import`. + +[npm-image]: https://img.shields.io/npm/v/get-package-type.svg +[npm-url]: https://npmjs.org/package/get-package-type diff --git a/node_modules/get-package-type/async.cjs b/node_modules/get-package-type/async.cjs new file mode 100644 index 0000000..fa7fd5c --- /dev/null +++ b/node_modules/get-package-type/async.cjs @@ -0,0 +1,52 @@ +'use strict'; + +const path = require('path'); +const {promisify} = require('util'); +const readFile = promisify(require('fs').readFile); + +const isNodeModules = require('./is-node-modules.cjs'); +const resultsCache = require('./cache.cjs'); + +const promiseCache = new Map(); + +async function getDirectoryTypeActual(directory) { + if (isNodeModules(directory)) { + return 'commonjs'; + } + + try { + return JSON.parse(await readFile(path.resolve(directory, 'package.json'))).type || 'commonjs'; + } catch (_) { + } + + const parent = path.dirname(directory); + if (parent === directory) { + return 'commonjs'; + } + + return getDirectoryType(parent); +} + +async function getDirectoryType(directory) { + if (resultsCache.has(directory)) { + return resultsCache.get(directory); + } + + if (promiseCache.has(directory)) { + return promiseCache.get(directory); + } + + const promise = getDirectoryTypeActual(directory); + promiseCache.set(directory, promise); + const result = await promise; + resultsCache.set(directory, result); + promiseCache.delete(directory); + + return result; +} + +function getPackageType(filename) { + return getDirectoryType(path.resolve(path.dirname(filename))); +} + +module.exports = getPackageType; diff --git a/node_modules/get-package-type/cache.cjs b/node_modules/get-package-type/cache.cjs new file mode 100644 index 0000000..4fd928a --- /dev/null +++ b/node_modules/get-package-type/cache.cjs @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = new Map(); diff --git a/node_modules/get-package-type/index.cjs b/node_modules/get-package-type/index.cjs new file mode 100644 index 0000000..b5b0734 --- /dev/null +++ b/node_modules/get-package-type/index.cjs @@ -0,0 +1,7 @@ +'use strict'; + +const getPackageType = require('./async.cjs'); +const getPackageTypeSync = require('./sync.cjs'); + +module.exports = filename => getPackageType(filename); +module.exports.sync = getPackageTypeSync; diff --git a/node_modules/get-package-type/is-node-modules.cjs b/node_modules/get-package-type/is-node-modules.cjs new file mode 100644 index 0000000..5a37a77 --- /dev/null +++ b/node_modules/get-package-type/is-node-modules.cjs @@ -0,0 +1,15 @@ +'use strict'; + +const path = require('path'); + +function isNodeModules(directory) { + let basename = path.basename(directory); + /* istanbul ignore next: platform specific branch */ + if (path.sep === '\\') { + basename = basename.toLowerCase(); + } + + return basename === 'node_modules'; +} + +module.exports = isNodeModules; diff --git a/node_modules/get-package-type/package.json b/node_modules/get-package-type/package.json new file mode 100644 index 0000000..dcb0ea8 --- /dev/null +++ b/node_modules/get-package-type/package.json @@ -0,0 +1,35 @@ +{ + "name": "get-package-type", + "version": "0.1.0", + "description": "Determine the `package.json#type` which applies to a location", + "type": "module", + "main": "index.cjs", + "exports": "./index.cjs", + "scripts": { + "pretest": "if-ver -ge 10 || exit 0; cfware-lint .", + "tests-only": "nyc -s node test.cjs", + "test": "npm run -s tests-only", + "posttest": "nyc report --check-coverage" + }, + "engines": { + "node": ">=8.0.0" + }, + "author": "Corey Farrell", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/cfware/get-package-type.git" + }, + "bugs": { + "url": "https://github.com/cfware/get-package-type/issues" + }, + "homepage": "https://github.com/cfware/get-package-type#readme", + "dependencies": {}, + "devDependencies": { + "@cfware/lint": "^1.4.3", + "@cfware/nyc": "^0.7.0", + "if-ver": "^1.1.0", + "libtap": "^0.3.0", + "nyc": "^15.0.1" + } +} diff --git a/node_modules/get-package-type/sync.cjs b/node_modules/get-package-type/sync.cjs new file mode 100644 index 0000000..85090a6 --- /dev/null +++ b/node_modules/get-package-type/sync.cjs @@ -0,0 +1,42 @@ +'use strict'; + +const path = require('path'); +const {readFileSync} = require('fs'); + +const isNodeModules = require('./is-node-modules.cjs'); +const resultsCache = require('./cache.cjs'); + +function getDirectoryTypeActual(directory) { + if (isNodeModules(directory)) { + return 'commonjs'; + } + + try { + return JSON.parse(readFileSync(path.resolve(directory, 'package.json'))).type || 'commonjs'; + } catch (_) { + } + + const parent = path.dirname(directory); + if (parent === directory) { + return 'commonjs'; + } + + return getDirectoryType(parent); +} + +function getDirectoryType(directory) { + if (resultsCache.has(directory)) { + return resultsCache.get(directory); + } + + const result = getDirectoryTypeActual(directory); + resultsCache.set(directory, result); + + return result; +} + +function getPackageTypeSync(filename) { + return getDirectoryType(path.resolve(path.dirname(filename))); +} + +module.exports = getPackageTypeSync; diff --git a/node_modules/get-stream/buffer-stream.js b/node_modules/get-stream/buffer-stream.js new file mode 100644 index 0000000..2dd7574 --- /dev/null +++ b/node_modules/get-stream/buffer-stream.js @@ -0,0 +1,52 @@ +'use strict'; +const {PassThrough: PassThroughStream} = require('stream'); + +module.exports = options => { + options = {...options}; + + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; + + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } + + if (isBuffer) { + encoding = null; + } + + const stream = new PassThroughStream({objectMode}); + + if (encoding) { + stream.setEncoding(encoding); + } + + let length = 0; + const chunks = []; + + stream.on('data', chunk => { + chunks.push(chunk); + + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); + + stream.getBufferedValue = () => { + if (array) { + return chunks; + } + + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; + + stream.getBufferedLength = () => length; + + return stream; +}; diff --git a/node_modules/get-stream/index.d.ts b/node_modules/get-stream/index.d.ts new file mode 100644 index 0000000..9485b2b --- /dev/null +++ b/node_modules/get-stream/index.d.ts @@ -0,0 +1,105 @@ +/// +import {Stream} from 'stream'; + +declare class MaxBufferErrorClass extends Error { + readonly name: 'MaxBufferError'; + constructor(); +} + +declare namespace getStream { + interface Options { + /** + Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `MaxBufferError` error. + + @default Infinity + */ + readonly maxBuffer?: number; + } + + interface OptionsWithEncoding extends Options { + /** + [Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream. + + @default 'utf8' + */ + readonly encoding?: EncodingType; + } + + type MaxBufferError = MaxBufferErrorClass; +} + +declare const getStream: { + /** + Get the `stream` as a string. + + @returns A promise that resolves when the end event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode. + + @example + ``` + import * as fs from 'fs'; + import getStream = require('get-stream'); + + (async () => { + const stream = fs.createReadStream('unicorn.txt'); + + console.log(await getStream(stream)); + // ,,))))))));, + // __)))))))))))))), + // \|/ -\(((((''''((((((((. + // -*-==//////(('' . `)))))), + // /|\ ))| o ;-. '((((( ,(, + // ( `| / ) ;))))' ,_))^;(~ + // | | | ,))((((_ _____------~~~-. %,;(;(>';'~ + // o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ + // ; ''''```` `: `:::|\,__,%% );`'; ~ + // | _ ) / `:|`----' `-' + // ______/\/~ | / / + // /~;;.____/;;' / ___--,-( `;;;/ + // / // _;______;'------~~~~~ /;;/\ / + // // | | / ; \;;,\ + // (<_ | ; /',/-----' _> + // \_| ||_ //~;~~~~~~~~~ + // `\_| (,~~ + // \~\ + // ~~ + })(); + ``` + */ + (stream: Stream, options?: getStream.OptionsWithEncoding): Promise; + + /** + Get the `stream` as a buffer. + + It honors the `maxBuffer` option as above, but it refers to byte length rather than string length. + */ + buffer( + stream: Stream, + options?: getStream.Options + ): Promise; + + /** + Get the `stream` as an array of values. + + It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen: + + - When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes). + - When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array. + - When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array. + */ + array( + stream: Stream, + options?: getStream.Options + ): Promise; + array( + stream: Stream, + options: getStream.OptionsWithEncoding<'buffer'> + ): Promise; + array( + stream: Stream, + options: getStream.OptionsWithEncoding + ): Promise; + + MaxBufferError: typeof MaxBufferErrorClass; +}; + +export = getStream; diff --git a/node_modules/get-stream/index.js b/node_modules/get-stream/index.js new file mode 100644 index 0000000..1c5d028 --- /dev/null +++ b/node_modules/get-stream/index.js @@ -0,0 +1,61 @@ +'use strict'; +const {constants: BufferConstants} = require('buffer'); +const stream = require('stream'); +const {promisify} = require('util'); +const bufferStream = require('./buffer-stream'); + +const streamPipelinePromisified = promisify(stream.pipeline); + +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} + +async function getStream(inputStream, options) { + if (!inputStream) { + throw new Error('Expected a stream'); + } + + options = { + maxBuffer: Infinity, + ...options + }; + + const {maxBuffer} = options; + const stream = bufferStream(options); + + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } + + reject(error); + }; + + (async () => { + try { + await streamPipelinePromisified(inputStream, stream); + resolve(); + } catch (error) { + rejectPromise(error); + } + })(); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + + return stream.getBufferedValue(); +} + +module.exports = getStream; +module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +module.exports.MaxBufferError = MaxBufferError; diff --git a/node_modules/get-stream/license b/node_modules/get-stream/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/get-stream/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/get-stream/package.json b/node_modules/get-stream/package.json new file mode 100644 index 0000000..bd47a75 --- /dev/null +++ b/node_modules/get-stream/package.json @@ -0,0 +1,47 @@ +{ + "name": "get-stream", + "version": "6.0.1", + "description": "Get a stream as a string, buffer, or array", + "license": "MIT", + "repository": "sindresorhus/get-stream", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "buffer-stream.js" + ], + "keywords": [ + "get", + "stream", + "promise", + "concat", + "string", + "text", + "buffer", + "read", + "data", + "consume", + "readable", + "readablestream", + "array", + "object" + ], + "devDependencies": { + "@types/node": "^14.0.27", + "ava": "^2.4.0", + "into-stream": "^5.0.0", + "tsd": "^0.13.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/get-stream/readme.md b/node_modules/get-stream/readme.md new file mode 100644 index 0000000..70b01fd --- /dev/null +++ b/node_modules/get-stream/readme.md @@ -0,0 +1,124 @@ +# get-stream + +> Get a stream as a string, buffer, or array + +## Install + +``` +$ npm install get-stream +``` + +## Usage + +```js +const fs = require('fs'); +const getStream = require('get-stream'); + +(async () => { + const stream = fs.createReadStream('unicorn.txt'); + + console.log(await getStream(stream)); + /* + ,,))))))));, + __)))))))))))))), + \|/ -\(((((''''((((((((. + -*-==//////(('' . `)))))), + /|\ ))| o ;-. '((((( ,(, + ( `| / ) ;))))' ,_))^;(~ + | | | ,))((((_ _____------~~~-. %,;(;(>';'~ + o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ + ; ''''```` `: `:::|\,__,%% );`'; ~ + | _ ) / `:|`----' `-' + ______/\/~ | / / + /~;;.____/;;' / ___--,-( `;;;/ + / // _;______;'------~~~~~ /;;/\ / + // | | / ; \;;,\ + (<_ | ; /',/-----' _> + \_| ||_ //~;~~~~~~~~~ + `\_| (,~~ + \~\ + ~~ + */ +})(); +``` + +## API + +The methods returns a promise that resolves when the `end` event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode. + +### getStream(stream, options?) + +Get the `stream` as a string. + +#### options + +Type: `object` + +##### encoding + +Type: `string`\ +Default: `'utf8'` + +[Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream. + +##### maxBuffer + +Type: `number`\ +Default: `Infinity` + +Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `getStream.MaxBufferError` error. + +### getStream.buffer(stream, options?) + +Get the `stream` as a buffer. + +It honors the `maxBuffer` option as above, but it refers to byte length rather than string length. + +### getStream.array(stream, options?) + +Get the `stream` as an array of values. + +It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen: + +- When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes). + +- When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array. + +- When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array. + +## Errors + +If the input stream emits an `error` event, the promise will be rejected with the error. The buffered data will be attached to the `bufferedData` property of the error. + +```js +(async () => { + try { + await getStream(streamThatErrorsAtTheEnd('unicorn')); + } catch (error) { + console.log(error.bufferedData); + //=> 'unicorn' + } +})() +``` + +## FAQ + +### How is this different from [`concat-stream`](https://github.com/maxogden/concat-stream)? + +This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, buffer, or array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge `readable-stream` package. + +## Related + +- [get-stdin](https://github.com/sindresorhus/get-stdin) - Get stdin as a string or buffer + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/get-symbol-description/.eslintignore b/node_modules/get-symbol-description/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/get-symbol-description/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/get-symbol-description/.eslintrc b/node_modules/get-symbol-description/.eslintrc new file mode 100644 index 0000000..e824dab --- /dev/null +++ b/node_modules/get-symbol-description/.eslintrc @@ -0,0 +1,14 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/get-symbol-description/.github/FUNDING.yml b/node_modules/get-symbol-description/.github/FUNDING.yml new file mode 100644 index 0000000..499729c --- /dev/null +++ b/node_modules/get-symbol-description/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/symbol-description +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/get-symbol-description/.nycrc b/node_modules/get-symbol-description/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/get-symbol-description/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/get-symbol-description/CHANGELOG.md b/node_modules/get-symbol-description/CHANGELOG.md new file mode 100644 index 0000000..1e1c079 --- /dev/null +++ b/node_modules/get-symbol-description/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2021-08-17 + +### Commits + +- Initial commit: pulled from es-abstract [`6e34a05`](https://github.com/inspect-js/get-symbol-description/commit/6e34a05ef10ce8620078cf4cecbe276c1fc1ae77) +- Initial commit [`3862092`](https://github.com/inspect-js/get-symbol-description/commit/3862092248d8ffa071ec90ec39d73e8be14ba6f1) +- [meta] do not publish github action workflow files [`9d1e2b9`](https://github.com/inspect-js/get-symbol-description/commit/9d1e2b94dd97664da5d0666985a3695c23f45865) +- npm init [`5051b32`](https://github.com/inspect-js/get-symbol-description/commit/5051b3221829f364c44b4d5e9a0c35aab3247f6a) +- Only apps should have lockfiles [`b866d1c`](https://github.com/inspect-js/get-symbol-description/commit/b866d1c4b4029277618d968cfb3cbe00f012d1a7) diff --git a/node_modules/get-symbol-description/LICENSE b/node_modules/get-symbol-description/LICENSE new file mode 100644 index 0000000..7948bc0 --- /dev/null +++ b/node_modules/get-symbol-description/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-symbol-description/README.md b/node_modules/get-symbol-description/README.md new file mode 100644 index 0000000..c44e72a --- /dev/null +++ b/node_modules/get-symbol-description/README.md @@ -0,0 +1,43 @@ +# get-symbol-description [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Gets the description of a Symbol. Handles `Symbol()` vs `Symbol('')` properly when possible. + +## Example + +```js +var getSymbolDescription = require('get-symbol-description'); +var assert = require('assert'); + +assert(getSymbolDescription(Symbol()) === undefined); +assert(getSymbolDescription(Symbol('')) === ''); // or `undefined`, if in an engine that lacks name inference from concise method +assert(getSymbolDescription(Symbol('foo')) === 'foo'); +assert(getSymbolDescription(Symbol.iterator) === 'Symbol.iterator'); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/get-symbol-description +[2]: https://versionbadg.es/inspect-js/get-symbol-description.svg +[5]: https://david-dm.org/inspect-js/get-symbol-description.svg +[6]: https://david-dm.org/inspect-js/get-symbol-description +[7]: https://david-dm.org/inspect-js/get-symbol-description/dev-status.svg +[8]: https://david-dm.org/inspect-js/get-symbol-description#info=devDependencies +[11]: https://nodei.co/npm/get-symbol-description.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-symbol-description.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-symbol-description.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-symbol-description +[codecov-image]: https://codecov.io/gh/inspect-js/get-symbol-description/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/get-symbol-description/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/get-symbol-description +[actions-url]: https://github.com/inspect-js/get-symbol-description/actions diff --git a/node_modules/get-symbol-description/getInferredName.js b/node_modules/get-symbol-description/getInferredName.js new file mode 100644 index 0000000..2dab6e7 --- /dev/null +++ b/node_modules/get-symbol-description/getInferredName.js @@ -0,0 +1,10 @@ +'use strict'; + +var getInferredName; +try { + // eslint-disable-next-line no-new-func + getInferredName = Function('s', 'return { [s]() {} }[s].name;'); +} catch (e) {} + +var inferred = function () {}; +module.exports = getInferredName && inferred.name === 'inferred' ? getInferredName : null; diff --git a/node_modules/get-symbol-description/index.js b/node_modules/get-symbol-description/index.js new file mode 100644 index 0000000..05d067f --- /dev/null +++ b/node_modules/get-symbol-description/index.js @@ -0,0 +1,43 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBound = require('call-bind/callBound'); + +var $SyntaxError = GetIntrinsic('%SyntaxError%'); +var getGlobalSymbolDescription = GetIntrinsic('%Symbol.keyFor%', true); +var thisSymbolValue = callBound('%Symbol.prototype.valueOf%', true); +var symToStr = callBound('Symbol.prototype.toString', true); + +var getInferredName = require('./getInferredName'); + +/* eslint-disable consistent-return */ +module.exports = callBound('%Symbol.prototype.description%', true) || function getSymbolDescription(symbol) { + if (!thisSymbolValue) { + throw new $SyntaxError('Symbols are not supported in this environment'); + } + + // will throw if not a symbol primitive or wrapper object + var sym = thisSymbolValue(symbol); + + if (getInferredName) { + var name = getInferredName(sym); + if (name === '') { + return; + } + return name.slice(1, -1); // name.slice('['.length, -']'.length); + } + + var desc; + if (getGlobalSymbolDescription) { + desc = getGlobalSymbolDescription(sym); + if (typeof desc === 'string') { + return desc; + } + } + + desc = symToStr(sym).slice(7, -1); // str.slice('Symbol('.length, -')'.length); + if (desc) { + return desc; + } +}; diff --git a/node_modules/get-symbol-description/package.json b/node_modules/get-symbol-description/package.json new file mode 100644 index 0000000..24b0e1a --- /dev/null +++ b/node_modules/get-symbol-description/package.json @@ -0,0 +1,71 @@ +{ + "name": "get-symbol-description", + "version": "1.0.0", + "description": "Gets the description of a Symbol. Handles `Symbol()` vs `Symbol('')` properly when possible.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./getInferredName": "./getInferredName.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/get-symbol-description.git" + }, + "keywords": [ + "symbol", + "ecmascript", + "javascript", + "description" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/get-symbol-description/issues" + }, + "homepage": "https://github.com/inspect-js/get-symbol-description#readme", + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "es-value-fixtures": "^1.2.1", + "eslint": "^7.32.0", + "evalmd": "^0.0.19", + "foreach": "^2.0.5", + "has": "^1.0.3", + "nyc": "^10.3.2", + "object-inspect": "^1.11.0", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.1" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/get-symbol-description/test/index.js b/node_modules/get-symbol-description/test/index.js new file mode 100644 index 0000000..d5363c2 --- /dev/null +++ b/node_modules/get-symbol-description/test/index.js @@ -0,0 +1,67 @@ +'use strict'; + +var test = require('tape'); +var debug = require('object-inspect'); +var forEach = require('foreach'); +var has = require('has'); +var v = require('es-value-fixtures'); + +var getSymbolDescription = require('../'); +var getInferredName = require('../getInferredName'); + +test('getSymbolDescription', function (t) { + t.test('no symbols', { skip: v.hasSymbols }, function (st) { + st['throws']( + getSymbolDescription, + SyntaxError, + 'requires Symbol support' + ); + + st.end(); + }); + + forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { + t['throws']( + function () { getSymbolDescription(nonSymbol); }, + v.hasSymbols ? TypeError : SyntaxError, + debug(nonSymbol) + ' is not a Symbol' + ); + }); + + t.test('with symbols', { skip: !v.hasSymbols }, function (st) { + forEach( + [ + [Symbol(), undefined], + [Symbol(undefined), undefined], + [Symbol(null), 'null'], + [Symbol.iterator, 'Symbol.iterator'], + [Symbol('foo'), 'foo'] + ], + function (pair) { + var sym = pair[0]; + var desc = pair[1]; + st.equal(getSymbolDescription(sym), desc, debug(sym) + ' description is ' + debug(desc)); + } + ); + + st.test('only possible when inference or native `Symbol.prototype.description` is supported', { + skip: !getInferredName && !has(Symbol.prototype, 'description') + }, function (s2t) { + s2t.equal(getSymbolDescription(Symbol('')), '', 'Symbol("") description is ""'); + + s2t.end(); + }); + + st.test('only possible when global symbols are supported', { + skip: !has(Symbol, 'for') || !has(Symbol, 'keyFor') + }, function (s2t) { + // eslint-disable-next-line no-restricted-properties + s2t.equal(getSymbolDescription(Symbol['for']('')), '', 'Symbol.for("") description is ""'); + s2t.end(); + }); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/glob-parent/LICENSE b/node_modules/glob-parent/LICENSE new file mode 100644 index 0000000..d701b08 --- /dev/null +++ b/node_modules/glob-parent/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015, 2019 Elan Shanker, 2021 Blaine Bublitz , Eric Schoffstall and other contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/glob-parent/README.md b/node_modules/glob-parent/README.md new file mode 100644 index 0000000..6ae18a1 --- /dev/null +++ b/node_modules/glob-parent/README.md @@ -0,0 +1,134 @@ +

+ + + +

+ +# glob-parent + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coveralls Status][coveralls-image]][coveralls-url] + +Extract the non-magic parent path from a glob string. + +## Usage + +```js +var globParent = require('glob-parent'); + +globParent('path/to/*.js'); // 'path/to' +globParent('/root/path/to/*.js'); // '/root/path/to' +globParent('/*.js'); // '/' +globParent('*.js'); // '.' +globParent('**/*.js'); // '.' +globParent('path/{to,from}'); // 'path' +globParent('path/!(to|from)'); // 'path' +globParent('path/?(to|from)'); // 'path' +globParent('path/+(to|from)'); // 'path' +globParent('path/*(to|from)'); // 'path' +globParent('path/@(to|from)'); // 'path' +globParent('path/**/*'); // 'path' + +// if provided a non-glob path, returns the nearest dir +globParent('path/foo/bar.js'); // 'path/foo' +globParent('path/foo/'); // 'path/foo' +globParent('path/foo'); // 'path' (see issue #3 for details) +``` + +## API + +### `globParent(maybeGlobString, [options])` + +Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. + +#### options + +```js +{ + // Disables the automatic conversion of slashes for Windows + flipBackslashes: true; +} +``` + +## Escaping + +The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: + +- `?` (question mark) unless used as a path segment alone +- `*` (asterisk) +- `|` (pipe) +- `(` (opening parenthesis) +- `)` (closing parenthesis) +- `{` (opening curly brace) +- `}` (closing curly brace) +- `[` (opening bracket) +- `]` (closing bracket) + +**Example** + +```js +globParent('foo/[bar]/'); // 'foo' +globParent('foo/\\[bar]/'); // 'foo/[bar]' +``` + +## Limitations + +### Braces & Brackets + +This library attempts a quick and imperfect method of determining which path +parts have glob magic without fully parsing/lexing the pattern. There are some +advanced use cases that can trip it up, such as nested braces where the outer +pair is escaped and the inner one contains a path separator. If you find +yourself in the unlikely circumstance of being affected by this or need to +ensure higher-fidelity glob handling in your library, it is recommended that you +pre-process your input with [expand-braces] and/or [expand-brackets]. + +### Windows + +Backslashes are not valid path separators for globs. If a path with backslashes +is provided anyway, for simple cases, glob-parent will replace the path +separator for you and return the non-glob parent path (now with +forward-slashes, which are still valid as Windows path separators). + +This cannot be used in conjunction with escape characters. + +```js +// BAD +globParent('C:\\Program Files \\(x86\\)\\*.ext'); // 'C:/Program Files /(x86/)' + +// GOOD +globParent('C:/Program Files\\(x86\\)/*.ext'); // 'C:/Program Files (x86)' +``` + +If you are using escape characters for a pattern without path parts (i.e. +relative to `cwd`), prefix with `./` to avoid confusing glob-parent. + +```js +// BAD +globParent('foo \\[bar]'); // 'foo ' +globParent('foo \\[bar]*'); // 'foo ' + +// GOOD +globParent('./foo \\[bar]'); // 'foo [bar]' +globParent('./foo \\[bar]*'); // '.' +``` + +## License + +ISC + + +[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg?style=flat-square +[npm-url]: https://www.npmjs.com/package/glob-parent +[npm-image]: https://img.shields.io/npm/v/glob-parent.svg?style=flat-square + +[ci-url]: https://github.com/gulpjs/glob-parent/actions?query=workflow:dev +[ci-image]: https://img.shields.io/github/workflow/status/gulpjs/glob-parent/dev?style=flat-square + +[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent +[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg?style=flat-square + + + +[expand-braces]: https://github.com/jonschlinkert/expand-braces +[expand-brackets]: https://github.com/jonschlinkert/expand-brackets + diff --git a/node_modules/glob-parent/index.js b/node_modules/glob-parent/index.js new file mode 100644 index 0000000..09dde64 --- /dev/null +++ b/node_modules/glob-parent/index.js @@ -0,0 +1,75 @@ +'use strict'; + +var isGlob = require('is-glob'); +var pathPosixDirname = require('path').posix.dirname; +var isWin32 = require('os').platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var escaped = /\\([!*?|[\](){}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (isEnclosure(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlobby(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +function isEnclosure(str) { + var lastChar = str.slice(-1); + + var enclosureStart; + switch (lastChar) { + case '}': + enclosureStart = '{'; + break; + case ']': + enclosureStart = '['; + break; + default: + return false; + } + + var foundIndex = str.indexOf(enclosureStart); + if (foundIndex < 0) { + return false; + } + + return str.slice(foundIndex + 1, -1).includes(slash); +} + +function isGlobby(str) { + if (/\([^()]+$/.test(str)) { + return true; + } + if (str[0] === '{' || str[0] === '[') { + return true; + } + if (/[^\\][{[]/.test(str)) { + return true; + } + return isGlob(str); +} diff --git a/node_modules/glob-parent/package.json b/node_modules/glob-parent/package.json new file mode 100644 index 0000000..baeab42 --- /dev/null +++ b/node_modules/glob-parent/package.json @@ -0,0 +1,54 @@ +{ + "name": "glob-parent", + "version": "6.0.2", + "description": "Extract the non-magic parent path from a glob string.", + "author": "Gulp Team (https://gulpjs.com/)", + "contributors": [ + "Elan Shanker (https://github.com/es128)", + "Blaine Bublitz " + ], + "repository": "gulpjs/glob-parent", + "license": "ISC", + "engines": { + "node": ">=10.13.0" + }, + "main": "index.js", + "files": [ + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "nyc mocha --async-only" + }, + "dependencies": { + "is-glob": "^4.0.3" + }, + "devDependencies": { + "eslint": "^7.0.0", + "eslint-config-gulp": "^5.0.0", + "expect": "^26.0.1", + "mocha": "^7.1.2", + "nyc": "^15.0.1" + }, + "nyc": { + "reporter": [ + "lcov", + "text-summary" + ] + }, + "prettier": { + "singleQuote": true + }, + "keywords": [ + "glob", + "parent", + "strip", + "path", + "dirname", + "directory", + "base", + "wildcard" + ] +} diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE new file mode 100644 index 0000000..42ca266 --- /dev/null +++ b/node_modules/glob/LICENSE @@ -0,0 +1,21 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +## Glob Logo + +Glob's logo created by Tanya Brassie , licensed +under a Creative Commons Attribution-ShareAlike 4.0 International License +https://creativecommons.org/licenses/by-sa/4.0/ diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md new file mode 100644 index 0000000..83f0c83 --- /dev/null +++ b/node_modules/glob/README.md @@ -0,0 +1,378 @@ +# Glob + +Match files using the patterns the shell uses, like stars and stuff. + +[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) + +This is a glob implementation in JavaScript. It uses the `minimatch` +library to do its matching. + +![a fun cartoon logo made of glob characters](logo/glob.png) + +## Usage + +Install with npm + +``` +npm i glob +``` + +```javascript +var glob = require("glob") + +// options is optional +glob("**/*.js", options, function (er, files) { + // files is an array of filenames. + // If the `nonull` option is set, and nothing + // was found, then files is ["**/*.js"] + // er is an error object or null. +}) +``` + +## Glob Primer + +"Globs" are the patterns you type when you do stuff like `ls *.js` on +the command line, or put `build/*` in a `.gitignore` file. + +Before parsing the path part patterns, braced sections are expanded +into a set. Braced sections start with `{` and end with `}`, with any +number of comma-delimited sections within. Braced sections may contain +slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. + +The following characters have special magic meaning when used in a +path portion: + +* `*` Matches 0 or more characters in a single path portion +* `?` Matches 1 character +* `[...]` Matches a range of characters, similar to a RegExp range. + If the first character of the range is `!` or `^` then it matches + any character not in the range. +* `!(pattern|pattern|pattern)` Matches anything that does not match + any of the patterns provided. +* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the + patterns provided. +* `+(pattern|pattern|pattern)` Matches one or more occurrences of the + patterns provided. +* `*(a|b|c)` Matches zero or more occurrences of the patterns provided +* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns + provided +* `**` If a "globstar" is alone in a path portion, then it matches + zero or more directories and subdirectories searching for matches. + It does not crawl symlinked directories. + +### Dots + +If a file or directory path portion has a `.` as the first character, +then it will not match any glob pattern unless that pattern's +corresponding path part also has a `.` as its first character. + +For example, the pattern `a/.*/c` would match the file at `a/.b/c`. +However the pattern `a/*/c` would not, because `*` does not start with +a dot character. + +You can make glob treat dots as normal characters by setting +`dot:true` in the options. + +### Basename Matching + +If you set `matchBase:true` in the options, and the pattern has no +slashes in it, then it will seek for any file anywhere in the tree +with a matching basename. For example, `*.js` would match +`test/simple/basic.js`. + +### Empty Sets + +If no matching files are found, then an empty array is returned. This +differs from the shell, where the pattern itself is returned. For +example: + + $ echo a*s*d*f + a*s*d*f + +To get the bash-style behavior, set the `nonull:true` in the options. + +### See Also: + +* `man sh` +* `man bash` (Search for "Pattern Matching") +* `man 3 fnmatch` +* `man 5 gitignore` +* [minimatch documentation](https://github.com/isaacs/minimatch) + +## glob.hasMagic(pattern, [options]) + +Returns `true` if there are any special characters in the pattern, and +`false` otherwise. + +Note that the options affect the results. If `noext:true` is set in +the options object, then `+(a|b)` will not be considered a magic +pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` +then that is considered magical, unless `nobrace:true` is set in the +options. + +## glob(pattern, [options], cb) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* `cb` `{Function}` + * `err` `{Error | null}` + * `matches` `{Array}` filenames found matching the pattern + +Perform an asynchronous glob search. + +## glob.sync(pattern, [options]) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* return: `{Array}` filenames found matching the pattern + +Perform a synchronous glob search. + +## Class: glob.Glob + +Create a Glob object by instantiating the `glob.Glob` class. + +```javascript +var Glob = require("glob").Glob +var mg = new Glob(pattern, options, cb) +``` + +It's an EventEmitter, and starts walking the filesystem to find matches +immediately. + +### new glob.Glob(pattern, [options], [cb]) + +* `pattern` `{String}` pattern to search for +* `options` `{Object}` +* `cb` `{Function}` Called when an error occurs, or matches are found + * `err` `{Error | null}` + * `matches` `{Array}` filenames found matching the pattern + +Note that if the `sync` flag is set in the options, then matches will +be immediately available on the `g.found` member. + +### Properties + +* `minimatch` The minimatch object that the glob uses. +* `options` The options object passed in. +* `aborted` Boolean which is set to true when calling `abort()`. There + is no way at this time to continue a glob search after aborting, but + you can re-use the statCache to avoid having to duplicate syscalls. +* `cache` Convenience object. Each field has the following possible + values: + * `false` - Path does not exist + * `true` - Path exists + * `'FILE'` - Path exists, and is not a directory + * `'DIR'` - Path exists, and is a directory + * `[file, entries, ...]` - Path exists, is a directory, and the + array value is the results of `fs.readdir` +* `statCache` Cache of `fs.stat` results, to prevent statting the same + path multiple times. +* `symlinks` A record of which paths are symbolic links, which is + relevant in resolving `**` patterns. +* `realpathCache` An optional object which is passed to `fs.realpath` + to minimize unnecessary syscalls. It is stored on the instantiated + Glob object, and may be re-used. + +### Events + +* `end` When the matching is finished, this is emitted with all the + matches found. If the `nonull` option is set, and no match was found, + then the `matches` list contains the original pattern. The matches + are sorted, unless the `nosort` flag is set. +* `match` Every time a match is found, this is emitted with the specific + thing that matched. It is not deduplicated or resolved to a realpath. +* `error` Emitted when an unexpected error is encountered, or whenever + any fs error occurs if `options.strict` is set. +* `abort` When `abort()` is called, this event is raised. + +### Methods + +* `pause` Temporarily stop the search +* `resume` Resume the search +* `abort` Stop the search forever + +### Options + +All the options that can be passed to Minimatch can also be passed to +Glob to change pattern matching behavior. Also, some have been added, +or have glob-specific ramifications. + +All options are false by default, unless otherwise noted. + +All options are added to the Glob object, as well. + +If you are running many `glob` operations, you can pass a Glob object +as the `options` argument to a subsequent operation to shortcut some +`stat` and `readdir` calls. At the very least, you may pass in shared +`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that +parallel glob operations will be sped up by sharing information about +the filesystem. + +* `cwd` The current working directory in which to search. Defaults + to `process.cwd()`. +* `root` The place where patterns starting with `/` will be mounted + onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix + systems, and `C:\` or some such on Windows.) +* `dot` Include `.dot` files in normal matches and `globstar` matches. + Note that an explicit dot in a portion of the pattern will always + match dot files. +* `nomount` By default, a pattern starting with a forward-slash will be + "mounted" onto the root setting, so that a valid filesystem path is + returned. Set this flag to disable that behavior. +* `mark` Add a `/` character to directory matches. Note that this + requires additional stat calls. +* `nosort` Don't sort the results. +* `stat` Set to true to stat *all* results. This reduces performance + somewhat, and is completely unnecessary, unless `readdir` is presumed + to be an untrustworthy indicator of file existence. +* `silent` When an unusual error is encountered when attempting to + read a directory, a warning will be printed to stderr. Set the + `silent` option to true to suppress these warnings. +* `strict` When an unusual error is encountered when attempting to + read a directory, the process will just continue on in search of + other matches. Set the `strict` option to raise an error in these + cases. +* `cache` See `cache` property above. Pass in a previously generated + cache object to save some fs calls. +* `statCache` A cache of results of filesystem information, to prevent + unnecessary stat calls. While it should not normally be necessary + to set this, you may pass the statCache from one glob() call to the + options object of another, if you know that the filesystem will not + change between calls. (See "Race Conditions" below.) +* `symlinks` A cache of known symbolic links. You may pass in a + previously generated `symlinks` object to save `lstat` calls when + resolving `**` matches. +* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. +* `nounique` In some cases, brace-expanded patterns can result in the + same file showing up multiple times in the result set. By default, + this implementation prevents duplicates in the result set. Set this + flag to disable that behavior. +* `nonull` Set to never return an empty set, instead returning a set + containing the pattern itself. This is the default in glob(3). +* `debug` Set to enable debug logging in minimatch and glob. +* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. +* `noglobstar` Do not match `**` against multiple filenames. (Ie, + treat it as a normal `*` instead.) +* `noext` Do not match `+(a|b)` "extglob" patterns. +* `nocase` Perform a case-insensitive match. Note: on + case-insensitive filesystems, non-magic patterns will match by + default, since `stat` and `readdir` will not raise errors. +* `matchBase` Perform a basename-only match if the pattern does not + contain any slash characters. That is, `*.js` would be treated as + equivalent to `**/*.js`, matching all js files in all directories. +* `nodir` Do not match directories, only files. (Note: to match + *only* directories, simply put a `/` at the end of the pattern.) +* `ignore` Add a pattern or an array of glob patterns to exclude matches. + Note: `ignore` patterns are *always* in `dot:true` mode, regardless + of any other settings. +* `follow` Follow symlinked directories when expanding `**` patterns. + Note that this can result in a lot of duplicate references in the + presence of cyclic links. +* `realpath` Set to true to call `fs.realpath` on all of the results. + In the case of a symlink that cannot be resolved, the full absolute + path to the matched entry is returned (though it will usually be a + broken symlink) +* `absolute` Set to true to always receive absolute paths for matched + files. Unlike `realpath`, this also affects the values returned in + the `match` event. +* `fs` File-system object with Node's `fs` API. By default, the built-in + `fs` module will be used. Set to a volume provided by a library like + `memfs` to avoid using the "real" file-system. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between node-glob and other +implementations, and are intentional. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.3, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +Note that symlinked directories are not crawled as part of a `**`, +though their contents may match against subsequent portions of the +pattern. This prevents infinite loops and duplicates and the like. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then glob returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +### Comments and Negation + +Previously, this module let you mark a pattern as a "comment" if it +started with a `#` character, or a "negated" pattern if it started +with a `!` character. + +These options were deprecated in version 5, and removed in version 6. + +To specify things that should not match, use the `ignore` option. + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes will always +be interpreted as escape characters, not path separators. + +Results from absolute patterns such as `/foo/*` are mounted onto the +root setting using `path.join`. On windows, this will by default result +in `/foo/*` matching `C:\foo\bar.txt`. + +## Race Conditions + +Glob searching, by its very nature, is susceptible to race conditions, +since it relies on directory walking and such. + +As a result, it is possible that a file that exists when glob looks for +it may have been deleted or modified by the time it returns the result. + +As part of its internal implementation, this program caches all stat +and readdir calls that it makes, in order to cut down on system +overhead. However, this also makes it even more susceptible to races, +especially if the cache or statCache objects are reused between glob +calls. + +Users are thus advised not to use a glob result as a guarantee of +filesystem state in the face of rapid changes. For the vast majority +of operations, this is never a problem. + +## Glob Logo +Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). + +The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). + +## Contributing + +Any change to behavior (including bugfixes) must come with a test. + +Patches that fail tests or reduce performance will be rejected. + +``` +# to run tests +npm test + +# to re-generate test fixtures +npm run test-regen + +# to benchmark against bash/zsh +npm run bench + +# to profile javascript +npm run prof +``` + +![](oh-my-glob.gif) diff --git a/node_modules/glob/common.js b/node_modules/glob/common.js new file mode 100644 index 0000000..424c46e --- /dev/null +++ b/node_modules/glob/common.js @@ -0,0 +1,238 @@ +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var fs = require("fs") +var path = require("path") +var minimatch = require("minimatch") +var isAbsolute = require("path-is-absolute") +var Minimatch = minimatch.Minimatch + +function alphasort (a, b) { + return a.localeCompare(b, 'en') +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {} + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + self.fs = options.fs || fs + + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) + + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } + + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + // always treat \ in patterns as escapes, not path separators + options.allowWindowsEscape = false + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } + + if (!nou) + all = Object.keys(all) + + if (!self.nosort) + all = all.sort(alphasort) + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) + + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} diff --git a/node_modules/glob/glob.js b/node_modules/glob/glob.js new file mode 100644 index 0000000..37a4d7e --- /dev/null +++ b/node_modules/glob/glob.js @@ -0,0 +1,790 @@ +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +module.exports = glob + +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var inherits = require('inherits') +var EE = require('events').EventEmitter +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var globSync = require('./sync.js') +var common = require('./common.js') +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = require('inflight') +var util = require('util') +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +var once = require('once') + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync + +// old api surface +glob.glob = glob + +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true + + var g = new Glob(pattern, options) + var set = g.minimatch.set + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +} + +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + this._processing = 0 + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false + + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this) + this.emit('end', this.found) +} + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true + + var n = this.matches.length + if (n === 0) + return this._finish() + + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } +} + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) + e = abs + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) +} + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) + + if (lstatcb) + self.fs.lstat(abs, lstatcb) + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this + self.fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) +} + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } + + return cb() +} + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) + + var isSym = this.symlinks[abs] + var len = entries.length + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() +} + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + self.fs.lstat(abs, statcb) + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return self.fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } + + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +} diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json new file mode 100644 index 0000000..5940b64 --- /dev/null +++ b/node_modules/glob/package.json @@ -0,0 +1,55 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "glob", + "description": "a little globber", + "version": "7.2.3", + "publishConfig": { + "tag": "v7-legacy" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" + }, + "main": "glob.js", + "files": [ + "glob.js", + "sync.js", + "common.js" + ], + "engines": { + "node": "*" + }, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "devDependencies": { + "memfs": "^3.2.0", + "mkdirp": "0", + "rimraf": "^2.2.8", + "tap": "^15.0.6", + "tick": "0.0.6" + }, + "tap": { + "before": "test/00-setup.js", + "after": "test/zz-cleanup.js", + "jobs": 1 + }, + "scripts": { + "prepublish": "npm run benchclean", + "profclean": "rm -f v8.log profile.txt", + "test": "tap", + "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js", + "bench": "bash benchmark.sh", + "prof": "bash prof.sh && cat profile.txt", + "benchclean": "node benchclean.js" + }, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } +} diff --git a/node_modules/glob/sync.js b/node_modules/glob/sync.js new file mode 100644 index 0000000..2c4f480 --- /dev/null +++ b/node_modules/glob/sync.js @@ -0,0 +1,486 @@ +module.exports = globSync +globSync.GlobSync = GlobSync + +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var Glob = require('./glob.js').Glob +var util = require('util') +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var common = require('./common.js') +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert.ok(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert.ok(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, this.fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = this.fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} diff --git a/node_modules/globals/globals.json b/node_modules/globals/globals.json new file mode 100644 index 0000000..76af3e3 --- /dev/null +++ b/node_modules/globals/globals.json @@ -0,0 +1,1972 @@ +{ + "builtin": { + "AggregateError": false, + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "FinalizationRegistry": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakRef": false, + "WeakSet": false + }, + "es5": { + "Array": false, + "Boolean": false, + "constructor": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "propertyIsEnumerable": false, + "RangeError": false, + "ReferenceError": false, + "RegExp": false, + "String": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false + }, + "es2015": { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2017": { + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2020": { + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2021": { + "AggregateError": false, + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "FinalizationRegistry": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakRef": false, + "WeakSet": false + }, + "browser": { + "AbortController": false, + "AbortSignal": false, + "addEventListener": false, + "alert": false, + "AnalyserNode": false, + "Animation": false, + "AnimationEffectReadOnly": false, + "AnimationEffectTiming": false, + "AnimationEffectTimingReadOnly": false, + "AnimationEvent": false, + "AnimationPlaybackEvent": false, + "AnimationTimeline": false, + "applicationCache": false, + "ApplicationCache": false, + "ApplicationCacheErrorEvent": false, + "atob": false, + "Attr": false, + "Audio": false, + "AudioBuffer": false, + "AudioBufferSourceNode": false, + "AudioContext": false, + "AudioDestinationNode": false, + "AudioListener": false, + "AudioNode": false, + "AudioParam": false, + "AudioProcessingEvent": false, + "AudioScheduledSourceNode": false, + "AudioWorkletGlobalScope": false, + "AudioWorkletNode": false, + "AudioWorkletProcessor": false, + "BarProp": false, + "BaseAudioContext": false, + "BatteryManager": false, + "BeforeUnloadEvent": false, + "BiquadFilterNode": false, + "Blob": false, + "BlobEvent": false, + "blur": false, + "BroadcastChannel": false, + "btoa": false, + "BudgetService": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "CacheStorage": false, + "cancelAnimationFrame": false, + "cancelIdleCallback": false, + "CanvasCaptureMediaStreamTrack": false, + "CanvasGradient": false, + "CanvasPattern": false, + "CanvasRenderingContext2D": false, + "ChannelMergerNode": false, + "ChannelSplitterNode": false, + "CharacterData": false, + "clearInterval": false, + "clearTimeout": false, + "clientInformation": false, + "ClipboardEvent": false, + "ClipboardItem": false, + "close": false, + "closed": false, + "CloseEvent": false, + "Comment": false, + "CompositionEvent": false, + "CompressionStream": false, + "confirm": false, + "console": false, + "ConstantSourceNode": false, + "ConvolverNode": false, + "CountQueuingStrategy": false, + "createImageBitmap": false, + "Credential": false, + "CredentialsContainer": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CSS": false, + "CSSConditionRule": false, + "CSSFontFaceRule": false, + "CSSGroupingRule": false, + "CSSImportRule": false, + "CSSKeyframeRule": false, + "CSSKeyframesRule": false, + "CSSMatrixComponent": false, + "CSSMediaRule": false, + "CSSNamespaceRule": false, + "CSSPageRule": false, + "CSSPerspective": false, + "CSSRotate": false, + "CSSRule": false, + "CSSRuleList": false, + "CSSScale": false, + "CSSSkew": false, + "CSSSkewX": false, + "CSSSkewY": false, + "CSSStyleDeclaration": false, + "CSSStyleRule": false, + "CSSStyleSheet": false, + "CSSSupportsRule": false, + "CSSTransformValue": false, + "CSSTranslate": false, + "CustomElementRegistry": false, + "customElements": false, + "CustomEvent": false, + "DataTransfer": false, + "DataTransferItem": false, + "DataTransferItemList": false, + "DecompressionStream": false, + "defaultstatus": false, + "defaultStatus": false, + "DelayNode": false, + "DeviceMotionEvent": false, + "DeviceOrientationEvent": false, + "devicePixelRatio": false, + "dispatchEvent": false, + "document": false, + "Document": false, + "DocumentFragment": false, + "DocumentType": false, + "DOMError": false, + "DOMException": false, + "DOMImplementation": false, + "DOMMatrix": false, + "DOMMatrixReadOnly": false, + "DOMParser": false, + "DOMPoint": false, + "DOMPointReadOnly": false, + "DOMQuad": false, + "DOMRect": false, + "DOMRectList": false, + "DOMRectReadOnly": false, + "DOMStringList": false, + "DOMStringMap": false, + "DOMTokenList": false, + "DragEvent": false, + "DynamicsCompressorNode": false, + "Element": false, + "ErrorEvent": false, + "event": false, + "Event": false, + "EventSource": false, + "EventTarget": false, + "external": false, + "fetch": false, + "File": false, + "FileList": false, + "FileReader": false, + "find": false, + "focus": false, + "FocusEvent": false, + "FontFace": false, + "FontFaceSetLoadEvent": false, + "FormData": false, + "FormDataEvent": false, + "frameElement": false, + "frames": false, + "GainNode": false, + "Gamepad": false, + "GamepadButton": false, + "GamepadEvent": false, + "getComputedStyle": false, + "getSelection": false, + "HashChangeEvent": false, + "Headers": false, + "history": false, + "History": false, + "HTMLAllCollection": false, + "HTMLAnchorElement": false, + "HTMLAreaElement": false, + "HTMLAudioElement": false, + "HTMLBaseElement": false, + "HTMLBodyElement": false, + "HTMLBRElement": false, + "HTMLButtonElement": false, + "HTMLCanvasElement": false, + "HTMLCollection": false, + "HTMLContentElement": false, + "HTMLDataElement": false, + "HTMLDataListElement": false, + "HTMLDetailsElement": false, + "HTMLDialogElement": false, + "HTMLDirectoryElement": false, + "HTMLDivElement": false, + "HTMLDListElement": false, + "HTMLDocument": false, + "HTMLElement": false, + "HTMLEmbedElement": false, + "HTMLFieldSetElement": false, + "HTMLFontElement": false, + "HTMLFormControlsCollection": false, + "HTMLFormElement": false, + "HTMLFrameElement": false, + "HTMLFrameSetElement": false, + "HTMLHeadElement": false, + "HTMLHeadingElement": false, + "HTMLHRElement": false, + "HTMLHtmlElement": false, + "HTMLIFrameElement": false, + "HTMLImageElement": false, + "HTMLInputElement": false, + "HTMLLabelElement": false, + "HTMLLegendElement": false, + "HTMLLIElement": false, + "HTMLLinkElement": false, + "HTMLMapElement": false, + "HTMLMarqueeElement": false, + "HTMLMediaElement": false, + "HTMLMenuElement": false, + "HTMLMetaElement": false, + "HTMLMeterElement": false, + "HTMLModElement": false, + "HTMLObjectElement": false, + "HTMLOListElement": false, + "HTMLOptGroupElement": false, + "HTMLOptionElement": false, + "HTMLOptionsCollection": false, + "HTMLOutputElement": false, + "HTMLParagraphElement": false, + "HTMLParamElement": false, + "HTMLPictureElement": false, + "HTMLPreElement": false, + "HTMLProgressElement": false, + "HTMLQuoteElement": false, + "HTMLScriptElement": false, + "HTMLSelectElement": false, + "HTMLShadowElement": false, + "HTMLSlotElement": false, + "HTMLSourceElement": false, + "HTMLSpanElement": false, + "HTMLStyleElement": false, + "HTMLTableCaptionElement": false, + "HTMLTableCellElement": false, + "HTMLTableColElement": false, + "HTMLTableElement": false, + "HTMLTableRowElement": false, + "HTMLTableSectionElement": false, + "HTMLTemplateElement": false, + "HTMLTextAreaElement": false, + "HTMLTimeElement": false, + "HTMLTitleElement": false, + "HTMLTrackElement": false, + "HTMLUListElement": false, + "HTMLUnknownElement": false, + "HTMLVideoElement": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "IdleDeadline": false, + "IIRFilterNode": false, + "Image": false, + "ImageBitmap": false, + "ImageBitmapRenderingContext": false, + "ImageCapture": false, + "ImageData": false, + "indexedDB": false, + "innerHeight": false, + "innerWidth": false, + "InputEvent": false, + "IntersectionObserver": false, + "IntersectionObserverEntry": false, + "Intl": false, + "isSecureContext": false, + "KeyboardEvent": false, + "KeyframeEffect": false, + "KeyframeEffectReadOnly": false, + "length": false, + "localStorage": false, + "location": true, + "Location": false, + "locationbar": false, + "matchMedia": false, + "MediaDeviceInfo": false, + "MediaDevices": false, + "MediaElementAudioSourceNode": false, + "MediaEncryptedEvent": false, + "MediaError": false, + "MediaKeyMessageEvent": false, + "MediaKeySession": false, + "MediaKeyStatusMap": false, + "MediaKeySystemAccess": false, + "MediaList": false, + "MediaMetadata": false, + "MediaQueryList": false, + "MediaQueryListEvent": false, + "MediaRecorder": false, + "MediaSettingsRange": false, + "MediaSource": false, + "MediaStream": false, + "MediaStreamAudioDestinationNode": false, + "MediaStreamAudioSourceNode": false, + "MediaStreamEvent": false, + "MediaStreamTrack": false, + "MediaStreamTrackEvent": false, + "menubar": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "MIDIAccess": false, + "MIDIConnectionEvent": false, + "MIDIInput": false, + "MIDIInputMap": false, + "MIDIMessageEvent": false, + "MIDIOutput": false, + "MIDIOutputMap": false, + "MIDIPort": false, + "MimeType": false, + "MimeTypeArray": false, + "MouseEvent": false, + "moveBy": false, + "moveTo": false, + "MutationEvent": false, + "MutationObserver": false, + "MutationRecord": false, + "name": false, + "NamedNodeMap": false, + "NavigationPreloadManager": false, + "navigator": false, + "Navigator": false, + "NavigatorUAData": false, + "NetworkInformation": false, + "Node": false, + "NodeFilter": false, + "NodeIterator": false, + "NodeList": false, + "Notification": false, + "OfflineAudioCompletionEvent": false, + "OfflineAudioContext": false, + "offscreenBuffering": false, + "OffscreenCanvas": true, + "OffscreenCanvasRenderingContext2D": false, + "onabort": true, + "onafterprint": true, + "onanimationend": true, + "onanimationiteration": true, + "onanimationstart": true, + "onappinstalled": true, + "onauxclick": true, + "onbeforeinstallprompt": true, + "onbeforeprint": true, + "onbeforeunload": true, + "onblur": true, + "oncancel": true, + "oncanplay": true, + "oncanplaythrough": true, + "onchange": true, + "onclick": true, + "onclose": true, + "oncontextmenu": true, + "oncuechange": true, + "ondblclick": true, + "ondevicemotion": true, + "ondeviceorientation": true, + "ondeviceorientationabsolute": true, + "ondrag": true, + "ondragend": true, + "ondragenter": true, + "ondragleave": true, + "ondragover": true, + "ondragstart": true, + "ondrop": true, + "ondurationchange": true, + "onemptied": true, + "onended": true, + "onerror": true, + "onfocus": true, + "ongotpointercapture": true, + "onhashchange": true, + "oninput": true, + "oninvalid": true, + "onkeydown": true, + "onkeypress": true, + "onkeyup": true, + "onlanguagechange": true, + "onload": true, + "onloadeddata": true, + "onloadedmetadata": true, + "onloadstart": true, + "onlostpointercapture": true, + "onmessage": true, + "onmessageerror": true, + "onmousedown": true, + "onmouseenter": true, + "onmouseleave": true, + "onmousemove": true, + "onmouseout": true, + "onmouseover": true, + "onmouseup": true, + "onmousewheel": true, + "onoffline": true, + "ononline": true, + "onpagehide": true, + "onpageshow": true, + "onpause": true, + "onplay": true, + "onplaying": true, + "onpointercancel": true, + "onpointerdown": true, + "onpointerenter": true, + "onpointerleave": true, + "onpointermove": true, + "onpointerout": true, + "onpointerover": true, + "onpointerup": true, + "onpopstate": true, + "onprogress": true, + "onratechange": true, + "onrejectionhandled": true, + "onreset": true, + "onresize": true, + "onscroll": true, + "onsearch": true, + "onseeked": true, + "onseeking": true, + "onselect": true, + "onstalled": true, + "onstorage": true, + "onsubmit": true, + "onsuspend": true, + "ontimeupdate": true, + "ontoggle": true, + "ontransitionend": true, + "onunhandledrejection": true, + "onunload": true, + "onvolumechange": true, + "onwaiting": true, + "onwheel": true, + "open": false, + "openDatabase": false, + "opener": false, + "Option": false, + "origin": false, + "OscillatorNode": false, + "outerHeight": false, + "outerWidth": false, + "OverconstrainedError": false, + "PageTransitionEvent": false, + "pageXOffset": false, + "pageYOffset": false, + "PannerNode": false, + "parent": false, + "Path2D": false, + "PaymentAddress": false, + "PaymentRequest": false, + "PaymentRequestUpdateEvent": false, + "PaymentResponse": false, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceLongTaskTiming": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceNavigationTiming": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformancePaintTiming": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "PeriodicWave": false, + "Permissions": false, + "PermissionStatus": false, + "personalbar": false, + "PhotoCapabilities": false, + "Plugin": false, + "PluginArray": false, + "PointerEvent": false, + "PopStateEvent": false, + "postMessage": false, + "Presentation": false, + "PresentationAvailability": false, + "PresentationConnection": false, + "PresentationConnectionAvailableEvent": false, + "PresentationConnectionCloseEvent": false, + "PresentationConnectionList": false, + "PresentationReceiver": false, + "PresentationRequest": false, + "print": false, + "ProcessingInstruction": false, + "ProgressEvent": false, + "PromiseRejectionEvent": false, + "prompt": false, + "PushManager": false, + "PushSubscription": false, + "PushSubscriptionOptions": false, + "queueMicrotask": false, + "RadioNodeList": false, + "Range": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "registerProcessor": false, + "RemotePlayback": false, + "removeEventListener": false, + "reportError": false, + "Request": false, + "requestAnimationFrame": false, + "requestIdleCallback": false, + "resizeBy": false, + "ResizeObserver": false, + "ResizeObserverEntry": false, + "resizeTo": false, + "Response": false, + "RTCCertificate": false, + "RTCDataChannel": false, + "RTCDataChannelEvent": false, + "RTCDtlsTransport": false, + "RTCIceCandidate": false, + "RTCIceGatherer": false, + "RTCIceTransport": false, + "RTCPeerConnection": false, + "RTCPeerConnectionIceEvent": false, + "RTCRtpContributingSource": false, + "RTCRtpReceiver": false, + "RTCRtpSender": false, + "RTCSctpTransport": false, + "RTCSessionDescription": false, + "RTCStatsReport": false, + "RTCTrackEvent": false, + "screen": false, + "Screen": false, + "screenLeft": false, + "ScreenOrientation": false, + "screenTop": false, + "screenX": false, + "screenY": false, + "ScriptProcessorNode": false, + "scroll": false, + "scrollbars": false, + "scrollBy": false, + "scrollTo": false, + "scrollX": false, + "scrollY": false, + "SecurityPolicyViolationEvent": false, + "Selection": false, + "self": false, + "ServiceWorker": false, + "ServiceWorkerContainer": false, + "ServiceWorkerRegistration": false, + "sessionStorage": false, + "setInterval": false, + "setTimeout": false, + "ShadowRoot": false, + "SharedWorker": false, + "SourceBuffer": false, + "SourceBufferList": false, + "speechSynthesis": false, + "SpeechSynthesisEvent": false, + "SpeechSynthesisUtterance": false, + "StaticRange": false, + "status": false, + "statusbar": false, + "StereoPannerNode": false, + "stop": false, + "Storage": false, + "StorageEvent": false, + "StorageManager": false, + "structuredClone": false, + "styleMedia": false, + "StyleSheet": false, + "StyleSheetList": false, + "SubmitEvent": false, + "SubtleCrypto": false, + "SVGAElement": false, + "SVGAngle": false, + "SVGAnimatedAngle": false, + "SVGAnimatedBoolean": false, + "SVGAnimatedEnumeration": false, + "SVGAnimatedInteger": false, + "SVGAnimatedLength": false, + "SVGAnimatedLengthList": false, + "SVGAnimatedNumber": false, + "SVGAnimatedNumberList": false, + "SVGAnimatedPreserveAspectRatio": false, + "SVGAnimatedRect": false, + "SVGAnimatedString": false, + "SVGAnimatedTransformList": false, + "SVGAnimateElement": false, + "SVGAnimateMotionElement": false, + "SVGAnimateTransformElement": false, + "SVGAnimationElement": false, + "SVGCircleElement": false, + "SVGClipPathElement": false, + "SVGComponentTransferFunctionElement": false, + "SVGDefsElement": false, + "SVGDescElement": false, + "SVGDiscardElement": false, + "SVGElement": false, + "SVGEllipseElement": false, + "SVGFEBlendElement": false, + "SVGFEColorMatrixElement": false, + "SVGFEComponentTransferElement": false, + "SVGFECompositeElement": false, + "SVGFEConvolveMatrixElement": false, + "SVGFEDiffuseLightingElement": false, + "SVGFEDisplacementMapElement": false, + "SVGFEDistantLightElement": false, + "SVGFEDropShadowElement": false, + "SVGFEFloodElement": false, + "SVGFEFuncAElement": false, + "SVGFEFuncBElement": false, + "SVGFEFuncGElement": false, + "SVGFEFuncRElement": false, + "SVGFEGaussianBlurElement": false, + "SVGFEImageElement": false, + "SVGFEMergeElement": false, + "SVGFEMergeNodeElement": false, + "SVGFEMorphologyElement": false, + "SVGFEOffsetElement": false, + "SVGFEPointLightElement": false, + "SVGFESpecularLightingElement": false, + "SVGFESpotLightElement": false, + "SVGFETileElement": false, + "SVGFETurbulenceElement": false, + "SVGFilterElement": false, + "SVGForeignObjectElement": false, + "SVGGElement": false, + "SVGGeometryElement": false, + "SVGGradientElement": false, + "SVGGraphicsElement": false, + "SVGImageElement": false, + "SVGLength": false, + "SVGLengthList": false, + "SVGLinearGradientElement": false, + "SVGLineElement": false, + "SVGMarkerElement": false, + "SVGMaskElement": false, + "SVGMatrix": false, + "SVGMetadataElement": false, + "SVGMPathElement": false, + "SVGNumber": false, + "SVGNumberList": false, + "SVGPathElement": false, + "SVGPatternElement": false, + "SVGPoint": false, + "SVGPointList": false, + "SVGPolygonElement": false, + "SVGPolylineElement": false, + "SVGPreserveAspectRatio": false, + "SVGRadialGradientElement": false, + "SVGRect": false, + "SVGRectElement": false, + "SVGScriptElement": false, + "SVGSetElement": false, + "SVGStopElement": false, + "SVGStringList": false, + "SVGStyleElement": false, + "SVGSVGElement": false, + "SVGSwitchElement": false, + "SVGSymbolElement": false, + "SVGTextContentElement": false, + "SVGTextElement": false, + "SVGTextPathElement": false, + "SVGTextPositioningElement": false, + "SVGTitleElement": false, + "SVGTransform": false, + "SVGTransformList": false, + "SVGTSpanElement": false, + "SVGUnitTypes": false, + "SVGUseElement": false, + "SVGViewElement": false, + "TaskAttributionTiming": false, + "Text": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TextEvent": false, + "TextMetrics": false, + "TextTrack": false, + "TextTrackCue": false, + "TextTrackCueList": false, + "TextTrackList": false, + "TimeRanges": false, + "toolbar": false, + "top": false, + "Touch": false, + "TouchEvent": false, + "TouchList": false, + "TrackEvent": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "TransitionEvent": false, + "TreeWalker": false, + "UIEvent": false, + "URL": false, + "URLSearchParams": false, + "ValidityState": false, + "visualViewport": false, + "VisualViewport": false, + "VTTCue": false, + "WaveShaperNode": false, + "WebAssembly": false, + "WebGL2RenderingContext": false, + "WebGLActiveInfo": false, + "WebGLBuffer": false, + "WebGLContextEvent": false, + "WebGLFramebuffer": false, + "WebGLProgram": false, + "WebGLQuery": false, + "WebGLRenderbuffer": false, + "WebGLRenderingContext": false, + "WebGLSampler": false, + "WebGLShader": false, + "WebGLShaderPrecisionFormat": false, + "WebGLSync": false, + "WebGLTexture": false, + "WebGLTransformFeedback": false, + "WebGLUniformLocation": false, + "WebGLVertexArrayObject": false, + "WebSocket": false, + "WheelEvent": false, + "window": false, + "Window": false, + "Worker": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLDocument": false, + "XMLHttpRequest": false, + "XMLHttpRequestEventTarget": false, + "XMLHttpRequestUpload": false, + "XMLSerializer": false, + "XPathEvaluator": false, + "XPathExpression": false, + "XPathResult": false, + "XSLTProcessor": false + }, + "worker": { + "addEventListener": false, + "applicationCache": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "clearInterval": false, + "clearTimeout": false, + "close": true, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "ErrorEvent": false, + "Event": false, + "fetch": false, + "File": false, + "FileReaderSync": false, + "FormData": false, + "Headers": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "ImageData": false, + "importScripts": true, + "indexedDB": false, + "location": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "name": false, + "navigator": false, + "Notification": false, + "onclose": true, + "onconnect": true, + "onerror": true, + "onlanguagechange": true, + "onmessage": true, + "onoffline": true, + "ononline": true, + "onrejectionhandled": true, + "onunhandledrejection": true, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "postMessage": true, + "Promise": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "removeEventListener": false, + "reportError": false, + "Request": false, + "Response": false, + "self": true, + "ServiceWorkerRegistration": false, + "setInterval": false, + "setTimeout": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WebSocket": false, + "Worker": false, + "WorkerGlobalScope": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLHttpRequest": false + }, + "node": { + "__dirname": false, + "__filename": false, + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "Buffer": false, + "ByteLengthQueuingStrategy": false, + "clearImmediate": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "exports": true, + "fetch": false, + "File": false, + "FormData": false, + "global": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "module": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "process": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "require": false, + "Response": false, + "setImmediate": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "nodeBuiltin": { + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "Buffer": false, + "ByteLengthQueuingStrategy": false, + "clearImmediate": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "fetch": false, + "File": false, + "FormData": false, + "global": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "process": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "Response": false, + "setImmediate": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "commonjs": { + "exports": true, + "global": false, + "module": false, + "require": false + }, + "amd": { + "define": false, + "require": false + }, + "mocha": { + "after": false, + "afterEach": false, + "before": false, + "beforeEach": false, + "context": false, + "describe": false, + "it": false, + "mocha": false, + "run": false, + "setup": false, + "specify": false, + "suite": false, + "suiteSetup": false, + "suiteTeardown": false, + "teardown": false, + "test": false, + "xcontext": false, + "xdescribe": false, + "xit": false, + "xspecify": false + }, + "jasmine": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "describe": false, + "expect": false, + "expectAsync": false, + "fail": false, + "fdescribe": false, + "fit": false, + "it": false, + "jasmine": false, + "pending": false, + "runs": false, + "spyOn": false, + "spyOnAllFunctions": false, + "spyOnProperty": false, + "waits": false, + "waitsFor": false, + "xdescribe": false, + "xit": false + }, + "jest": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "describe": false, + "expect": false, + "fdescribe": false, + "fit": false, + "it": false, + "jest": false, + "pit": false, + "require": false, + "test": false, + "xdescribe": false, + "xit": false, + "xtest": false + }, + "qunit": { + "asyncTest": false, + "deepEqual": false, + "equal": false, + "expect": false, + "module": false, + "notDeepEqual": false, + "notEqual": false, + "notOk": false, + "notPropEqual": false, + "notStrictEqual": false, + "ok": false, + "propEqual": false, + "QUnit": false, + "raises": false, + "start": false, + "stop": false, + "strictEqual": false, + "test": false, + "throws": false + }, + "phantomjs": { + "console": true, + "exports": true, + "phantom": true, + "require": true, + "WebPage": true + }, + "couch": { + "emit": false, + "exports": false, + "getRow": false, + "log": false, + "module": false, + "provides": false, + "require": false, + "respond": false, + "send": false, + "start": false, + "sum": false + }, + "rhino": { + "defineClass": false, + "deserialize": false, + "gc": false, + "help": false, + "importClass": false, + "importPackage": false, + "java": false, + "load": false, + "loadClass": false, + "Packages": false, + "print": false, + "quit": false, + "readFile": false, + "readUrl": false, + "runCommand": false, + "seal": false, + "serialize": false, + "spawn": false, + "sync": false, + "toint32": false, + "version": false + }, + "nashorn": { + "__DIR__": false, + "__FILE__": false, + "__LINE__": false, + "com": false, + "edu": false, + "exit": false, + "java": false, + "Java": false, + "javafx": false, + "JavaImporter": false, + "javax": false, + "JSAdapter": false, + "load": false, + "loadWithNewGlobal": false, + "org": false, + "Packages": false, + "print": false, + "quit": false + }, + "wsh": { + "ActiveXObject": false, + "CollectGarbage": false, + "Debug": false, + "Enumerator": false, + "GetObject": false, + "RuntimeObject": false, + "ScriptEngine": false, + "ScriptEngineBuildVersion": false, + "ScriptEngineMajorVersion": false, + "ScriptEngineMinorVersion": false, + "VBArray": false, + "WScript": false, + "WSH": false + }, + "jquery": { + "$": false, + "jQuery": false + }, + "yui": { + "YAHOO": false, + "YAHOO_config": false, + "YUI": false, + "YUI_config": false + }, + "shelljs": { + "cat": false, + "cd": false, + "chmod": false, + "config": false, + "cp": false, + "dirs": false, + "echo": false, + "env": false, + "error": false, + "exec": false, + "exit": false, + "find": false, + "grep": false, + "ln": false, + "ls": false, + "mkdir": false, + "mv": false, + "popd": false, + "pushd": false, + "pwd": false, + "rm": false, + "sed": false, + "set": false, + "target": false, + "tempdir": false, + "test": false, + "touch": false, + "which": false + }, + "prototypejs": { + "$": false, + "$$": false, + "$A": false, + "$break": false, + "$continue": false, + "$F": false, + "$H": false, + "$R": false, + "$w": false, + "Abstract": false, + "Ajax": false, + "Autocompleter": false, + "Builder": false, + "Class": false, + "Control": false, + "Draggable": false, + "Draggables": false, + "Droppables": false, + "Effect": false, + "Element": false, + "Enumerable": false, + "Event": false, + "Field": false, + "Form": false, + "Hash": false, + "Insertion": false, + "ObjectRange": false, + "PeriodicalExecuter": false, + "Position": false, + "Prototype": false, + "Scriptaculous": false, + "Selector": false, + "Sortable": false, + "SortableObserver": false, + "Sound": false, + "Template": false, + "Toggle": false, + "Try": false + }, + "meteor": { + "$": false, + "Accounts": false, + "AccountsClient": false, + "AccountsCommon": false, + "AccountsServer": false, + "App": false, + "Assets": false, + "Blaze": false, + "check": false, + "Cordova": false, + "DDP": false, + "DDPRateLimiter": false, + "DDPServer": false, + "Deps": false, + "EJSON": false, + "Email": false, + "HTTP": false, + "Log": false, + "Match": false, + "Meteor": false, + "Mongo": false, + "MongoInternals": false, + "Npm": false, + "Package": false, + "Plugin": false, + "process": false, + "Random": false, + "ReactiveDict": false, + "ReactiveVar": false, + "Router": false, + "ServiceConfiguration": false, + "Session": false, + "share": false, + "Spacebars": false, + "Template": false, + "Tinytest": false, + "Tracker": false, + "UI": false, + "Utils": false, + "WebApp": false, + "WebAppInternals": false + }, + "mongo": { + "_isWindows": false, + "_rand": false, + "BulkWriteResult": false, + "cat": false, + "cd": false, + "connect": false, + "db": false, + "getHostName": false, + "getMemInfo": false, + "hostname": false, + "ISODate": false, + "listFiles": false, + "load": false, + "ls": false, + "md5sumFile": false, + "mkdir": false, + "Mongo": false, + "NumberInt": false, + "NumberLong": false, + "ObjectId": false, + "PlanCache": false, + "print": false, + "printjson": false, + "pwd": false, + "quit": false, + "removeFile": false, + "rs": false, + "sh": false, + "UUID": false, + "version": false, + "WriteResult": false + }, + "applescript": { + "$": false, + "Application": false, + "Automation": false, + "console": false, + "delay": false, + "Library": false, + "ObjC": false, + "ObjectSpecifier": false, + "Path": false, + "Progress": false, + "Ref": false + }, + "serviceworker": { + "addEventListener": false, + "applicationCache": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "CacheStorage": false, + "clearInterval": false, + "clearTimeout": false, + "Client": false, + "clients": false, + "Clients": false, + "close": true, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "ErrorEvent": false, + "Event": false, + "ExtendableEvent": false, + "ExtendableMessageEvent": false, + "fetch": false, + "FetchEvent": false, + "File": false, + "FileReaderSync": false, + "FormData": false, + "Headers": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "ImageData": false, + "importScripts": false, + "indexedDB": false, + "location": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "name": false, + "navigator": false, + "Notification": false, + "onclose": true, + "onconnect": true, + "onerror": true, + "onfetch": true, + "oninstall": true, + "onlanguagechange": true, + "onmessage": true, + "onmessageerror": true, + "onnotificationclick": true, + "onnotificationclose": true, + "onoffline": true, + "ononline": true, + "onpush": true, + "onpushsubscriptionchange": true, + "onrejectionhandled": true, + "onsync": true, + "onunhandledrejection": true, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "postMessage": true, + "Promise": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "registration": false, + "removeEventListener": false, + "Request": false, + "Response": false, + "self": false, + "ServiceWorker": false, + "ServiceWorkerContainer": false, + "ServiceWorkerGlobalScope": false, + "ServiceWorkerMessageEvent": false, + "ServiceWorkerRegistration": false, + "setInterval": false, + "setTimeout": false, + "skipWaiting": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WebSocket": false, + "WindowClient": false, + "Worker": false, + "WorkerGlobalScope": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLHttpRequest": false + }, + "atomtest": { + "advanceClock": false, + "atom": false, + "fakeClearInterval": false, + "fakeClearTimeout": false, + "fakeSetInterval": false, + "fakeSetTimeout": false, + "resetTimeouts": false, + "waitsForPromise": false + }, + "embertest": { + "andThen": false, + "click": false, + "currentPath": false, + "currentRouteName": false, + "currentURL": false, + "fillIn": false, + "find": false, + "findAll": false, + "findWithAssert": false, + "keyEvent": false, + "pauseTest": false, + "resumeTest": false, + "triggerEvent": false, + "visit": false, + "wait": false + }, + "protractor": { + "$": false, + "$$": false, + "browser": false, + "by": false, + "By": false, + "DartObject": false, + "element": false, + "protractor": false + }, + "shared-node-browser": { + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "fetch": false, + "File": false, + "FormData": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "Response": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "webextensions": { + "browser": false, + "chrome": false, + "opr": false + }, + "greasemonkey": { + "cloneInto": false, + "createObjectIn": false, + "exportFunction": false, + "GM": false, + "GM_addElement": false, + "GM_addStyle": false, + "GM_addValueChangeListener": false, + "GM_deleteValue": false, + "GM_download": false, + "GM_getResourceText": false, + "GM_getResourceURL": false, + "GM_getTab": false, + "GM_getTabs": false, + "GM_getValue": false, + "GM_info": false, + "GM_listValues": false, + "GM_log": false, + "GM_notification": false, + "GM_openInTab": false, + "GM_registerMenuCommand": false, + "GM_removeValueChangeListener": false, + "GM_saveTab": false, + "GM_setClipboard": false, + "GM_setValue": false, + "GM_unregisterMenuCommand": false, + "GM_xmlhttpRequest": false, + "unsafeWindow": false + }, + "devtools": { + "$": false, + "$_": false, + "$$": false, + "$0": false, + "$1": false, + "$2": false, + "$3": false, + "$4": false, + "$x": false, + "chrome": false, + "clear": false, + "copy": false, + "debug": false, + "dir": false, + "dirxml": false, + "getEventListeners": false, + "inspect": false, + "keys": false, + "monitor": false, + "monitorEvents": false, + "profile": false, + "profileEnd": false, + "queryObjects": false, + "table": false, + "undebug": false, + "unmonitor": false, + "unmonitorEvents": false, + "values": false + } +} diff --git a/node_modules/globals/index.d.ts b/node_modules/globals/index.d.ts new file mode 100644 index 0000000..a842e4c --- /dev/null +++ b/node_modules/globals/index.d.ts @@ -0,0 +1,6 @@ +import {ReadonlyDeep} from 'type-fest'; +import globalsJson = require('./globals.json'); + +declare const globals: ReadonlyDeep; + +export = globals; diff --git a/node_modules/globals/index.js b/node_modules/globals/index.js new file mode 100644 index 0000000..a951582 --- /dev/null +++ b/node_modules/globals/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = require('./globals.json'); diff --git a/node_modules/globals/license b/node_modules/globals/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/globals/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/globals/package.json b/node_modules/globals/package.json new file mode 100644 index 0000000..2eb5e44 --- /dev/null +++ b/node_modules/globals/package.json @@ -0,0 +1,55 @@ +{ + "name": "globals", + "version": "13.21.0", + "description": "Global identifiers from different JavaScript environments", + "license": "MIT", + "repository": "sindresorhus/globals", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "index.d.ts", + "globals.json" + ], + "keywords": [ + "globals", + "global", + "identifiers", + "variables", + "vars", + "jshint", + "eslint", + "environments" + ], + "dependencies": { + "type-fest": "^0.20.2" + }, + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.14.0", + "xo": "^0.36.1" + }, + "xo": { + "ignores": [ + "get-browser-globals.js" + ], + "rules": { + "node/no-unsupported-features/es-syntax": "off" + } + }, + "tsd": { + "compilerOptions": { + "resolveJsonModule": true + } + } +} diff --git a/node_modules/globals/readme.md b/node_modules/globals/readme.md new file mode 100644 index 0000000..0ef22c3 --- /dev/null +++ b/node_modules/globals/readme.md @@ -0,0 +1,56 @@ +# globals + +> Global identifiers from different JavaScript environments + +It's just a [JSON file](globals.json), so use it in any environment. + +This package is used by ESLint. + +**This package [no longer accepts](https://github.com/sindresorhus/globals/issues/82) new environments. If you need it for ESLint, just [create a plugin](http://eslint.org/docs/developer-guide/working-with-plugins#environments-in-plugins).** + +## Install + +``` +$ npm install globals +``` + +## Usage + +```js +const globals = require('globals'); + +console.log(globals.browser); +/* +{ + addEventListener: false, + applicationCache: false, + ArrayBuffer: false, + atob: false, + … +} +*/ +``` + +Each global is given a value of `true` or `false`. A value of `true` indicates that the variable may be overwritten. A value of `false` indicates that the variable should be considered read-only. This information is used by static analysis tools to flag incorrect behavior. We assume all variables should be `false` unless we hear otherwise. + +For Node.js this package provides two sets of globals: + +- `globals.nodeBuiltin`: Globals available to all code running in Node.js. + These will usually be available as properties on the `global` object and include `process`, `Buffer`, but not CommonJS arguments like `require`. + See: https://nodejs.org/api/globals.html +- `globals.node`: A combination of the globals from `nodeBuiltin` plus all CommonJS arguments ("CommonJS module scope"). + See: https://nodejs.org/api/modules.html#modules_the_module_scope + +When analyzing code that is known to run outside of a CommonJS wrapper, for example, JavaScript modules, `nodeBuiltin` can find accidental CommonJS references. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/globalthis/.eslintrc b/node_modules/globalthis/.eslintrc new file mode 100644 index 0000000..afbd40a --- /dev/null +++ b/node_modules/globalthis/.eslintrc @@ -0,0 +1,18 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "browser": true, + "node": true, + }, + + "ignorePatterns": [ + "dist", + ], + + "rules": { + "max-statements-per-line": [2, { "max": 2 }] + } +} diff --git a/node_modules/globalthis/.nycrc b/node_modules/globalthis/.nycrc new file mode 100644 index 0000000..726d82b --- /dev/null +++ b/node_modules/globalthis/.nycrc @@ -0,0 +1,10 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "dist", + "test" + ] +} diff --git a/node_modules/globalthis/CHANGELOG.md b/node_modules/globalthis/CHANGELOG.md new file mode 100644 index 0000000..b2962da --- /dev/null +++ b/node_modules/globalthis/CHANGELOG.md @@ -0,0 +1,96 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.3](https://github.com/es-shims/globalThis/compare/v1.0.2...v1.0.3) - 2022-05-07 + +### Commits + +- [actions] reuse common workflows [`65891e4`](https://github.com/es-shims/globalThis/commit/65891e4d285ae04e216ff01160cff861e0e41a4f) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`82f8481`](https://github.com/es-shims/globalThis/commit/82f84815027f666f625e1ccb41f723800a05d016) +- [meta] use `npmignore` to autogenerate an npmignore file [`53afc39`](https://github.com/es-shims/globalThis/commit/53afc39bfd3eb262c5e6e9dfd25e4f81f3578c1c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`03169d4`](https://github.com/es-shims/globalThis/commit/03169d4254c9ef177d6537becca5b0b56df50d91) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`4986e3e`](https://github.com/es-shims/globalThis/commit/4986e3e20c5f664601871a0fac68c1efd0a68472) +- [actions] update codecov uploader [`15c4b06`](https://github.com/es-shims/globalThis/commit/15c4b062b1a9434dbec93604ed31b6893d11d458) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `tape` [`8b04a74`](https://github.com/es-shims/globalThis/commit/8b04a749d3cb2f825920beb700899f0c13ad2fb8) +- [Fix] `globalThis` should be writable [`8759985`](https://github.com/es-shims/globalThis/commit/87599852d5f91e2e1f06e424cdefcd443ec98476) +- [readme] add github actions/codecov badges [`0263f0d`](https://github.com/es-shims/globalThis/commit/0263f0debfa982b928fcd301b11fe3e3193bf33d) +- [Dev Deps] update `aud`, `eslint`, `tape` [`e88d296`](https://github.com/es-shims/globalThis/commit/e88d296bb026633bdd1be2e1542903a5d0107cd8) +- [meta] use `prepublishOnly` script for npm 7+ [`c81fde6`](https://github.com/es-shims/globalThis/commit/c81fde6a9e44345e56dada588e16db736809ddd9) +- [Tests] nycignore `dist` [`bde0c0d`](https://github.com/es-shims/globalThis/commit/bde0c0df46f684316ab414da1487a0cd2efe3eeb) +- [meta] gitignore coverage output [`79f73f8`](https://github.com/es-shims/globalThis/commit/79f73f8b0c1180567fba473f92c07d71efd4dd0b) + +## [v1.0.2](https://github.com/es-shims/globalThis/compare/v1.0.1...v1.0.2) - 2021-02-22 + +### Commits + +- [Tests] migrate tests to Github Actions [`a3f50f7`](https://github.com/es-shims/globalThis/commit/a3f50f77a392c0ffdaca18fb5881743b874d0a6f) +- [meta] do not publish github action workflow files [`eb5c787`](https://github.com/es-shims/globalThis/commit/eb5c7879317cd7f1fde52228660be8e779c9d4e3) +- [Tests] add `implementation` est; run `es-shim-api` in postlint; use `tape` runner [`c9dd792`](https://github.com/es-shims/globalThis/commit/c9dd792d492ec9744a5e5d5033e919b94d441bac) +- [Tests] fix native tests [`6b76dff`](https://github.com/es-shims/globalThis/commit/6b76dff3af3fe9bcd7b24d48c6ba55116169e840) +- [Tests] run `nyc` on all tests [`0407f79`](https://github.com/es-shims/globalThis/commit/0407f79f64bf9fc30111f3bf4dff7e4205331fb6) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape`, `browserify` [`b8cc020`](https://github.com/es-shims/globalThis/commit/b8cc020e5ecc2d5a5a5b4160aabc60cc42d50c03) +- [actions] add "Allow Edits" workflow [`e2854df`](https://github.com/es-shims/globalThis/commit/e2854df653667b16ff34a7a0a7b677231dfe2b02) +- [readme] remove travis badge [`262eb76`](https://github.com/es-shims/globalThis/commit/262eb76e4e0d3f2df354cc6aff1b18f50c7b147f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`; add `safe-publish-latest` [`3c76883`](https://github.com/es-shims/globalThis/commit/3c7688325f6aa050afe3ed978e423e70974e4d3b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`7276123`](https://github.com/es-shims/globalThis/commit/727612396262fc22275f44159ec5b39115dc359f) +- [actions] update workflows [`bcb0f42`](https://github.com/es-shims/globalThis/commit/bcb0f42c319cf19746e03a6667cf25d3e835f46e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`5485851`](https://github.com/es-shims/globalThis/commit/548585148e874d6eb0b0463526a88e8b64e7c5eb) +- [Dev Deps] update `auto-changelog`, `tape` [`6a01da3`](https://github.com/es-shims/globalThis/commit/6a01da3f321983d1970d793711d31cf8508ef94d) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`7a07f4e`](https://github.com/es-shims/globalThis/commit/7a07f4ebc5580933b40bbe67f357632e0f7d5586) +- [meta] only run the build script in publish [`797e492`](https://github.com/es-shims/globalThis/commit/797e492519ed0bf6270537290e69ca0456790575) +- [meta] combine duplicate `prepublish` scripts [`92bbef0`](https://github.com/es-shims/globalThis/commit/92bbef0f91f6e91163186f68b5f5f1ffd26c479d) +- [Dev Deps] update `auto-changelog`; add `aud` [`be6dbec`](https://github.com/es-shims/globalThis/commit/be6dbecefddb40493c5568a2cbe83f74e2e0385f) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`bfd54f8`](https://github.com/es-shims/globalThis/commit/bfd54f8388758e7dec618dc34956e7075a7c15f0) +- [Tests] only audit prod deps [`0f64b47`](https://github.com/es-shims/globalThis/commit/0f64b47acfa812affbacbe487fcb0f6c02eccc25) + +## [v1.0.1](https://github.com/es-shims/globalThis/compare/v1.0.0...v1.0.1) - 2019-12-15 + +### Fixed + +- [Refactor] only use `global` in node; only check browser globals in browsers [`#2`](https://github.com/es-shims/globalThis/issues/2) + +### Commits + +- [Tests] use shared travis-ci configs [`edb1cc9`](https://github.com/es-shims/globalThis/commit/edb1cc9d900a40e8c1732264b6e85d4f9760920c) +- [Tests] remove `jscs` [`1847ac2`](https://github.com/es-shims/globalThis/commit/1847ac2487e2c13cf8bf717211c6a93fe60831f9) +- [meta] add `auto-changelog` [`933c381`](https://github.com/es-shims/globalThis/commit/933c381083890965ac848d3da21ed9e910cc09cf) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `tape` [`93310bc`](https://github.com/es-shims/globalThis/commit/93310bc01ddacbe23a93b3022daebc9b6f6ae8c3) +- [actions] add automatic rebasing / merge commit blocking [`231dec5`](https://github.com/es-shims/globalThis/commit/231dec511c42e1509035d176e2451c55de20bfe7) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `covert`, `is`, `tape` [`e50c1f6`](https://github.com/es-shims/globalThis/commit/e50c1f6d2d45c66f53ffda471bbf62c08ed15c9b) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`4abd340`](https://github.com/es-shims/globalThis/commit/4abd3400fc8942963e77515d0cf2fbcac3cb7bc8) +- [meta] add `funding` field [`2d1f9eb`](https://github.com/es-shims/globalThis/commit/2d1f9eb00b2dea46f6de7d563b31db17f44f1899) +- [meta] remove unused deps [`5bd6bef`](https://github.com/es-shims/globalThis/commit/5bd6befefbaf0c7e6f70eb3c1919b5c5a271d29d) +- readme: Fix casing + phrasing [`66379cc`](https://github.com/es-shims/globalThis/commit/66379ccf5008f7676aac5f3dec1ea2fe55e3516c) +- [Deps] update `define-properties`, `object-keys` [`4585e5a`](https://github.com/es-shims/globalThis/commit/4585e5ab461093ab6c62ce0b22b959925e8f818c) +- fix issue with Webpack's CaseSensitivePathsPlugin [`842e84e`](https://github.com/es-shims/globalThis/commit/842e84e0096c9eea660c78fd19c9c07799b81537) + +## v1.0.0 - 2018-08-10 + +### Commits + +- Dotfiles. [`f01b02d`](https://github.com/es-shims/globalThis/commit/f01b02d315865c812e5b9158f71bb18f3b153def) +- [Tests] up to `node` `v10.7`, `v9.11`, `v8.11`, `v7.10`, `v6.14`, `v4.9`; use `nvm install-latest-npm`; improve matrix [`ed1fa5d`](https://github.com/es-shims/globalThis/commit/ed1fa5d473d933b3270410b658183dc1c556a663) +- Tests [`ab99527`](https://github.com/es-shims/globalThis/commit/ab99527e3c434e89dd40f8cba3b0e2e976156611) +- [breaking] update property name, rename repo [`be42e3d`](https://github.com/es-shims/globalThis/commit/be42e3dce08b62a78260d487f62fa69b410d7918) +- package.json [`ca43a36`](https://github.com/es-shims/globalThis/commit/ca43a363e3ce0dbc2d4623169f8cb3d792f8bc84) +- implementation [`80b5a40`](https://github.com/es-shims/globalThis/commit/80b5a403ef532254b2af46ec3ba5f442a308a57d) +- read me [`f6df9b3`](https://github.com/es-shims/globalThis/commit/f6df9b3b69977f04e080d1720ba1203c13447884) +- Rename `System.global` to `global` [`fa8503c`](https://github.com/es-shims/globalThis/commit/fa8503cf94afe84b3729dd5b0e9f73f481fb1fee) +- Initial commit [`99f1dc3`](https://github.com/es-shims/globalThis/commit/99f1dc328d0b4c52a550037de0139d5452ac01de) +- [Tests] up to `node` `v6.7`, `v5.12`, `v4.6`; improve test matrix [`712ec0e`](https://github.com/es-shims/globalThis/commit/712ec0e545d1603c4e23f4ff1acb066cc4a3c9ee) +- [Dev Deps] update `browserify`, `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`73278bd`](https://github.com/es-shims/globalThis/commit/73278bd638d1e762eb7415350a738f5d345896f5) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `browserify`, `eslint`, `for-each`, `is`, `nsp`, `tape` [`75fa992`](https://github.com/es-shims/globalThis/commit/75fa9929be81afec43895c02e33d0b8a78f11d1f) +- [Dev Deps] update `browserify`, `is`, `tape`, `nsp`, `eslint` [`b223e86`](https://github.com/es-shims/globalThis/commit/b223e86d0868efb1f0c966370ff2f822516d6956) +- [Tests] fix linting; remove parallelshell [`271b329`](https://github.com/es-shims/globalThis/commit/271b329d174b94c08913060752a2e9f9116fe5b8) +- [Deps] update `function-bind`, `object-keys` [`002d0c5`](https://github.com/es-shims/globalThis/commit/002d0c5685a83f97e014a8a07134eb621794c649) +- Only apps should have lockfiles [`960f1d0`](https://github.com/es-shims/globalThis/commit/960f1d00598cbba5427849c863eb10b8de82fb1b) +- [Tests] on `node` `v10.8` [`37fad9d`](https://github.com/es-shims/globalThis/commit/37fad9db9860c654efe0a32ec187f21730d5fed8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`df28dfe`](https://github.com/es-shims/globalThis/commit/df28dfe7f0daf3db95a536a6ce64062bd706185d) +- [New] add `auto` entry point [`86eb2ab`](https://github.com/es-shims/globalThis/commit/86eb2ab4c4dc2babff20ac436cf7fb7f8da7d2f2) +- [Dev Deps] update `eslint` [`1bdc1aa`](https://github.com/es-shims/globalThis/commit/1bdc1aacfb94dcdc7bb61688c7634c435012e35d) +- [Deps] update `object-keys` [`72cdbf5`](https://github.com/es-shims/globalThis/commit/72cdbf596b16103ee711d52b2b645b42efc08c51) +- Update most common usage to invoke the function upon being required [`5026296`](https://github.com/es-shims/globalThis/commit/502629660da2c21cfb0f8ca233e2b9d427c052fe) diff --git a/node_modules/globalthis/LICENSE b/node_modules/globalthis/LICENSE new file mode 100644 index 0000000..44f679a --- /dev/null +++ b/node_modules/globalthis/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/globalthis/README.md b/node_modules/globalthis/README.md new file mode 100644 index 0000000..6abffa0 --- /dev/null +++ b/node_modules/globalthis/README.md @@ -0,0 +1,70 @@ +# globalThis [![Version Badge][npm-version-svg]][npm-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][npm-url] + +An ECMAScript spec-compliant polyfill/shim for `globalThis`. Invoke its "shim" method to shim `globalThis` if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec proposal](https://github.com/tc39/proposal-global). + +Most common usage: +```js +var globalThis = require('globalthis')(); // returns native globalThis if compliant + /* or */ +var globalThis = require('globalthis/polyfill')(); // returns native globalThis if compliant +``` + +## Example + +```js +var assert = require('assert'); + +// the below function is not CSP-compliant, but reliably gets the +// global object in sloppy mode in every engine. +var getGlobal = Function('return this'); + +assert.equal(globalThis, getGlobal()); +``` + +```js +/* when `globalThis` is not present */ +var shimmedGlobal = require('globalthis').shim(); + /* or */ +var shimmedGlobal = require('globalthis/shim')(); + +assert.equal(shimmedGlobal, globalThis); +assert.equal(shimmedGlobal, getGlobal()); +``` + +```js +/* when `globalThis` is present */ +var shimmedGlobal = require('globalthis').shim(); + +assert.equal(shimmedGlobal, globalThis); +assert.equal(shimmedGlobal, getGlobal()); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[npm-url]: https://npmjs.org/package/globalthis +[npm-version-svg]: https://versionbadg.es/ljharb/globalThis.svg +[deps-svg]: https://david-dm.org/ljharb/globalThis.svg?theme=shields.io +[deps-url]: https://david-dm.org/ljharb/globalThis +[dev-deps-svg]: https://david-dm.org/ljharb/globalThis/dev-status.svg?theme=shields.io +[dev-deps-url]: https://david-dm.org/ljharb/globalThis#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/globalthis.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/globalthis.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/globalthis.svg +[downloads-url]: https://npm-stat.com/charts.html?package=globalthis +[codecov-image]: https://codecov.io/gh/es-shims/globalThis/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/globalThis/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/globalThis +[actions-url]: https://github.com/es-shims/globalThis/actions diff --git a/node_modules/globalthis/auto.js b/node_modules/globalthis/auto.js new file mode 100644 index 0000000..8ebf606 --- /dev/null +++ b/node_modules/globalthis/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/globalthis/implementation.browser.js b/node_modules/globalthis/implementation.browser.js new file mode 100644 index 0000000..746a274 --- /dev/null +++ b/node_modules/globalthis/implementation.browser.js @@ -0,0 +1,11 @@ +/* eslint no-negated-condition: 0, no-new-func: 0 */ + +'use strict'; + +if (typeof self !== 'undefined') { + module.exports = self; +} else if (typeof window !== 'undefined') { + module.exports = window; +} else { + module.exports = Function('return this')(); +} diff --git a/node_modules/globalthis/implementation.js b/node_modules/globalthis/implementation.js new file mode 100644 index 0000000..46b8ceb --- /dev/null +++ b/node_modules/globalthis/implementation.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = global; diff --git a/node_modules/globalthis/index.js b/node_modules/globalthis/index.js new file mode 100644 index 0000000..7c73cef --- /dev/null +++ b/node_modules/globalthis/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var defineProperties = require('define-properties'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var polyfill = getPolyfill(); + +var getGlobal = function () { return polyfill; }; + +defineProperties(getGlobal, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = getGlobal; diff --git a/node_modules/globalthis/package.json b/node_modules/globalthis/package.json new file mode 100644 index 0000000..3750c43 --- /dev/null +++ b/node_modules/globalthis/package.json @@ -0,0 +1,97 @@ +{ + "name": "globalthis", + "version": "1.0.3", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "ECMAScript spec-compliant polyfill/shim for `globalThis`", + "license": "MIT", + "main": "index.js", + "browser": { + "./implementation": "./implementation.browser.js" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest && npm run build", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run --silent tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "postlint": "es-shim-api --bound --property", + "build": "mkdir -p dist && browserify browserShim.js > dist/browser.js", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/ljharb/System.global.git" + }, + "keywords": [ + "window", + "self", + "global", + "globalThis", + "System.global", + "global object", + "global this value", + "ECMAScript", + "es-shim API", + "polyfill", + "shim" + ], + "dependencies": { + "define-properties": "^1.1.3" + }, + "devDependencies": { + "@es-shims/api": "^2.2.3", + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "browserify": "^16.5.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "is": "^3.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.3" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + "browserShim.js", + ".github/workflows" + ] + } +} diff --git a/node_modules/globalthis/polyfill.js b/node_modules/globalthis/polyfill.js new file mode 100644 index 0000000..e2e706b --- /dev/null +++ b/node_modules/globalthis/polyfill.js @@ -0,0 +1,10 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + if (typeof global !== 'object' || !global || global.Math !== Math || global.Array !== Array) { + return implementation; + } + return global; +}; diff --git a/node_modules/globalthis/shim.js b/node_modules/globalthis/shim.js new file mode 100644 index 0000000..7ccf455 --- /dev/null +++ b/node_modules/globalthis/shim.js @@ -0,0 +1,22 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimGlobal() { + var polyfill = getPolyfill(); + if (define.supportsDescriptors) { + var descriptor = Object.getOwnPropertyDescriptor(polyfill, 'globalThis'); + if (!descriptor || (descriptor.configurable && (descriptor.enumerable || !descriptor.writable || globalThis !== polyfill))) { // eslint-disable-line max-len + Object.defineProperty(polyfill, 'globalThis', { + configurable: true, + enumerable: false, + value: polyfill, + writable: true + }); + } + } else if (typeof globalThis !== 'object' || globalThis !== polyfill) { + polyfill.globalThis = polyfill; + } + return polyfill; +}; diff --git a/node_modules/globalthis/test/implementation.js b/node_modules/globalthis/test/implementation.js new file mode 100644 index 0000000..36f1275 --- /dev/null +++ b/node_modules/globalthis/test/implementation.js @@ -0,0 +1,11 @@ +'use strict'; + +var implementation = require('../implementation'); +var test = require('tape'); +var runTests = require('./tests'); + +test('implementation', function (t) { + runTests(implementation, t); + + t.end(); +}); diff --git a/node_modules/globalthis/test/index.js b/node_modules/globalthis/test/index.js new file mode 100644 index 0000000..dac0a10 --- /dev/null +++ b/node_modules/globalthis/test/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var systemGlobal = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + runTests(systemGlobal(), t); + + t.end(); +}); diff --git a/node_modules/globalthis/test/native.js b/node_modules/globalthis/test/native.js new file mode 100644 index 0000000..7a085ab --- /dev/null +++ b/node_modules/globalthis/test/native.js @@ -0,0 +1,26 @@ +'use strict'; + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var missing = {}; +var theGlobal = typeof globalThis === 'object' ? globalThis : missing; + +var runTests = require('./tests'); + +test('native', { todo: theGlobal === missing }, function (t) { + if (theGlobal !== missing) { + t.equal(typeof theGlobal, 'object', 'globalThis is an object'); + t.equal('globalThis' in theGlobal, true, 'globalThis is in globalThis'); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(theGlobal, 'globalThis'), 'globalThis is not enumerable'); + et.end(); + }); + + runTests(theGlobal, t); + } + + t.end(); +}); diff --git a/node_modules/globalthis/test/shimmed.js b/node_modules/globalthis/test/shimmed.js new file mode 100644 index 0000000..24b3f34 --- /dev/null +++ b/node_modules/globalthis/test/shimmed.js @@ -0,0 +1,29 @@ +'use strict'; + +require('../auto'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.equal(typeof globalThis, 'object', 'globalThis is an object'); + t.equal('globalThis' in globalThis, true, 'globalThis is in globalThis'); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(globalThis, 'globalThis'), 'globalThis.globalThis is not enumerable'); + et.end(); + }); + + t.test('writability', { skip: !defineProperties.supportsDescriptors }, function (wt) { + var desc = Object.getOwnPropertyDescriptor(globalThis, 'globalThis'); + wt.equal(desc.writable, true, 'globalThis.globalThis is writable'); + wt.end(); + }); + + runTests(globalThis.globalThis, t); + + t.end(); +}); diff --git a/node_modules/globalthis/test/tests.js b/node_modules/globalthis/test/tests.js new file mode 100644 index 0000000..2189640 --- /dev/null +++ b/node_modules/globalthis/test/tests.js @@ -0,0 +1,36 @@ +/* jscs:disable requireUseStrict */ +/* eslint strict: 0, max-statements: 0 */ + +module.exports = function (theGlobal, t) { + t.equal(typeof theGlobal, 'object', 'is an object'); + + t.test('built-in globals', function (st) { + st.equal(theGlobal.Math, Math, 'Math is on the global'); + st.equal(theGlobal.JSON, JSON, 'JSON is on the global'); + st.equal(theGlobal.String, String, 'String is on the global'); + st.equal(theGlobal.Array, Array, 'Array is on the global'); + st.equal(theGlobal.Number, Number, 'Number is on the global'); + st.equal(theGlobal.Boolean, Boolean, 'Boolean is on the global'); + st.equal(theGlobal.Object, Object, 'Object is on the global'); + st.equal(theGlobal.Function, Function, 'Function is on the global'); + st.equal(theGlobal.Date, Date, 'Date is on the global'); + st.equal(theGlobal.RegExp, RegExp, 'RegExp is on the global'); + + if (typeof Symbol === 'undefined') { + st.comment('# SKIP Symbol is not supported'); + } else { + st.equal(theGlobal.Symbol, Symbol, 'Symbol is on the global'); + } + st.end(); + }); + + t.test('custom property', function (st) { + var key = 'random_custom_key_' + new Date().getTime(); + var semaphore = {}; + /* eslint no-eval: 1 */ + eval(key + ' = semaphore;'); + st.equal(theGlobal[key], semaphore, 'global variable ends up on the global object'); + delete theGlobal[key]; // eslint-disable-line no-param-reassign + st.end(); + }); +}; diff --git a/node_modules/gopd/.eslintrc b/node_modules/gopd/.eslintrc new file mode 100644 index 0000000..e2550c0 --- /dev/null +++ b/node_modules/gopd/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": [2, "declaration"], + "id-length": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/gopd/.github/FUNDING.yml b/node_modules/gopd/.github/FUNDING.yml new file mode 100644 index 0000000..94a44a8 --- /dev/null +++ b/node_modules/gopd/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/gopd +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/gopd/CHANGELOG.md b/node_modules/gopd/CHANGELOG.md new file mode 100644 index 0000000..f111eb1 --- /dev/null +++ b/node_modules/gopd/CHANGELOG.md @@ -0,0 +1,25 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/gopd/compare/v1.0.0...v1.0.1) - 2022-11-01 + +### Commits + +- [Fix] actually export gOPD instead of dP [`4b624bf`](https://github.com/ljharb/gopd/commit/4b624bfbeff788c5e3ff16d9443a83627847234f) + +## v1.0.0 - 2022-11-01 + +### Commits + +- Initial implementation, tests, readme [`0911e01`](https://github.com/ljharb/gopd/commit/0911e012cd642092bd88b732c161c58bf4f20bea) +- Initial commit [`b84e33f`](https://github.com/ljharb/gopd/commit/b84e33f5808a805ac57ff88d4247ad935569acbe) +- [actions] add reusable workflows [`12ae28a`](https://github.com/ljharb/gopd/commit/12ae28ae5f50f86e750215b6e2188901646d0119) +- npm init [`280118b`](https://github.com/ljharb/gopd/commit/280118badb45c80b4483836b5cb5315bddf6e582) +- [meta] add `auto-changelog` [`bb78de5`](https://github.com/ljharb/gopd/commit/bb78de5639a180747fb290c28912beaaf1615709) +- [meta] create FUNDING.yml; add `funding` in package.json [`11c22e6`](https://github.com/ljharb/gopd/commit/11c22e6355bb01f24e7fac4c9bb3055eb5b25002) +- [meta] use `npmignore` to autogenerate an npmignore file [`4f4537a`](https://github.com/ljharb/gopd/commit/4f4537a843b39f698c52f072845092e6fca345bb) +- Only apps should have lockfiles [`c567022`](https://github.com/ljharb/gopd/commit/c567022a18573aa7951cf5399445d9840e23e98b) diff --git a/node_modules/gopd/LICENSE b/node_modules/gopd/LICENSE new file mode 100644 index 0000000..6abfe14 --- /dev/null +++ b/node_modules/gopd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/gopd/README.md b/node_modules/gopd/README.md new file mode 100644 index 0000000..784e56a --- /dev/null +++ b/node_modules/gopd/README.md @@ -0,0 +1,40 @@ +# gopd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation. + +## Usage + +```javascript +var gOPD = require('gopd'); +var assert = require('assert'); + +if (gOPD) { + assert.equal(typeof gOPD, 'function', 'descriptors supported'); + // use gOPD like Object.getOwnPropertyDescriptor here +} else { + assert.ok(!gOPD, 'descriptors not supported'); +} +``` + +[package-url]: https://npmjs.org/package/gopd +[npm-version-svg]: https://versionbadg.es/ljharb/gopd.svg +[deps-svg]: https://david-dm.org/ljharb/gopd.svg +[deps-url]: https://david-dm.org/ljharb/gopd +[dev-deps-svg]: https://david-dm.org/ljharb/gopd/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/gopd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/gopd.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/gopd.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/gopd.svg +[downloads-url]: https://npm-stat.com/charts.html?package=gopd +[codecov-image]: https://codecov.io/gh/ljharb/gopd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/gopd/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/gopd +[actions-url]: https://github.com/ljharb/gopd/actions diff --git a/node_modules/gopd/index.js b/node_modules/gopd/index.js new file mode 100644 index 0000000..fb6d3bb --- /dev/null +++ b/node_modules/gopd/index.js @@ -0,0 +1,16 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; diff --git a/node_modules/gopd/package.json b/node_modules/gopd/package.json new file mode 100644 index 0000000..d5e1fa4 --- /dev/null +++ b/node_modules/gopd/package.json @@ -0,0 +1,71 @@ +{ + "name": "gopd", + "version": "1.0.1", + "description": "`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/gopd.git" + }, + "keywords": [ + "ecmascript", + "javascript", + "getownpropertydescriptor", + "property", + "descriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/gopd/issues" + }, + "homepage": "https://github.com/ljharb/gopd#readme", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.1", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/gopd/test/index.js b/node_modules/gopd/test/index.js new file mode 100644 index 0000000..0376bfb --- /dev/null +++ b/node_modules/gopd/test/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var test = require('tape'); +var gOPD = require('../'); + +test('gOPD', function (t) { + t.test('supported', { skip: !gOPD }, function (st) { + st.equal(typeof gOPD, 'function', 'is a function'); + + var obj = { x: 1 }; + st.ok('x' in obj, 'property exists'); + + var desc = gOPD(obj, 'x'); + st.deepEqual( + desc, + { + configurable: true, + enumerable: true, + value: 1, + writable: true + }, + 'descriptor is as expected' + ); + + st.end(); + }); + + t.test('not supported', { skip: gOPD }, function (st) { + st.notOk(gOPD, 'is falsy'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/graceful-fs/LICENSE b/node_modules/graceful-fs/LICENSE new file mode 100644 index 0000000..e906a25 --- /dev/null +++ b/node_modules/graceful-fs/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/graceful-fs/README.md b/node_modules/graceful-fs/README.md new file mode 100644 index 0000000..82d6e4d --- /dev/null +++ b/node_modules/graceful-fs/README.md @@ -0,0 +1,143 @@ +# graceful-fs + +graceful-fs functions as a drop-in replacement for the fs module, +making various improvements. + +The improvements are meant to normalize behavior across different +platforms and environments, and to make filesystem access more +resilient to errors. + +## Improvements over [fs module](https://nodejs.org/api/fs.html) + +* Queues up `open` and `readdir` calls, and retries them once + something closes if there is an EMFILE error from too many file + descriptors. +* fixes `lchmod` for Node versions prior to 0.6.2. +* implements `fs.lutimes` if possible. Otherwise it becomes a noop. +* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or + `lchown` if the user isn't root. +* makes `lchmod` and `lchown` become noops, if not available. +* retries reading a file if `read` results in EAGAIN error. + +On Windows, it retries renaming a file for up to one second if `EACCESS` +or `EPERM` error occurs, likely because antivirus software has locked +the directory. + +## USAGE + +```javascript +// use just like fs +var fs = require('graceful-fs') + +// now go and do stuff with it... +fs.readFile('some-file-or-whatever', (err, data) => { + // Do stuff here. +}) +``` + +## Sync methods + +This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync +methods. If you use sync methods which open file descriptors then you are +responsible for dealing with any errors. + +This is a known limitation, not a bug. + +## Global Patching + +If you want to patch the global fs module (or any other fs-like +module) you can do this: + +```javascript +// Make sure to read the caveat below. +var realFs = require('fs') +var gracefulFs = require('graceful-fs') +gracefulFs.gracefulify(realFs) +``` + +This should only ever be done at the top-level application layer, in +order to delay on EMFILE errors from any fs-using dependencies. You +should **not** do this in a library, because it can cause unexpected +delays in other parts of the program. + +## Changes + +This module is fairly stable at this point, and used by a lot of +things. That being said, because it implements a subtle behavior +change in a core part of the node API, even modest changes can be +extremely breaking, and the versioning is thus biased towards +bumping the major when in doubt. + +The main change between major versions has been switching between +providing a fully-patched `fs` module vs monkey-patching the node core +builtin, and the approach by which a non-monkey-patched `fs` was +created. + +The goal is to trade `EMFILE` errors for slower fs operations. So, if +you try to open a zillion files, rather than crashing, `open` +operations will be queued up and wait for something else to `close`. + +There are advantages to each approach. Monkey-patching the fs means +that no `EMFILE` errors can possibly occur anywhere in your +application, because everything is using the same core `fs` module, +which is patched. However, it can also obviously cause undesirable +side-effects, especially if the module is loaded multiple times. + +Implementing a separate-but-identical patched `fs` module is more +surgical (and doesn't run the risk of patching multiple times), but +also imposes the challenge of keeping in sync with the core module. + +The current approach loads the `fs` module, and then creates a +lookalike object that has all the same methods, except a few that are +patched. It is safe to use in all versions of Node from 0.8 through +7.0. + +### v4 + +* Do not monkey-patch the fs module. This module may now be used as a + drop-in dep, and users can opt into monkey-patching the fs builtin + if their app requires it. + +### v3 + +* Monkey-patch fs, because the eval approach no longer works on recent + node. +* fixed possible type-error throw if rename fails on windows +* verify that we *never* get EMFILE errors +* Ignore ENOSYS from chmod/chown +* clarify that graceful-fs must be used as a drop-in + +### v2.1.0 + +* Use eval rather than monkey-patching fs. +* readdir: Always sort the results +* win32: requeue a file if error has an OK status + +### v2.0 + +* A return to monkey patching +* wrap process.cwd + +### v1.1 + +* wrap readFile +* Wrap fs.writeFile. +* readdir protection +* Don't clobber the fs builtin +* Handle fs.read EAGAIN errors by trying again +* Expose the curOpen counter +* No-op lchown/lchmod if not implemented +* fs.rename patch only for win32 +* Patch fs.rename to handle AV software on Windows +* Close #4 Chown should not fail on einval or eperm if non-root +* Fix isaacs/fstream#1 Only wrap fs one time +* Fix #3 Start at 1024 max files, then back off on EMFILE +* lutimes that doens't blow up on Linux +* A full on-rewrite using a queue instead of just swallowing the EMFILE error +* Wrap Read/Write streams as well + +### 1.0 + +* Update engines for node 0.6 +* Be lstat-graceful on Windows +* first diff --git a/node_modules/graceful-fs/clone.js b/node_modules/graceful-fs/clone.js new file mode 100644 index 0000000..dff3cc8 --- /dev/null +++ b/node_modules/graceful-fs/clone.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = clone + +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} + +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy +} diff --git a/node_modules/graceful-fs/graceful-fs.js b/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000..8d5b89e --- /dev/null +++ b/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,448 @@ +var fs = require('fs') +var polyfills = require('./polyfills.js') +var legacy = require('./legacy-streams.js') +var clone = require('./clone.js') + +var util = require('util') + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} + +function noop () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } + +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } + + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) + + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } + + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + require('assert').equal(fs[gracefulQueue].length, 0) + }) + } +} + +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} + +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} + +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$readFile(path, options, cb) + + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) + + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } + + return go$readdir(path, options, cb) + + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() + + if (typeof cb === 'function') + cb.call(this, err, files) + } + } + } + } + + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } + + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } + + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) + + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } + + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } + + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } + + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + return fs +} + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} + +// keep track of the timeout between retry() calls +var retryTimer + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} + +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined + + if (fs[gracefulQueue].length === 0) + return + + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } +} diff --git a/node_modules/graceful-fs/legacy-streams.js b/node_modules/graceful-fs/legacy-streams.js new file mode 100644 index 0000000..d617b50 --- /dev/null +++ b/node_modules/graceful-fs/legacy-streams.js @@ -0,0 +1,118 @@ +var Stream = require('stream').Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; + } + + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} diff --git a/node_modules/graceful-fs/package.json b/node_modules/graceful-fs/package.json new file mode 100644 index 0000000..87babf0 --- /dev/null +++ b/node_modules/graceful-fs/package.json @@ -0,0 +1,53 @@ +{ + "name": "graceful-fs", + "description": "A drop-in replacement for fs, making various improvements.", + "version": "4.2.11", + "repository": { + "type": "git", + "url": "https://github.com/isaacs/node-graceful-fs" + }, + "main": "graceful-fs.js", + "directories": { + "test": "test" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags", + "test": "nyc --silent node test.js | tap -c -", + "posttest": "nyc report" + }, + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "ISC", + "devDependencies": { + "import-fresh": "^2.0.0", + "mkdirp": "^0.5.0", + "rimraf": "^2.2.8", + "tap": "^16.3.4" + }, + "files": [ + "fs.js", + "graceful-fs.js", + "legacy-streams.js", + "polyfills.js", + "clone.js" + ], + "tap": { + "reporter": "classic" + } +} diff --git a/node_modules/graceful-fs/polyfills.js b/node_modules/graceful-fs/polyfills.js new file mode 100644 index 0000000..453f1a9 --- /dev/null +++ b/node_modules/graceful-fs/polyfills.js @@ -0,0 +1,355 @@ +var constants = require('constants') + +var origCwd = process.cwd +var cwd = null + +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} + +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} + +module.exports = patch + +function patch (fs) { + // (re-)implement some things that are known busted or missing. + + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } + + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } + + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) + + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) + + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) + + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) + + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } + + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) + + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } + + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } + + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } +} diff --git a/node_modules/graphemer/CHANGELOG.md b/node_modules/graphemer/CHANGELOG.md new file mode 100644 index 0000000..dc1dd42 --- /dev/null +++ b/node_modules/graphemer/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.3.0] - 2021-12-13 + +### Added + +- Updated to include support for Unicode 14 + +## [1.2.0] - 2021-01-29 + +### Updated + +- Refactored to increase speed + +## [1.1.0] - 2020-09-14 + +### Added + +- Updated to include support for Unicode 13 + +## [1.0.0] - 2020-09-13 + +- Forked from work by @JLHwung on original `Grapheme-Splitter` library: https://github.com/JLHwung/grapheme-splitter/tree/next +- Converted to Typescript +- Added development and build tooling diff --git a/node_modules/graphemer/LICENSE b/node_modules/graphemer/LICENSE new file mode 100644 index 0000000..51f3831 --- /dev/null +++ b/node_modules/graphemer/LICENSE @@ -0,0 +1,18 @@ +Copyright 2020 Filament (Anomalous Technologies Limited) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/graphemer/README.md b/node_modules/graphemer/README.md new file mode 100644 index 0000000..0ac98ad --- /dev/null +++ b/node_modules/graphemer/README.md @@ -0,0 +1,132 @@ +# Graphemer: Unicode Character Splitter 🪓 + +## Introduction + +This library continues the work of [Grapheme Splitter](https://github.com/orling/grapheme-splitter) and supports the following unicode versions: + +- Unicode 15 and below `[v1.4.0]` +- Unicode 14 and below `[v1.3.0]` +- Unicode 13 and below `[v1.1.0]` +- Unicode 11 and below `[v1.0.0]` (Unicode 10 supported by `grapheme-splitter`) + +In JavaScript there is not always a one-to-one relationship between string characters and what a user would call a separate visual "letter". Some symbols are represented by several characters. This can cause issues when splitting strings and inadvertently cutting a multi-char letter in half, or when you need the actual number of letters in a string. + +For example, emoji characters like "🌷","🎁","💩","😜" and "👍" are represented by two JavaScript characters each (high surrogate and low surrogate). That is, + +```javascript +'🌷'.length == 2; +``` + +The combined emoji are even longer: + +```javascript +'🏳️‍🌈'.length == 6; +``` + +What's more, some languages often include combining marks - characters that are used to modify the letters before them. Common examples are the German letter ü and the Spanish letter ñ. Sometimes they can be represented alternatively both as a single character and as a letter + combining mark, with both forms equally valid: + +```javascript +var two = 'ñ'; // unnormalized two-char n+◌̃, i.e. "\u006E\u0303"; +var one = 'ñ'; // normalized single-char, i.e. "\u00F1" + +console.log(one != two); // prints 'true' +``` + +Unicode normalization, as performed by the popular punycode.js library or ECMAScript 6's String.normalize, can **sometimes** fix those differences and turn two-char sequences into single characters. But it is **not** enough in all cases. Some languages like Hindi make extensive use of combining marks on their letters, that have no dedicated single-codepoint Unicode sequences, due to the sheer number of possible combinations. +For example, the Hindi word "अनुच्छेद" is comprised of 5 letters and 3 combining marks: + +अ + न + ु + च + ् + छ + े + द + +which is in fact just 5 user-perceived letters: + +अ + नु + च् + छे + द + +and which Unicode normalization would not combine properly. +There are also the unusual letter+combining mark combinations which have no dedicated Unicode codepoint. The string Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘ obviously has 5 separate letters, but is in fact comprised of 58 JavaScript characters, most of which are combining marks. + +Enter the `graphemer` library. It can be used to properly split JavaScript strings into what a human user would call separate letters (or "extended grapheme clusters" in Unicode terminology), no matter what their internal representation is. It is an implementation on the [Default Grapheme Cluster Boundary](http://unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table) of [UAX #29](http://www.unicode.org/reports/tr29/). + +## Installation + +Install `graphemer` using the NPM command below: + +``` +$ npm i graphemer +``` + +## Usage + +If you're using [Typescript](https://www.typescriptlang.org/) or a compiler like [Babel](https://babeljs.io/) (or something like Create React App) things are pretty simple; just import, initialize and use! + +```javascript +import Graphemer from 'graphemer'; + +const splitter = new Graphemer(); + +// split the string to an array of grapheme clusters (one string each) +const graphemes = splitter.splitGraphemes(string); + +// iterate the string to an iterable iterator of grapheme clusters (one string each) +const graphemeIterator = splitter.iterateGraphemes(string); + +// or do this if you just need their number +const graphemeCount = splitter.countGraphemes(string); +``` + +If you're using vanilla Node you can use the `require()` method. + +```javascript +const Graphemer = require('graphemer').default; + +const splitter = new Graphemer(); + +const graphemes = splitter.splitGraphemes(string); +``` + +## Examples + +```javascript +import Graphemer from 'graphemer'; + +const splitter = new Graphemer(); + +// plain latin alphabet - nothing spectacular +splitter.splitGraphemes('abcd'); // returns ["a", "b", "c", "d"] + +// two-char emojis and six-char combined emoji +splitter.splitGraphemes('🌷🎁💩😜👍🏳️‍🌈'); // returns ["🌷","🎁","💩","😜","👍","🏳️‍🌈"] + +// diacritics as combining marks, 10 JavaScript chars +splitter.splitGraphemes('Ĺo͂řȩm̅'); // returns ["Ĺ","o͂","ř","ȩ","m̅"] + +// individual Korean characters (Jamo), 4 JavaScript chars +splitter.splitGraphemes('뎌쉐'); // returns ["뎌","쉐"] + +// Hindi text with combining marks, 8 JavaScript chars +splitter.splitGraphemes('अनुच्छेद'); // returns ["अ","नु","च्","छे","द"] + +// demonic multiple combining marks, 75 JavaScript chars +splitter.splitGraphemes('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞'); // returns ["Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍","A̴̵̜̰͔ͫ͗͢","L̠ͨͧͩ͘","G̴̻͈͍͔̹̑͗̎̅͛́","Ǫ̵̹̻̝̳͂̌̌͘","!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞"] +``` + +## TypeScript + +Graphemer is built with TypeScript and, of course, includes type declarations. + +```javascript +import Graphemer from 'graphemer'; + +const splitter = new Graphemer(); + +const split: string[] = splitter.splitGraphemes('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞'); +``` + +## Contributing + +See [Contribution Guide](./CONTRIBUTING.md). + +## Acknowledgements + +This library is a fork of the incredible work done by Orlin Georgiev and Huáng Jùnliàng at https://github.com/orling/grapheme-splitter. + +The original library was heavily influenced by Devon Govett's excellent [grapheme-breaker](https://github.com/devongovett/grapheme-breaker) CoffeeScript library. diff --git a/node_modules/graphemer/lib/Graphemer.d.ts b/node_modules/graphemer/lib/Graphemer.d.ts new file mode 100644 index 0000000..a89b8cb --- /dev/null +++ b/node_modules/graphemer/lib/Graphemer.d.ts @@ -0,0 +1,41 @@ +import GraphemerIterator from './GraphemerIterator'; +export default class Graphemer { + /** + * Returns the next grapheme break in the string after the given index + * @param string {string} + * @param index {number} + * @returns {number} + */ + static nextBreak(string: string, index: number): number; + /** + * Breaks the given string into an array of grapheme clusters + * @param str {string} + * @returns {string[]} + */ + splitGraphemes(str: string): string[]; + /** + * Returns an iterator of grapheme clusters in the given string + * @param str {string} + * @returns {GraphemerIterator} + */ + iterateGraphemes(str: string): GraphemerIterator; + /** + * Returns the number of grapheme clusters in the given string + * @param str {string} + * @returns {number} + */ + countGraphemes(str: string): number; + /** + * Given a Unicode code point, determines this symbol's grapheme break property + * @param code {number} Unicode code point + * @returns {number} + */ + static getGraphemeBreakProperty(code: number): number; + /** + * Given a Unicode code point, returns if symbol is an extended pictographic or some other break + * @param code {number} Unicode code point + * @returns {number} + */ + static getEmojiProperty(code: number): number; +} +//# sourceMappingURL=Graphemer.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/Graphemer.d.ts.map b/node_modules/graphemer/lib/Graphemer.d.ts.map new file mode 100644 index 0000000..692b762 --- /dev/null +++ b/node_modules/graphemer/lib/Graphemer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Graphemer.d.ts","sourceRoot":"","sources":["../src/Graphemer.ts"],"names":[],"mappings":"AAEA,OAAO,iBAAiB,MAAM,qBAAqB,CAAC;AAEpD,MAAM,CAAC,OAAO,OAAO,SAAS;IAC5B;;;;;OAKG;IACH,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM;IA2CvD;;;;OAIG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE;IAcrC;;;;OAIG;IACH,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB;IAIhD;;;;OAIG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAcnC;;;;OAIG;IACH,MAAM,CAAC,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAoySrD;;;;OAIG;IACH,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CA47B9C"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/Graphemer.js b/node_modules/graphemer/lib/Graphemer.js new file mode 100644 index 0000000..8ed00ca --- /dev/null +++ b/node_modules/graphemer/lib/Graphemer.js @@ -0,0 +1,11959 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const boundaries_1 = require("./boundaries"); +const GraphemerHelper_1 = __importDefault(require("./GraphemerHelper")); +const GraphemerIterator_1 = __importDefault(require("./GraphemerIterator")); +class Graphemer { + /** + * Returns the next grapheme break in the string after the given index + * @param string {string} + * @param index {number} + * @returns {number} + */ + static nextBreak(string, index) { + if (index === undefined) { + index = 0; + } + if (index < 0) { + return 0; + } + if (index >= string.length - 1) { + return string.length; + } + const prevCP = GraphemerHelper_1.default.codePointAt(string, index); + const prev = Graphemer.getGraphemeBreakProperty(prevCP); + const prevEmoji = Graphemer.getEmojiProperty(prevCP); + const mid = []; + const midEmoji = []; + for (let i = index + 1; i < string.length; i++) { + // check for already processed low surrogates + if (GraphemerHelper_1.default.isSurrogate(string, i - 1)) { + continue; + } + const nextCP = GraphemerHelper_1.default.codePointAt(string, i); + const next = Graphemer.getGraphemeBreakProperty(nextCP); + const nextEmoji = Graphemer.getEmojiProperty(nextCP); + if (GraphemerHelper_1.default.shouldBreak(prev, mid, next, prevEmoji, midEmoji, nextEmoji)) { + return i; + } + mid.push(next); + midEmoji.push(nextEmoji); + } + return string.length; + } + /** + * Breaks the given string into an array of grapheme clusters + * @param str {string} + * @returns {string[]} + */ + splitGraphemes(str) { + const res = []; + let index = 0; + let brk; + while ((brk = Graphemer.nextBreak(str, index)) < str.length) { + res.push(str.slice(index, brk)); + index = brk; + } + if (index < str.length) { + res.push(str.slice(index)); + } + return res; + } + /** + * Returns an iterator of grapheme clusters in the given string + * @param str {string} + * @returns {GraphemerIterator} + */ + iterateGraphemes(str) { + return new GraphemerIterator_1.default(str, Graphemer.nextBreak); + } + /** + * Returns the number of grapheme clusters in the given string + * @param str {string} + * @returns {number} + */ + countGraphemes(str) { + let count = 0; + let index = 0; + let brk; + while ((brk = Graphemer.nextBreak(str, index)) < str.length) { + index = brk; + count++; + } + if (index < str.length) { + count++; + } + return count; + } + /** + * Given a Unicode code point, determines this symbol's grapheme break property + * @param code {number} Unicode code point + * @returns {number} + */ + static getGraphemeBreakProperty(code) { + // Grapheme break property taken from: + // https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt + // and generated by + // node ./scripts/generate-grapheme-break.js + if (code < 0xbf09) { + if (code < 0xac54) { + if (code < 0x102d) { + if (code < 0xb02) { + if (code < 0x93b) { + if (code < 0x6df) { + if (code < 0x5bf) { + if (code < 0x7f) { + if (code < 0xb) { + if (code < 0xa) { + // Cc [10] .. + if (0x0 <= code && code <= 0x9) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Cc + if (0xa === code) { + return boundaries_1.CLUSTER_BREAK.LF; + } + } + } + else { + if (code < 0xd) { + // Cc [2] .. + if (0xb <= code && code <= 0xc) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0xe) { + // Cc + if (0xd === code) { + return boundaries_1.CLUSTER_BREAK.CR; + } + } + else { + // Cc [18] .. + if (0xe <= code && code <= 0x1f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + } + } + else { + if (code < 0x300) { + if (code < 0xad) { + // Cc [33] .. + if (0x7f <= code && code <= 0x9f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Cf SOFT HYPHEN + if (0xad === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + else { + if (code < 0x483) { + // Mn [112] COMBINING GRAVE ACCENT..COMBINING LATIN SMALL LETTER X + if (0x300 <= code && code <= 0x36f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x591) { + // Mn [5] COMBINING CYRILLIC TITLO..COMBINING CYRILLIC POKRYTIE + // Me [2] COMBINING CYRILLIC HUNDRED THOUSANDS SIGN..COMBINING CYRILLIC MILLIONS SIGN + if (0x483 <= code && code <= 0x489) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [45] HEBREW ACCENT ETNAHTA..HEBREW POINT METEG + if (0x591 <= code && code <= 0x5bd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x610) { + if (code < 0x5c4) { + if (code < 0x5c1) { + // Mn HEBREW POINT RAFE + if (0x5bf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] HEBREW POINT SHIN DOT..HEBREW POINT SIN DOT + if (0x5c1 <= code && code <= 0x5c2) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x5c7) { + // Mn [2] HEBREW MARK UPPER DOT..HEBREW MARK LOWER DOT + if (0x5c4 <= code && code <= 0x5c5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x600) { + // Mn HEBREW POINT QAMATS QATAN + if (0x5c7 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf [6] ARABIC NUMBER SIGN..ARABIC NUMBER MARK ABOVE + if (0x600 <= code && code <= 0x605) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + } + else { + if (code < 0x670) { + if (code < 0x61c) { + // Mn [11] ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM..ARABIC SMALL KASRA + if (0x610 <= code && code <= 0x61a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x64b) { + // Cf ARABIC LETTER MARK + if (0x61c === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Mn [21] ARABIC FATHATAN..ARABIC WAVY HAMZA BELOW + if (0x64b <= code && code <= 0x65f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x6d6) { + // Mn ARABIC LETTER SUPERSCRIPT ALEF + if (0x670 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x6dd) { + // Mn [7] ARABIC SMALL HIGH LIGATURE SAD WITH LAM WITH ALEF MAKSURA..ARABIC SMALL HIGH SEEN + if (0x6d6 <= code && code <= 0x6dc) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf ARABIC END OF AYAH + if (0x6dd === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + } + } + } + else { + if (code < 0x81b) { + if (code < 0x730) { + if (code < 0x6ea) { + if (code < 0x6e7) { + // Mn [6] ARABIC SMALL HIGH ROUNDED ZERO..ARABIC SMALL HIGH MADDA + if (0x6df <= code && code <= 0x6e4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] ARABIC SMALL HIGH YEH..ARABIC SMALL HIGH NOON + if (0x6e7 <= code && code <= 0x6e8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x70f) { + // Mn [4] ARABIC EMPTY CENTRE LOW STOP..ARABIC SMALL LOW MEEM + if (0x6ea <= code && code <= 0x6ed) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf SYRIAC ABBREVIATION MARK + if (0x70f === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + // Mn SYRIAC LETTER SUPERSCRIPT ALAPH + if (0x711 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x7eb) { + if (code < 0x7a6) { + // Mn [27] SYRIAC PTHAHA ABOVE..SYRIAC BARREKH + if (0x730 <= code && code <= 0x74a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [11] THAANA ABAFILI..THAANA SUKUN + if (0x7a6 <= code && code <= 0x7b0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x7fd) { + // Mn [9] NKO COMBINING SHORT HIGH TONE..NKO COMBINING DOUBLE DOT ABOVE + if (0x7eb <= code && code <= 0x7f3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x816) { + // Mn NKO DANTAYALAN + if (0x7fd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [4] SAMARITAN MARK IN..SAMARITAN MARK DAGESH + if (0x816 <= code && code <= 0x819) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x898) { + if (code < 0x829) { + if (code < 0x825) { + // Mn [9] SAMARITAN MARK EPENTHETIC YUT..SAMARITAN VOWEL SIGN A + if (0x81b <= code && code <= 0x823) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] SAMARITAN VOWEL SIGN SHORT A..SAMARITAN VOWEL SIGN U + if (0x825 <= code && code <= 0x827) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x859) { + // Mn [5] SAMARITAN VOWEL SIGN LONG I..SAMARITAN MARK NEQUDAA + if (0x829 <= code && code <= 0x82d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x890) { + // Mn [3] MANDAIC AFFRICATION MARK..MANDAIC GEMINATION MARK + if (0x859 <= code && code <= 0x85b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf [2] ARABIC POUND MARK ABOVE..ARABIC PIASTRE MARK ABOVE + if (0x890 <= code && code <= 0x891) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + } + else { + if (code < 0x8e3) { + if (code < 0x8ca) { + // Mn [8] ARABIC SMALL HIGH WORD AL-JUZ..ARABIC HALF MADDA OVER MADDA + if (0x898 <= code && code <= 0x89f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x8e2) { + // Mn [24] ARABIC SMALL HIGH FARSI YEH..ARABIC SMALL HIGH SIGN SAFHA + if (0x8ca <= code && code <= 0x8e1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf ARABIC DISPUTED END OF AYAH + if (0x8e2 === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + else { + if (code < 0x903) { + // Mn [32] ARABIC TURNED DAMMA BELOW..DEVANAGARI SIGN ANUSVARA + if (0x8e3 <= code && code <= 0x902) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc DEVANAGARI SIGN VISARGA + if (0x903 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn DEVANAGARI VOWEL SIGN OE + if (0x93a === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0xa01) { + if (code < 0x982) { + if (code < 0x94d) { + if (code < 0x93e) { + // Mc DEVANAGARI VOWEL SIGN OOE + if (0x93b === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn DEVANAGARI SIGN NUKTA + if (0x93c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x941) { + // Mc [3] DEVANAGARI VOWEL SIGN AA..DEVANAGARI VOWEL SIGN II + if (0x93e <= code && code <= 0x940) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x949) { + // Mn [8] DEVANAGARI VOWEL SIGN U..DEVANAGARI VOWEL SIGN AI + if (0x941 <= code && code <= 0x948) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [4] DEVANAGARI VOWEL SIGN CANDRA O..DEVANAGARI VOWEL SIGN AU + if (0x949 <= code && code <= 0x94c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x951) { + if (code < 0x94e) { + // Mn DEVANAGARI SIGN VIRAMA + if (0x94d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] DEVANAGARI VOWEL SIGN PRISHTHAMATRA E..DEVANAGARI VOWEL SIGN AW + if (0x94e <= code && code <= 0x94f) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x962) { + // Mn [7] DEVANAGARI STRESS SIGN UDATTA..DEVANAGARI VOWEL SIGN UUE + if (0x951 <= code && code <= 0x957) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x981) { + // Mn [2] DEVANAGARI VOWEL SIGN VOCALIC L..DEVANAGARI VOWEL SIGN VOCALIC LL + if (0x962 <= code && code <= 0x963) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn BENGALI SIGN CANDRABINDU + if (0x981 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x9c7) { + if (code < 0x9be) { + if (code < 0x9bc) { + // Mc [2] BENGALI SIGN ANUSVARA..BENGALI SIGN VISARGA + if (0x982 <= code && code <= 0x983) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BENGALI SIGN NUKTA + if (0x9bc === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x9bf) { + // Mc BENGALI VOWEL SIGN AA + if (0x9be === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x9c1) { + // Mc [2] BENGALI VOWEL SIGN I..BENGALI VOWEL SIGN II + if (0x9bf <= code && code <= 0x9c0) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] BENGALI VOWEL SIGN U..BENGALI VOWEL SIGN VOCALIC RR + if (0x9c1 <= code && code <= 0x9c4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x9d7) { + if (code < 0x9cb) { + // Mc [2] BENGALI VOWEL SIGN E..BENGALI VOWEL SIGN AI + if (0x9c7 <= code && code <= 0x9c8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x9cd) { + // Mc [2] BENGALI VOWEL SIGN O..BENGALI VOWEL SIGN AU + if (0x9cb <= code && code <= 0x9cc) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BENGALI SIGN VIRAMA + if (0x9cd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x9e2) { + // Mc BENGALI AU LENGTH MARK + if (0x9d7 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x9fe) { + // Mn [2] BENGALI VOWEL SIGN VOCALIC L..BENGALI VOWEL SIGN VOCALIC LL + if (0x9e2 <= code && code <= 0x9e3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn BENGALI SANDHI MARK + if (0x9fe === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0xa83) { + if (code < 0xa47) { + if (code < 0xa3c) { + if (code < 0xa03) { + // Mn [2] GURMUKHI SIGN ADAK BINDI..GURMUKHI SIGN BINDI + if (0xa01 <= code && code <= 0xa02) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc GURMUKHI SIGN VISARGA + if (0xa03 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0xa3e) { + // Mn GURMUKHI SIGN NUKTA + if (0xa3c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa41) { + // Mc [3] GURMUKHI VOWEL SIGN AA..GURMUKHI VOWEL SIGN II + if (0xa3e <= code && code <= 0xa40) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] GURMUKHI VOWEL SIGN U..GURMUKHI VOWEL SIGN UU + if (0xa41 <= code && code <= 0xa42) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xa70) { + if (code < 0xa4b) { + // Mn [2] GURMUKHI VOWEL SIGN EE..GURMUKHI VOWEL SIGN AI + if (0xa47 <= code && code <= 0xa48) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa51) { + // Mn [3] GURMUKHI VOWEL SIGN OO..GURMUKHI SIGN VIRAMA + if (0xa4b <= code && code <= 0xa4d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn GURMUKHI SIGN UDAAT + if (0xa51 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xa75) { + // Mn [2] GURMUKHI TIPPI..GURMUKHI ADDAK + if (0xa70 <= code && code <= 0xa71) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa81) { + // Mn GURMUKHI SIGN YAKASH + if (0xa75 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] GUJARATI SIGN CANDRABINDU..GUJARATI SIGN ANUSVARA + if (0xa81 <= code && code <= 0xa82) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xac9) { + if (code < 0xabe) { + // Mc GUJARATI SIGN VISARGA + if (0xa83 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn GUJARATI SIGN NUKTA + if (0xabc === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xac1) { + // Mc [3] GUJARATI VOWEL SIGN AA..GUJARATI VOWEL SIGN II + if (0xabe <= code && code <= 0xac0) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xac7) { + // Mn [5] GUJARATI VOWEL SIGN U..GUJARATI VOWEL SIGN CANDRA E + if (0xac1 <= code && code <= 0xac5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] GUJARATI VOWEL SIGN E..GUJARATI VOWEL SIGN AI + if (0xac7 <= code && code <= 0xac8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xae2) { + if (code < 0xacb) { + // Mc GUJARATI VOWEL SIGN CANDRA O + if (0xac9 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xacd) { + // Mc [2] GUJARATI VOWEL SIGN O..GUJARATI VOWEL SIGN AU + if (0xacb <= code && code <= 0xacc) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn GUJARATI SIGN VIRAMA + if (0xacd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xafa) { + // Mn [2] GUJARATI VOWEL SIGN VOCALIC L..GUJARATI VOWEL SIGN VOCALIC LL + if (0xae2 <= code && code <= 0xae3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xb01) { + // Mn [6] GUJARATI SIGN SUKUN..GUJARATI SIGN TWO-CIRCLE NUKTA ABOVE + if (0xafa <= code && code <= 0xaff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn ORIYA SIGN CANDRABINDU + if (0xb01 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xcf3) { + if (code < 0xc04) { + if (code < 0xb82) { + if (code < 0xb47) { + if (code < 0xb3e) { + if (code < 0xb3c) { + // Mc [2] ORIYA SIGN ANUSVARA..ORIYA SIGN VISARGA + if (0xb02 <= code && code <= 0xb03) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn ORIYA SIGN NUKTA + if (0xb3c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xb40) { + // Mc ORIYA VOWEL SIGN AA + // Mn ORIYA VOWEL SIGN I + if (0xb3e <= code && code <= 0xb3f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xb41) { + // Mc ORIYA VOWEL SIGN II + if (0xb40 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] ORIYA VOWEL SIGN U..ORIYA VOWEL SIGN VOCALIC RR + if (0xb41 <= code && code <= 0xb44) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xb4d) { + if (code < 0xb4b) { + // Mc [2] ORIYA VOWEL SIGN E..ORIYA VOWEL SIGN AI + if (0xb47 <= code && code <= 0xb48) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [2] ORIYA VOWEL SIGN O..ORIYA VOWEL SIGN AU + if (0xb4b <= code && code <= 0xb4c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0xb55) { + // Mn ORIYA SIGN VIRAMA + if (0xb4d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xb62) { + // Mn [2] ORIYA SIGN OVERLINE..ORIYA AI LENGTH MARK + // Mc ORIYA AU LENGTH MARK + if (0xb55 <= code && code <= 0xb57) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] ORIYA VOWEL SIGN VOCALIC L..ORIYA VOWEL SIGN VOCALIC LL + if (0xb62 <= code && code <= 0xb63) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xbc6) { + if (code < 0xbbf) { + // Mn TAMIL SIGN ANUSVARA + if (0xb82 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc TAMIL VOWEL SIGN AA + if (0xbbe === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xbc0) { + // Mc TAMIL VOWEL SIGN I + if (0xbbf === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xbc1) { + // Mn TAMIL VOWEL SIGN II + if (0xbc0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] TAMIL VOWEL SIGN U..TAMIL VOWEL SIGN UU + if (0xbc1 <= code && code <= 0xbc2) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xbd7) { + if (code < 0xbca) { + // Mc [3] TAMIL VOWEL SIGN E..TAMIL VOWEL SIGN AI + if (0xbc6 <= code && code <= 0xbc8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xbcd) { + // Mc [3] TAMIL VOWEL SIGN O..TAMIL VOWEL SIGN AU + if (0xbca <= code && code <= 0xbcc) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn TAMIL SIGN VIRAMA + if (0xbcd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xc00) { + // Mc TAMIL AU LENGTH MARK + if (0xbd7 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xc01) { + // Mn TELUGU SIGN COMBINING CANDRABINDU ABOVE + if (0xc00 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] TELUGU SIGN CANDRABINDU..TELUGU SIGN VISARGA + if (0xc01 <= code && code <= 0xc03) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + else { + if (code < 0xcbe) { + if (code < 0xc4a) { + if (code < 0xc3e) { + // Mn TELUGU SIGN COMBINING ANUSVARA ABOVE + if (0xc04 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn TELUGU SIGN NUKTA + if (0xc3c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xc41) { + // Mn [3] TELUGU VOWEL SIGN AA..TELUGU VOWEL SIGN II + if (0xc3e <= code && code <= 0xc40) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xc46) { + // Mc [4] TELUGU VOWEL SIGN U..TELUGU VOWEL SIGN VOCALIC RR + if (0xc41 <= code && code <= 0xc44) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [3] TELUGU VOWEL SIGN E..TELUGU VOWEL SIGN AI + if (0xc46 <= code && code <= 0xc48) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xc81) { + if (code < 0xc55) { + // Mn [4] TELUGU VOWEL SIGN O..TELUGU SIGN VIRAMA + if (0xc4a <= code && code <= 0xc4d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xc62) { + // Mn [2] TELUGU LENGTH MARK..TELUGU AI LENGTH MARK + if (0xc55 <= code && code <= 0xc56) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] TELUGU VOWEL SIGN VOCALIC L..TELUGU VOWEL SIGN VOCALIC LL + if (0xc62 <= code && code <= 0xc63) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xc82) { + // Mn KANNADA SIGN CANDRABINDU + if (0xc81 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xcbc) { + // Mc [2] KANNADA SIGN ANUSVARA..KANNADA SIGN VISARGA + if (0xc82 <= code && code <= 0xc83) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn KANNADA SIGN NUKTA + if (0xcbc === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xcc6) { + if (code < 0xcc0) { + // Mc KANNADA VOWEL SIGN AA + if (0xcbe === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn KANNADA VOWEL SIGN I + if (0xcbf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xcc2) { + // Mc [2] KANNADA VOWEL SIGN II..KANNADA VOWEL SIGN U + if (0xcc0 <= code && code <= 0xcc1) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xcc3) { + // Mc KANNADA VOWEL SIGN UU + if (0xcc2 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] KANNADA VOWEL SIGN VOCALIC R..KANNADA VOWEL SIGN VOCALIC RR + if (0xcc3 <= code && code <= 0xcc4) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xccc) { + if (code < 0xcc7) { + // Mn KANNADA VOWEL SIGN E + if (0xcc6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xcca) { + // Mc [2] KANNADA VOWEL SIGN EE..KANNADA VOWEL SIGN AI + if (0xcc7 <= code && code <= 0xcc8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [2] KANNADA VOWEL SIGN O..KANNADA VOWEL SIGN OO + if (0xcca <= code && code <= 0xccb) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0xcd5) { + // Mn [2] KANNADA VOWEL SIGN AU..KANNADA SIGN VIRAMA + if (0xccc <= code && code <= 0xccd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xce2) { + // Mc [2] KANNADA LENGTH MARK..KANNADA AI LENGTH MARK + if (0xcd5 <= code && code <= 0xcd6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] KANNADA VOWEL SIGN VOCALIC L..KANNADA VOWEL SIGN VOCALIC LL + if (0xce2 <= code && code <= 0xce3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0xddf) { + if (code < 0xd4e) { + if (code < 0xd3f) { + if (code < 0xd02) { + if (code < 0xd00) { + // Mc KANNADA SIGN COMBINING ANUSVARA ABOVE RIGHT + if (0xcf3 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] MALAYALAM SIGN COMBINING ANUSVARA ABOVE..MALAYALAM SIGN CANDRABINDU + if (0xd00 <= code && code <= 0xd01) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xd3b) { + // Mc [2] MALAYALAM SIGN ANUSVARA..MALAYALAM SIGN VISARGA + if (0xd02 <= code && code <= 0xd03) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xd3e) { + // Mn [2] MALAYALAM SIGN VERTICAL BAR VIRAMA..MALAYALAM SIGN CIRCULAR VIRAMA + if (0xd3b <= code && code <= 0xd3c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc MALAYALAM VOWEL SIGN AA + if (0xd3e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xd46) { + if (code < 0xd41) { + // Mc [2] MALAYALAM VOWEL SIGN I..MALAYALAM VOWEL SIGN II + if (0xd3f <= code && code <= 0xd40) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] MALAYALAM VOWEL SIGN U..MALAYALAM VOWEL SIGN VOCALIC RR + if (0xd41 <= code && code <= 0xd44) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xd4a) { + // Mc [3] MALAYALAM VOWEL SIGN E..MALAYALAM VOWEL SIGN AI + if (0xd46 <= code && code <= 0xd48) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xd4d) { + // Mc [3] MALAYALAM VOWEL SIGN O..MALAYALAM VOWEL SIGN AU + if (0xd4a <= code && code <= 0xd4c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MALAYALAM SIGN VIRAMA + if (0xd4d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xdca) { + if (code < 0xd62) { + // Lo MALAYALAM LETTER DOT REPH + if (0xd4e === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + // Mc MALAYALAM AU LENGTH MARK + if (0xd57 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xd81) { + // Mn [2] MALAYALAM VOWEL SIGN VOCALIC L..MALAYALAM VOWEL SIGN VOCALIC LL + if (0xd62 <= code && code <= 0xd63) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xd82) { + // Mn SINHALA SIGN CANDRABINDU + if (0xd81 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SINHALA SIGN ANUSVARAYA..SINHALA SIGN VISARGAYA + if (0xd82 <= code && code <= 0xd83) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xdd2) { + if (code < 0xdcf) { + // Mn SINHALA SIGN AL-LAKUNA + if (0xdca === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xdd0) { + // Mc SINHALA VOWEL SIGN AELA-PILLA + if (0xdcf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SINHALA VOWEL SIGN KETTI AEDA-PILLA..SINHALA VOWEL SIGN DIGA AEDA-PILLA + if (0xdd0 <= code && code <= 0xdd1) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0xdd6) { + // Mn [3] SINHALA VOWEL SIGN KETTI IS-PILLA..SINHALA VOWEL SIGN KETTI PAA-PILLA + if (0xdd2 <= code && code <= 0xdd4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xdd8) { + // Mn SINHALA VOWEL SIGN DIGA PAA-PILLA + if (0xdd6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [7] SINHALA VOWEL SIGN GAETTA-PILLA..SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA + if (0xdd8 <= code && code <= 0xdde) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + else { + if (code < 0xf35) { + if (code < 0xe47) { + if (code < 0xe31) { + if (code < 0xdf2) { + // Mc SINHALA VOWEL SIGN GAYANUKITTA + if (0xddf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SINHALA VOWEL SIGN DIGA GAETTA-PILLA..SINHALA VOWEL SIGN DIGA GAYANUKITTA + if (0xdf2 <= code && code <= 0xdf3) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0xe33) { + // Mn THAI CHARACTER MAI HAN-AKAT + if (0xe31 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xe34) { + // Lo THAI CHARACTER SARA AM + if (0xe33 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [7] THAI CHARACTER SARA I..THAI CHARACTER PHINTHU + if (0xe34 <= code && code <= 0xe3a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xeb4) { + if (code < 0xeb1) { + // Mn [8] THAI CHARACTER MAITAIKHU..THAI CHARACTER YAMAKKAN + if (0xe47 <= code && code <= 0xe4e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn LAO VOWEL SIGN MAI KAN + if (0xeb1 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Lo LAO VOWEL SIGN AM + if (0xeb3 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0xec8) { + // Mn [9] LAO VOWEL SIGN I..LAO SEMIVOWEL SIGN LO + if (0xeb4 <= code && code <= 0xebc) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xf18) { + // Mn [7] LAO TONE MAI EK..LAO YAMAKKAN + if (0xec8 <= code && code <= 0xece) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] TIBETAN ASTROLOGICAL SIGN -KHYUD PA..TIBETAN ASTROLOGICAL SIGN SDONG TSHUGS + if (0xf18 <= code && code <= 0xf19) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xf7f) { + if (code < 0xf39) { + // Mn TIBETAN MARK NGAS BZUNG NYI ZLA + if (0xf35 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn TIBETAN MARK NGAS BZUNG SGOR RTAGS + if (0xf37 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xf3e) { + // Mn TIBETAN MARK TSA -PHRU + if (0xf39 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xf71) { + // Mc [2] TIBETAN SIGN YAR TSHES..TIBETAN SIGN MAR TSHES + if (0xf3e <= code && code <= 0xf3f) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [14] TIBETAN VOWEL SIGN AA..TIBETAN SIGN RJES SU NGA RO + if (0xf71 <= code && code <= 0xf7e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xf8d) { + if (code < 0xf80) { + // Mc TIBETAN SIGN RNAM BCAD + if (0xf7f === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xf86) { + // Mn [5] TIBETAN VOWEL SIGN REVERSED I..TIBETAN MARK HALANTA + if (0xf80 <= code && code <= 0xf84) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] TIBETAN SIGN LCI RTAGS..TIBETAN SIGN YANG RTAGS + if (0xf86 <= code && code <= 0xf87) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xf99) { + // Mn [11] TIBETAN SUBJOINED SIGN LCE TSA CAN..TIBETAN SUBJOINED LETTER JA + if (0xf8d <= code && code <= 0xf97) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xfc6) { + // Mn [36] TIBETAN SUBJOINED LETTER NYA..TIBETAN SUBJOINED LETTER FIXED-FORM RA + if (0xf99 <= code && code <= 0xfbc) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn TIBETAN SYMBOL PADMA GDAN + if (0xfc6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0x1c24) { + if (code < 0x1930) { + if (code < 0x1732) { + if (code < 0x1082) { + if (code < 0x103d) { + if (code < 0x1032) { + if (code < 0x1031) { + // Mn [4] MYANMAR VOWEL SIGN I..MYANMAR VOWEL SIGN UU + if (0x102d <= code && code <= 0x1030) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc MYANMAR VOWEL SIGN E + if (0x1031 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1039) { + // Mn [6] MYANMAR VOWEL SIGN AI..MYANMAR SIGN DOT BELOW + if (0x1032 <= code && code <= 0x1037) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x103b) { + // Mn [2] MYANMAR SIGN VIRAMA..MYANMAR SIGN ASAT + if (0x1039 <= code && code <= 0x103a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] MYANMAR CONSONANT SIGN MEDIAL YA..MYANMAR CONSONANT SIGN MEDIAL RA + if (0x103b <= code && code <= 0x103c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1058) { + if (code < 0x1056) { + // Mn [2] MYANMAR CONSONANT SIGN MEDIAL WA..MYANMAR CONSONANT SIGN MEDIAL HA + if (0x103d <= code && code <= 0x103e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] MYANMAR VOWEL SIGN VOCALIC R..MYANMAR VOWEL SIGN VOCALIC RR + if (0x1056 <= code && code <= 0x1057) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x105e) { + // Mn [2] MYANMAR VOWEL SIGN VOCALIC L..MYANMAR VOWEL SIGN VOCALIC LL + if (0x1058 <= code && code <= 0x1059) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1071) { + // Mn [3] MYANMAR CONSONANT SIGN MON MEDIAL NA..MYANMAR CONSONANT SIGN MON MEDIAL LA + if (0x105e <= code && code <= 0x1060) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [4] MYANMAR VOWEL SIGN GEBA KAREN I..MYANMAR VOWEL SIGN KAYAH EE + if (0x1071 <= code && code <= 0x1074) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x1100) { + if (code < 0x1085) { + // Mn MYANMAR CONSONANT SIGN SHAN MEDIAL WA + if (0x1082 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc MYANMAR VOWEL SIGN SHAN E + if (0x1084 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x108d) { + // Mn [2] MYANMAR VOWEL SIGN SHAN E ABOVE..MYANMAR VOWEL SIGN SHAN FINAL Y + if (0x1085 <= code && code <= 0x1086) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn MYANMAR SIGN SHAN COUNCIL EMPHATIC TONE + if (0x108d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn MYANMAR VOWEL SIGN AITON AI + if (0x109d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x135d) { + if (code < 0x1160) { + // Lo [96] HANGUL CHOSEONG KIYEOK..HANGUL CHOSEONG FILLER + if (0x1100 <= code && code <= 0x115f) { + return boundaries_1.CLUSTER_BREAK.L; + } + } + else { + if (code < 0x11a8) { + // Lo [72] HANGUL JUNGSEONG FILLER..HANGUL JUNGSEONG O-YAE + if (0x1160 <= code && code <= 0x11a7) { + return boundaries_1.CLUSTER_BREAK.V; + } + } + else { + // Lo [88] HANGUL JONGSEONG KIYEOK..HANGUL JONGSEONG SSANGNIEUN + if (0x11a8 <= code && code <= 0x11ff) { + return boundaries_1.CLUSTER_BREAK.T; + } + } + } + } + else { + if (code < 0x1712) { + // Mn [3] ETHIOPIC COMBINING GEMINATION AND VOWEL LENGTH MARK..ETHIOPIC COMBINING GEMINATION MARK + if (0x135d <= code && code <= 0x135f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1715) { + // Mn [3] TAGALOG VOWEL SIGN I..TAGALOG SIGN VIRAMA + if (0x1712 <= code && code <= 0x1714) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc TAGALOG SIGN PAMUDPOD + if (0x1715 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + else { + if (code < 0x17c9) { + if (code < 0x17b6) { + if (code < 0x1752) { + if (code < 0x1734) { + // Mn [2] HANUNOO VOWEL SIGN I..HANUNOO VOWEL SIGN U + if (0x1732 <= code && code <= 0x1733) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc HANUNOO SIGN PAMUDPOD + if (0x1734 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1772) { + // Mn [2] BUHID VOWEL SIGN I..BUHID VOWEL SIGN U + if (0x1752 <= code && code <= 0x1753) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x17b4) { + // Mn [2] TAGBANWA VOWEL SIGN I..TAGBANWA VOWEL SIGN U + if (0x1772 <= code && code <= 0x1773) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA + if (0x17b4 <= code && code <= 0x17b5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x17be) { + if (code < 0x17b7) { + // Mc KHMER VOWEL SIGN AA + if (0x17b6 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [7] KHMER VOWEL SIGN I..KHMER VOWEL SIGN UA + if (0x17b7 <= code && code <= 0x17bd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x17c6) { + // Mc [8] KHMER VOWEL SIGN OE..KHMER VOWEL SIGN AU + if (0x17be <= code && code <= 0x17c5) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x17c7) { + // Mn KHMER SIGN NIKAHIT + if (0x17c6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] KHMER SIGN REAHMUK..KHMER SIGN YUUKALEAPINTU + if (0x17c7 <= code && code <= 0x17c8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0x1885) { + if (code < 0x180b) { + if (code < 0x17dd) { + // Mn [11] KHMER SIGN MUUSIKATOAN..KHMER SIGN BATHAMASAT + if (0x17c9 <= code && code <= 0x17d3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn KHMER SIGN ATTHACAN + if (0x17dd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x180e) { + // Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE + if (0x180b <= code && code <= 0x180d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf MONGOLIAN VOWEL SEPARATOR + if (0x180e === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + // Mn MONGOLIAN FREE VARIATION SELECTOR FOUR + if (0x180f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1923) { + if (code < 0x18a9) { + // Mn [2] MONGOLIAN LETTER ALI GALI BALUDA..MONGOLIAN LETTER ALI GALI THREE BALUDA + if (0x1885 <= code && code <= 0x1886) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1920) { + // Mn MONGOLIAN LETTER ALI GALI DAGALGA + if (0x18a9 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] LIMBU VOWEL SIGN A..LIMBU VOWEL SIGN U + if (0x1920 <= code && code <= 0x1922) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1927) { + // Mc [4] LIMBU VOWEL SIGN EE..LIMBU VOWEL SIGN AU + if (0x1923 <= code && code <= 0x1926) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1929) { + // Mn [2] LIMBU VOWEL SIGN E..LIMBU VOWEL SIGN O + if (0x1927 <= code && code <= 0x1928) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] LIMBU SUBJOINED LETTER YA..LIMBU SUBJOINED LETTER WA + if (0x1929 <= code && code <= 0x192b) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + } + else { + if (code < 0x1b3b) { + if (code < 0x1a58) { + if (code < 0x1a19) { + if (code < 0x1933) { + if (code < 0x1932) { + // Mc [2] LIMBU SMALL LETTER KA..LIMBU SMALL LETTER NGA + if (0x1930 <= code && code <= 0x1931) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn LIMBU SMALL LETTER ANUSVARA + if (0x1932 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1939) { + // Mc [6] LIMBU SMALL LETTER TA..LIMBU SMALL LETTER LA + if (0x1933 <= code && code <= 0x1938) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1a17) { + // Mn [3] LIMBU SIGN MUKPHRENG..LIMBU SIGN SA-I + if (0x1939 <= code && code <= 0x193b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] BUGINESE VOWEL SIGN I..BUGINESE VOWEL SIGN U + if (0x1a17 <= code && code <= 0x1a18) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1a55) { + if (code < 0x1a1b) { + // Mc [2] BUGINESE VOWEL SIGN E..BUGINESE VOWEL SIGN O + if (0x1a19 <= code && code <= 0x1a1a) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BUGINESE VOWEL SIGN AE + if (0x1a1b === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1a56) { + // Mc TAI THAM CONSONANT SIGN MEDIAL RA + if (0x1a55 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn TAI THAM CONSONANT SIGN MEDIAL LA + if (0x1a56 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc TAI THAM CONSONANT SIGN LA TANG LAI + if (0x1a57 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1a73) { + if (code < 0x1a62) { + if (code < 0x1a60) { + // Mn [7] TAI THAM SIGN MAI KANG LAI..TAI THAM CONSONANT SIGN SA + if (0x1a58 <= code && code <= 0x1a5e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn TAI THAM SIGN SAKOT + if (0x1a60 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1a65) { + // Mn TAI THAM VOWEL SIGN MAI SAT + if (0x1a62 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1a6d) { + // Mn [8] TAI THAM VOWEL SIGN I..TAI THAM VOWEL SIGN OA BELOW + if (0x1a65 <= code && code <= 0x1a6c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [6] TAI THAM VOWEL SIGN OY..TAI THAM VOWEL SIGN THAM AI + if (0x1a6d <= code && code <= 0x1a72) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1b00) { + if (code < 0x1a7f) { + // Mn [10] TAI THAM VOWEL SIGN OA ABOVE..TAI THAM SIGN KHUEN-LUE KARAN + if (0x1a73 <= code && code <= 0x1a7c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1ab0) { + // Mn TAI THAM COMBINING CRYPTOGRAMMIC DOT + if (0x1a7f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [14] COMBINING DOUBLED CIRCUMFLEX ACCENT..COMBINING PARENTHESES BELOW + // Me COMBINING PARENTHESES OVERLAY + // Mn [16] COMBINING LATIN SMALL LETTER W BELOW..COMBINING LATIN SMALL LETTER INSULAR T + if (0x1ab0 <= code && code <= 0x1ace) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1b04) { + // Mn [4] BALINESE SIGN ULU RICEM..BALINESE SIGN SURANG + if (0x1b00 <= code && code <= 0x1b03) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1b34) { + // Mc BALINESE SIGN BISAH + if (0x1b04 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BALINESE SIGN REREKAN + // Mc BALINESE VOWEL SIGN TEDUNG + // Mn [5] BALINESE VOWEL SIGN ULU..BALINESE VOWEL SIGN RA REPA + if (0x1b34 <= code && code <= 0x1b3a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0x1ba8) { + if (code < 0x1b6b) { + if (code < 0x1b3d) { + // Mc BALINESE VOWEL SIGN RA REPA TEDUNG + if (0x1b3b === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn BALINESE VOWEL SIGN LA LENGA + if (0x1b3c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1b42) { + // Mc [5] BALINESE VOWEL SIGN LA LENGA TEDUNG..BALINESE VOWEL SIGN TALING REPA TEDUNG + if (0x1b3d <= code && code <= 0x1b41) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1b43) { + // Mn BALINESE VOWEL SIGN PEPET + if (0x1b42 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] BALINESE VOWEL SIGN PEPET TEDUNG..BALINESE ADEG ADEG + if (0x1b43 <= code && code <= 0x1b44) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1ba1) { + if (code < 0x1b80) { + // Mn [9] BALINESE MUSICAL SYMBOL COMBINING TEGEH..BALINESE MUSICAL SYMBOL COMBINING GONG + if (0x1b6b <= code && code <= 0x1b73) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1b82) { + // Mn [2] SUNDANESE SIGN PANYECEK..SUNDANESE SIGN PANGLAYAR + if (0x1b80 <= code && code <= 0x1b81) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc SUNDANESE SIGN PANGWISAD + if (0x1b82 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1ba2) { + // Mc SUNDANESE CONSONANT SIGN PAMINGKAL + if (0x1ba1 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1ba6) { + // Mn [4] SUNDANESE CONSONANT SIGN PANYAKRA..SUNDANESE VOWEL SIGN PANYUKU + if (0x1ba2 <= code && code <= 0x1ba5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SUNDANESE VOWEL SIGN PANAELAENG..SUNDANESE VOWEL SIGN PANOLONG + if (0x1ba6 <= code && code <= 0x1ba7) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0x1be8) { + if (code < 0x1bab) { + if (code < 0x1baa) { + // Mn [2] SUNDANESE VOWEL SIGN PAMEPET..SUNDANESE VOWEL SIGN PANEULEUNG + if (0x1ba8 <= code && code <= 0x1ba9) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc SUNDANESE SIGN PAMAAEH + if (0x1baa === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1be6) { + // Mn [3] SUNDANESE SIGN VIRAMA..SUNDANESE CONSONANT SIGN PASANGAN WA + if (0x1bab <= code && code <= 0x1bad) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn BATAK SIGN TOMPI + if (0x1be6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc BATAK VOWEL SIGN E + if (0x1be7 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1bee) { + if (code < 0x1bea) { + // Mn [2] BATAK VOWEL SIGN PAKPAK E..BATAK VOWEL SIGN EE + if (0x1be8 <= code && code <= 0x1be9) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1bed) { + // Mc [3] BATAK VOWEL SIGN I..BATAK VOWEL SIGN O + if (0x1bea <= code && code <= 0x1bec) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BATAK VOWEL SIGN KARO O + if (0x1bed === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1bef) { + // Mc BATAK VOWEL SIGN U + if (0x1bee === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1bf2) { + // Mn [3] BATAK VOWEL SIGN U FOR SIMALUNGUN SA..BATAK CONSONANT SIGN H + if (0x1bef <= code && code <= 0x1bf1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] BATAK PANGOLAT..BATAK PANONGONAN + if (0x1bf2 <= code && code <= 0x1bf3) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xa952) { + if (code < 0x2d7f) { + if (code < 0x1cf7) { + if (code < 0x1cd4) { + if (code < 0x1c34) { + if (code < 0x1c2c) { + // Mc [8] LEPCHA SUBJOINED LETTER YA..LEPCHA VOWEL SIGN UU + if (0x1c24 <= code && code <= 0x1c2b) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [8] LEPCHA VOWEL SIGN E..LEPCHA CONSONANT SIGN T + if (0x1c2c <= code && code <= 0x1c33) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1c36) { + // Mc [2] LEPCHA CONSONANT SIGN NYIN-DO..LEPCHA CONSONANT SIGN KANG + if (0x1c34 <= code && code <= 0x1c35) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1cd0) { + // Mn [2] LEPCHA SIGN RAN..LEPCHA SIGN NUKTA + if (0x1c36 <= code && code <= 0x1c37) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] VEDIC TONE KARSHANA..VEDIC TONE PRENKHA + if (0x1cd0 <= code && code <= 0x1cd2) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1ce2) { + if (code < 0x1ce1) { + // Mn [13] VEDIC SIGN YAJURVEDIC MIDLINE SVARITA..VEDIC TONE RIGVEDIC KASHMIRI INDEPENDENT SVARITA + if (0x1cd4 <= code && code <= 0x1ce0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc VEDIC TONE ATHARVAVEDIC INDEPENDENT SVARITA + if (0x1ce1 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1ced) { + // Mn [7] VEDIC SIGN VISARGA SVARITA..VEDIC SIGN VISARGA ANUDATTA WITH TAIL + if (0x1ce2 <= code && code <= 0x1ce8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn VEDIC SIGN TIRYAK + if (0x1ced === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn VEDIC TONE CANDRA ABOVE + if (0x1cf4 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x200d) { + if (code < 0x1dc0) { + if (code < 0x1cf8) { + // Mc VEDIC SIGN ATIKRAMA + if (0x1cf7 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] VEDIC TONE RING ABOVE..VEDIC TONE DOUBLE RING ABOVE + if (0x1cf8 <= code && code <= 0x1cf9) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x200b) { + // Mn [64] COMBINING DOTTED GRAVE ACCENT..COMBINING RIGHT ARROWHEAD AND DOWN ARROWHEAD BELOW + if (0x1dc0 <= code && code <= 0x1dff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf ZERO WIDTH SPACE + if (0x200b === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + // Cf ZERO WIDTH NON-JOINER + if (0x200c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x2060) { + if (code < 0x200e) { + // Cf ZERO WIDTH JOINER + if (0x200d === code) { + return boundaries_1.CLUSTER_BREAK.ZWJ; + } + } + else { + if (code < 0x2028) { + // Cf [2] LEFT-TO-RIGHT MARK..RIGHT-TO-LEFT MARK + if (0x200e <= code && code <= 0x200f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Zl LINE SEPARATOR + // Zp PARAGRAPH SEPARATOR + // Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE + if (0x2028 <= code && code <= 0x202e) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + } + else { + if (code < 0x20d0) { + // Cf [5] WORD JOINER..INVISIBLE PLUS + // Cn + // Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES + if (0x2060 <= code && code <= 0x206f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0x2cef) { + // Mn [13] COMBINING LEFT HARPOON ABOVE..COMBINING FOUR DOTS ABOVE + // Me [4] COMBINING ENCLOSING CIRCLE..COMBINING ENCLOSING CIRCLE BACKSLASH + // Mn COMBINING LEFT RIGHT ARROW ABOVE + // Me [3] COMBINING ENCLOSING SCREEN..COMBINING ENCLOSING UPWARD POINTING TRIANGLE + // Mn [12] COMBINING REVERSE SOLIDUS OVERLAY..COMBINING ASTERISK ABOVE + if (0x20d0 <= code && code <= 0x20f0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] COPTIC COMBINING NI ABOVE..COPTIC COMBINING SPIRITUS LENIS + if (0x2cef <= code && code <= 0x2cf1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0xa823) { + if (code < 0xa674) { + if (code < 0x302a) { + if (code < 0x2de0) { + // Mn TIFINAGH CONSONANT JOINER + if (0x2d7f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [32] COMBINING CYRILLIC LETTER BE..COMBINING CYRILLIC LETTER IOTIFIED BIG YUS + if (0x2de0 <= code && code <= 0x2dff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x3099) { + // Mn [4] IDEOGRAPHIC LEVEL TONE MARK..IDEOGRAPHIC ENTERING TONE MARK + // Mc [2] HANGUL SINGLE DOT TONE MARK..HANGUL DOUBLE DOT TONE MARK + if (0x302a <= code && code <= 0x302f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa66f) { + // Mn [2] COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK..COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK + if (0x3099 <= code && code <= 0x309a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn COMBINING CYRILLIC VZMET + // Me [3] COMBINING CYRILLIC TEN MILLIONS SIGN..COMBINING CYRILLIC THOUSAND MILLIONS SIGN + if (0xa66f <= code && code <= 0xa672) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xa802) { + if (code < 0xa69e) { + // Mn [10] COMBINING CYRILLIC LETTER UKRAINIAN IE..COMBINING CYRILLIC PAYEROK + if (0xa674 <= code && code <= 0xa67d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa6f0) { + // Mn [2] COMBINING CYRILLIC LETTER EF..COMBINING CYRILLIC LETTER IOTIFIED E + if (0xa69e <= code && code <= 0xa69f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] BAMUM COMBINING MARK KOQNDON..BAMUM COMBINING MARK TUKWENTIS + if (0xa6f0 <= code && code <= 0xa6f1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xa806) { + // Mn SYLOTI NAGRI SIGN DVISVARA + if (0xa802 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn SYLOTI NAGRI SIGN HASANTA + if (0xa806 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn SYLOTI NAGRI SIGN ANUSVARA + if (0xa80b === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xa8b4) { + if (code < 0xa827) { + if (code < 0xa825) { + // Mc [2] SYLOTI NAGRI VOWEL SIGN A..SYLOTI NAGRI VOWEL SIGN I + if (0xa823 <= code && code <= 0xa824) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] SYLOTI NAGRI VOWEL SIGN U..SYLOTI NAGRI VOWEL SIGN E + if (0xa825 <= code && code <= 0xa826) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xa82c) { + // Mc SYLOTI NAGRI VOWEL SIGN OO + if (0xa827 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xa880) { + // Mn SYLOTI NAGRI SIGN ALTERNATE HASANTA + if (0xa82c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SAURASHTRA SIGN ANUSVARA..SAURASHTRA SIGN VISARGA + if (0xa880 <= code && code <= 0xa881) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xa8ff) { + if (code < 0xa8c4) { + // Mc [16] SAURASHTRA CONSONANT SIGN HAARU..SAURASHTRA VOWEL SIGN AU + if (0xa8b4 <= code && code <= 0xa8c3) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xa8e0) { + // Mn [2] SAURASHTRA SIGN VIRAMA..SAURASHTRA SIGN CANDRABINDU + if (0xa8c4 <= code && code <= 0xa8c5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [18] COMBINING DEVANAGARI DIGIT ZERO..COMBINING DEVANAGARI SIGN AVAGRAHA + if (0xa8e0 <= code && code <= 0xa8f1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xa926) { + // Mn DEVANAGARI VOWEL SIGN AY + if (0xa8ff === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa947) { + // Mn [8] KAYAH LI VOWEL UE..KAYAH LI TONE CALYA PLOPHU + if (0xa926 <= code && code <= 0xa92d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [11] REJANG VOWEL SIGN I..REJANG CONSONANT SIGN R + if (0xa947 <= code && code <= 0xa951) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0xaab2) { + if (code < 0xa9e5) { + if (code < 0xa9b4) { + if (code < 0xa980) { + if (code < 0xa960) { + // Mc [2] REJANG CONSONANT SIGN H..REJANG VIRAMA + if (0xa952 <= code && code <= 0xa953) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Lo [29] HANGUL CHOSEONG TIKEUT-MIEUM..HANGUL CHOSEONG SSANGYEORINHIEUH + if (0xa960 <= code && code <= 0xa97c) { + return boundaries_1.CLUSTER_BREAK.L; + } + } + } + else { + if (code < 0xa983) { + // Mn [3] JAVANESE SIGN PANYANGGA..JAVANESE SIGN LAYAR + if (0xa980 <= code && code <= 0xa982) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc JAVANESE SIGN WIGNYAN + if (0xa983 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn JAVANESE SIGN CECAK TELU + if (0xa9b3 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xa9ba) { + if (code < 0xa9b6) { + // Mc [2] JAVANESE VOWEL SIGN TARUNG..JAVANESE VOWEL SIGN TOLONG + if (0xa9b4 <= code && code <= 0xa9b5) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] JAVANESE VOWEL SIGN WULU..JAVANESE VOWEL SIGN SUKU MENDUT + if (0xa9b6 <= code && code <= 0xa9b9) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xa9bc) { + // Mc [2] JAVANESE VOWEL SIGN TALING..JAVANESE VOWEL SIGN DIRGA MURE + if (0xa9ba <= code && code <= 0xa9bb) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xa9be) { + // Mn [2] JAVANESE VOWEL SIGN PEPET..JAVANESE CONSONANT SIGN KERET + if (0xa9bc <= code && code <= 0xa9bd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] JAVANESE CONSONANT SIGN PENGKAL..JAVANESE PANGKON + if (0xa9be <= code && code <= 0xa9c0) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0xaa35) { + if (code < 0xaa2f) { + if (code < 0xaa29) { + // Mn MYANMAR SIGN SHAN SAW + if (0xa9e5 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [6] CHAM VOWEL SIGN AA..CHAM VOWEL SIGN OE + if (0xaa29 <= code && code <= 0xaa2e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xaa31) { + // Mc [2] CHAM VOWEL SIGN O..CHAM VOWEL SIGN AI + if (0xaa2f <= code && code <= 0xaa30) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xaa33) { + // Mn [2] CHAM VOWEL SIGN AU..CHAM VOWEL SIGN UE + if (0xaa31 <= code && code <= 0xaa32) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] CHAM CONSONANT SIGN YA..CHAM CONSONANT SIGN RA + if (0xaa33 <= code && code <= 0xaa34) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xaa4d) { + if (code < 0xaa43) { + // Mn [2] CHAM CONSONANT SIGN LA..CHAM CONSONANT SIGN WA + if (0xaa35 <= code && code <= 0xaa36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn CHAM CONSONANT SIGN FINAL NG + if (0xaa43 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn CHAM CONSONANT SIGN FINAL M + if (0xaa4c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xaa7c) { + // Mc CHAM CONSONANT SIGN FINAL H + if (0xaa4d === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MYANMAR SIGN TAI LAING TONE-2 + if (0xaa7c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn TAI VIET MAI KANG + if (0xaab0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xabe6) { + if (code < 0xaaec) { + if (code < 0xaabe) { + if (code < 0xaab7) { + // Mn [3] TAI VIET VOWEL I..TAI VIET VOWEL U + if (0xaab2 <= code && code <= 0xaab4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] TAI VIET MAI KHIT..TAI VIET VOWEL IA + if (0xaab7 <= code && code <= 0xaab8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xaac1) { + // Mn [2] TAI VIET VOWEL AM..TAI VIET TONE MAI EK + if (0xaabe <= code && code <= 0xaabf) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn TAI VIET TONE MAI THO + if (0xaac1 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc MEETEI MAYEK VOWEL SIGN II + if (0xaaeb === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0xaaf6) { + if (code < 0xaaee) { + // Mn [2] MEETEI MAYEK VOWEL SIGN UU..MEETEI MAYEK VOWEL SIGN AAI + if (0xaaec <= code && code <= 0xaaed) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xaaf5) { + // Mc [2] MEETEI MAYEK VOWEL SIGN AU..MEETEI MAYEK VOWEL SIGN AAU + if (0xaaee <= code && code <= 0xaaef) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc MEETEI MAYEK VOWEL SIGN VISARGA + if (0xaaf5 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0xabe3) { + // Mn MEETEI MAYEK VIRAMA + if (0xaaf6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xabe5) { + // Mc [2] MEETEI MAYEK VOWEL SIGN ONAP..MEETEI MAYEK VOWEL SIGN INAP + if (0xabe3 <= code && code <= 0xabe4) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MEETEI MAYEK VOWEL SIGN ANAP + if (0xabe5 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xac00) { + if (code < 0xabe9) { + if (code < 0xabe8) { + // Mc [2] MEETEI MAYEK VOWEL SIGN YENAP..MEETEI MAYEK VOWEL SIGN SOUNAP + if (0xabe6 <= code && code <= 0xabe7) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MEETEI MAYEK VOWEL SIGN UNAP + if (0xabe8 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xabec) { + // Mc [2] MEETEI MAYEK VOWEL SIGN CHEINAP..MEETEI MAYEK VOWEL SIGN NUNG + if (0xabe9 <= code && code <= 0xabea) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc MEETEI MAYEK LUM IYEK + if (0xabec === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn MEETEI MAYEK APUN IYEK + if (0xabed === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xac1d) { + if (code < 0xac01) { + // Lo HANGUL SYLLABLE GA + if (0xac00 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xac1c) { + // Lo [27] HANGUL SYLLABLE GAG..HANGUL SYLLABLE GAH + if (0xac01 <= code && code <= 0xac1b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GAE + if (0xac1c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xac38) { + // Lo [27] HANGUL SYLLABLE GAEG..HANGUL SYLLABLE GAEH + if (0xac1d <= code && code <= 0xac37) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xac39) { + // Lo HANGUL SYLLABLE GYA + if (0xac38 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GYAG..HANGUL SYLLABLE GYAH + if (0xac39 <= code && code <= 0xac53) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0xb5a1) { + if (code < 0xb0ed) { + if (code < 0xaea0) { + if (code < 0xad6d) { + if (code < 0xace0) { + if (code < 0xac8d) { + if (code < 0xac70) { + if (code < 0xac55) { + // Lo HANGUL SYLLABLE GYAE + if (0xac54 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GYAEG..HANGUL SYLLABLE GYAEH + if (0xac55 <= code && code <= 0xac6f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xac71) { + // Lo HANGUL SYLLABLE GEO + if (0xac70 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xac8c) { + // Lo [27] HANGUL SYLLABLE GEOG..HANGUL SYLLABLE GEOH + if (0xac71 <= code && code <= 0xac8b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GE + if (0xac8c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xaca9) { + if (code < 0xaca8) { + // Lo [27] HANGUL SYLLABLE GEG..HANGUL SYLLABLE GEH + if (0xac8d <= code && code <= 0xaca7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GYEO + if (0xaca8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xacc4) { + // Lo [27] HANGUL SYLLABLE GYEOG..HANGUL SYLLABLE GYEOH + if (0xaca9 <= code && code <= 0xacc3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xacc5) { + // Lo HANGUL SYLLABLE GYE + if (0xacc4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GYEG..HANGUL SYLLABLE GYEH + if (0xacc5 <= code && code <= 0xacdf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xad19) { + if (code < 0xacfc) { + if (code < 0xace1) { + // Lo HANGUL SYLLABLE GO + if (0xace0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GOG..HANGUL SYLLABLE GOH + if (0xace1 <= code && code <= 0xacfb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xacfd) { + // Lo HANGUL SYLLABLE GWA + if (0xacfc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xad18) { + // Lo [27] HANGUL SYLLABLE GWAG..HANGUL SYLLABLE GWAH + if (0xacfd <= code && code <= 0xad17) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GWAE + if (0xad18 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xad50) { + if (code < 0xad34) { + // Lo [27] HANGUL SYLLABLE GWAEG..HANGUL SYLLABLE GWAEH + if (0xad19 <= code && code <= 0xad33) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xad35) { + // Lo HANGUL SYLLABLE GOE + if (0xad34 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GOEG..HANGUL SYLLABLE GOEH + if (0xad35 <= code && code <= 0xad4f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xad51) { + // Lo HANGUL SYLLABLE GYO + if (0xad50 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xad6c) { + // Lo [27] HANGUL SYLLABLE GYOG..HANGUL SYLLABLE GYOH + if (0xad51 <= code && code <= 0xad6b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GU + if (0xad6c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xadf9) { + if (code < 0xadc0) { + if (code < 0xad89) { + if (code < 0xad88) { + // Lo [27] HANGUL SYLLABLE GUG..HANGUL SYLLABLE GUH + if (0xad6d <= code && code <= 0xad87) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GWEO + if (0xad88 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xada4) { + // Lo [27] HANGUL SYLLABLE GWEOG..HANGUL SYLLABLE GWEOH + if (0xad89 <= code && code <= 0xada3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xada5) { + // Lo HANGUL SYLLABLE GWE + if (0xada4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GWEG..HANGUL SYLLABLE GWEH + if (0xada5 <= code && code <= 0xadbf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xaddc) { + if (code < 0xadc1) { + // Lo HANGUL SYLLABLE GWI + if (0xadc0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GWIG..HANGUL SYLLABLE GWIH + if (0xadc1 <= code && code <= 0xaddb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xaddd) { + // Lo HANGUL SYLLABLE GYU + if (0xaddc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xadf8) { + // Lo [27] HANGUL SYLLABLE GYUG..HANGUL SYLLABLE GYUH + if (0xaddd <= code && code <= 0xadf7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GEU + if (0xadf8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xae4c) { + if (code < 0xae15) { + if (code < 0xae14) { + // Lo [27] HANGUL SYLLABLE GEUG..HANGUL SYLLABLE GEUH + if (0xadf9 <= code && code <= 0xae13) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GYI + if (0xae14 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xae30) { + // Lo [27] HANGUL SYLLABLE GYIG..HANGUL SYLLABLE GYIH + if (0xae15 <= code && code <= 0xae2f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xae31) { + // Lo HANGUL SYLLABLE GI + if (0xae30 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GIG..HANGUL SYLLABLE GIH + if (0xae31 <= code && code <= 0xae4b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xae69) { + if (code < 0xae4d) { + // Lo HANGUL SYLLABLE GGA + if (0xae4c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xae68) { + // Lo [27] HANGUL SYLLABLE GGAG..HANGUL SYLLABLE GGAH + if (0xae4d <= code && code <= 0xae67) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGAE + if (0xae68 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xae84) { + // Lo [27] HANGUL SYLLABLE GGAEG..HANGUL SYLLABLE GGAEH + if (0xae69 <= code && code <= 0xae83) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xae85) { + // Lo HANGUL SYLLABLE GGYA + if (0xae84 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGYAG..HANGUL SYLLABLE GGYAH + if (0xae85 <= code && code <= 0xae9f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xafb9) { + if (code < 0xaf2c) { + if (code < 0xaed9) { + if (code < 0xaebc) { + if (code < 0xaea1) { + // Lo HANGUL SYLLABLE GGYAE + if (0xaea0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGYAEG..HANGUL SYLLABLE GGYAEH + if (0xaea1 <= code && code <= 0xaebb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xaebd) { + // Lo HANGUL SYLLABLE GGEO + if (0xaebc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xaed8) { + // Lo [27] HANGUL SYLLABLE GGEOG..HANGUL SYLLABLE GGEOH + if (0xaebd <= code && code <= 0xaed7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGE + if (0xaed8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xaef5) { + if (code < 0xaef4) { + // Lo [27] HANGUL SYLLABLE GGEG..HANGUL SYLLABLE GGEH + if (0xaed9 <= code && code <= 0xaef3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGYEO + if (0xaef4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xaf10) { + // Lo [27] HANGUL SYLLABLE GGYEOG..HANGUL SYLLABLE GGYEOH + if (0xaef5 <= code && code <= 0xaf0f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xaf11) { + // Lo HANGUL SYLLABLE GGYE + if (0xaf10 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGYEG..HANGUL SYLLABLE GGYEH + if (0xaf11 <= code && code <= 0xaf2b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xaf65) { + if (code < 0xaf48) { + if (code < 0xaf2d) { + // Lo HANGUL SYLLABLE GGO + if (0xaf2c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGOG..HANGUL SYLLABLE GGOH + if (0xaf2d <= code && code <= 0xaf47) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xaf49) { + // Lo HANGUL SYLLABLE GGWA + if (0xaf48 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xaf64) { + // Lo [27] HANGUL SYLLABLE GGWAG..HANGUL SYLLABLE GGWAH + if (0xaf49 <= code && code <= 0xaf63) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGWAE + if (0xaf64 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xaf9c) { + if (code < 0xaf80) { + // Lo [27] HANGUL SYLLABLE GGWAEG..HANGUL SYLLABLE GGWAEH + if (0xaf65 <= code && code <= 0xaf7f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xaf81) { + // Lo HANGUL SYLLABLE GGOE + if (0xaf80 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGOEG..HANGUL SYLLABLE GGOEH + if (0xaf81 <= code && code <= 0xaf9b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xaf9d) { + // Lo HANGUL SYLLABLE GGYO + if (0xaf9c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xafb8) { + // Lo [27] HANGUL SYLLABLE GGYOG..HANGUL SYLLABLE GGYOH + if (0xaf9d <= code && code <= 0xafb7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGU + if (0xafb8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xb060) { + if (code < 0xb00c) { + if (code < 0xafd5) { + if (code < 0xafd4) { + // Lo [27] HANGUL SYLLABLE GGUG..HANGUL SYLLABLE GGUH + if (0xafb9 <= code && code <= 0xafd3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGWEO + if (0xafd4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xaff0) { + // Lo [27] HANGUL SYLLABLE GGWEOG..HANGUL SYLLABLE GGWEOH + if (0xafd5 <= code && code <= 0xafef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xaff1) { + // Lo HANGUL SYLLABLE GGWE + if (0xaff0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGWEG..HANGUL SYLLABLE GGWEH + if (0xaff1 <= code && code <= 0xb00b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb029) { + if (code < 0xb00d) { + // Lo HANGUL SYLLABLE GGWI + if (0xb00c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb028) { + // Lo [27] HANGUL SYLLABLE GGWIG..HANGUL SYLLABLE GGWIH + if (0xb00d <= code && code <= 0xb027) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGYU + if (0xb028 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb044) { + // Lo [27] HANGUL SYLLABLE GGYUG..HANGUL SYLLABLE GGYUH + if (0xb029 <= code && code <= 0xb043) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb045) { + // Lo HANGUL SYLLABLE GGEU + if (0xb044 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGEUG..HANGUL SYLLABLE GGEUH + if (0xb045 <= code && code <= 0xb05f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xb099) { + if (code < 0xb07c) { + if (code < 0xb061) { + // Lo HANGUL SYLLABLE GGYI + if (0xb060 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGYIG..HANGUL SYLLABLE GGYIH + if (0xb061 <= code && code <= 0xb07b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb07d) { + // Lo HANGUL SYLLABLE GGI + if (0xb07c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb098) { + // Lo [27] HANGUL SYLLABLE GGIG..HANGUL SYLLABLE GGIH + if (0xb07d <= code && code <= 0xb097) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NA + if (0xb098 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb0d0) { + if (code < 0xb0b4) { + // Lo [27] HANGUL SYLLABLE NAG..HANGUL SYLLABLE NAH + if (0xb099 <= code && code <= 0xb0b3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb0b5) { + // Lo HANGUL SYLLABLE NAE + if (0xb0b4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NAEG..HANGUL SYLLABLE NAEH + if (0xb0b5 <= code && code <= 0xb0cf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb0d1) { + // Lo HANGUL SYLLABLE NYA + if (0xb0d0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb0ec) { + // Lo [27] HANGUL SYLLABLE NYAG..HANGUL SYLLABLE NYAH + if (0xb0d1 <= code && code <= 0xb0eb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NYAE + if (0xb0ec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xb354) { + if (code < 0xb220) { + if (code < 0xb179) { + if (code < 0xb140) { + if (code < 0xb109) { + if (code < 0xb108) { + // Lo [27] HANGUL SYLLABLE NYAEG..HANGUL SYLLABLE NYAEH + if (0xb0ed <= code && code <= 0xb107) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NEO + if (0xb108 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb124) { + // Lo [27] HANGUL SYLLABLE NEOG..HANGUL SYLLABLE NEOH + if (0xb109 <= code && code <= 0xb123) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb125) { + // Lo HANGUL SYLLABLE NE + if (0xb124 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NEG..HANGUL SYLLABLE NEH + if (0xb125 <= code && code <= 0xb13f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb15c) { + if (code < 0xb141) { + // Lo HANGUL SYLLABLE NYEO + if (0xb140 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NYEOG..HANGUL SYLLABLE NYEOH + if (0xb141 <= code && code <= 0xb15b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb15d) { + // Lo HANGUL SYLLABLE NYE + if (0xb15c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb178) { + // Lo [27] HANGUL SYLLABLE NYEG..HANGUL SYLLABLE NYEH + if (0xb15d <= code && code <= 0xb177) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NO + if (0xb178 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xb1cc) { + if (code < 0xb195) { + if (code < 0xb194) { + // Lo [27] HANGUL SYLLABLE NOG..HANGUL SYLLABLE NOH + if (0xb179 <= code && code <= 0xb193) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NWA + if (0xb194 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb1b0) { + // Lo [27] HANGUL SYLLABLE NWAG..HANGUL SYLLABLE NWAH + if (0xb195 <= code && code <= 0xb1af) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb1b1) { + // Lo HANGUL SYLLABLE NWAE + if (0xb1b0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NWAEG..HANGUL SYLLABLE NWAEH + if (0xb1b1 <= code && code <= 0xb1cb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb1e9) { + if (code < 0xb1cd) { + // Lo HANGUL SYLLABLE NOE + if (0xb1cc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb1e8) { + // Lo [27] HANGUL SYLLABLE NOEG..HANGUL SYLLABLE NOEH + if (0xb1cd <= code && code <= 0xb1e7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NYO + if (0xb1e8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb204) { + // Lo [27] HANGUL SYLLABLE NYOG..HANGUL SYLLABLE NYOH + if (0xb1e9 <= code && code <= 0xb203) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb205) { + // Lo HANGUL SYLLABLE NU + if (0xb204 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NUG..HANGUL SYLLABLE NUH + if (0xb205 <= code && code <= 0xb21f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xb2ad) { + if (code < 0xb259) { + if (code < 0xb23c) { + if (code < 0xb221) { + // Lo HANGUL SYLLABLE NWEO + if (0xb220 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NWEOG..HANGUL SYLLABLE NWEOH + if (0xb221 <= code && code <= 0xb23b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb23d) { + // Lo HANGUL SYLLABLE NWE + if (0xb23c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb258) { + // Lo [27] HANGUL SYLLABLE NWEG..HANGUL SYLLABLE NWEH + if (0xb23d <= code && code <= 0xb257) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NWI + if (0xb258 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb290) { + if (code < 0xb274) { + // Lo [27] HANGUL SYLLABLE NWIG..HANGUL SYLLABLE NWIH + if (0xb259 <= code && code <= 0xb273) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb275) { + // Lo HANGUL SYLLABLE NYU + if (0xb274 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NYUG..HANGUL SYLLABLE NYUH + if (0xb275 <= code && code <= 0xb28f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb291) { + // Lo HANGUL SYLLABLE NEU + if (0xb290 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb2ac) { + // Lo [27] HANGUL SYLLABLE NEUG..HANGUL SYLLABLE NEUH + if (0xb291 <= code && code <= 0xb2ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NYI + if (0xb2ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xb300) { + if (code < 0xb2c9) { + if (code < 0xb2c8) { + // Lo [27] HANGUL SYLLABLE NYIG..HANGUL SYLLABLE NYIH + if (0xb2ad <= code && code <= 0xb2c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NI + if (0xb2c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb2e4) { + // Lo [27] HANGUL SYLLABLE NIG..HANGUL SYLLABLE NIH + if (0xb2c9 <= code && code <= 0xb2e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb2e5) { + // Lo HANGUL SYLLABLE DA + if (0xb2e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DAG..HANGUL SYLLABLE DAH + if (0xb2e5 <= code && code <= 0xb2ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb31d) { + if (code < 0xb301) { + // Lo HANGUL SYLLABLE DAE + if (0xb300 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb31c) { + // Lo [27] HANGUL SYLLABLE DAEG..HANGUL SYLLABLE DAEH + if (0xb301 <= code && code <= 0xb31b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DYA + if (0xb31c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb338) { + // Lo [27] HANGUL SYLLABLE DYAG..HANGUL SYLLABLE DYAH + if (0xb31d <= code && code <= 0xb337) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb339) { + // Lo HANGUL SYLLABLE DYAE + if (0xb338 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DYAEG..HANGUL SYLLABLE DYAEH + if (0xb339 <= code && code <= 0xb353) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xb46d) { + if (code < 0xb3e0) { + if (code < 0xb38d) { + if (code < 0xb370) { + if (code < 0xb355) { + // Lo HANGUL SYLLABLE DEO + if (0xb354 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DEOG..HANGUL SYLLABLE DEOH + if (0xb355 <= code && code <= 0xb36f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb371) { + // Lo HANGUL SYLLABLE DE + if (0xb370 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb38c) { + // Lo [27] HANGUL SYLLABLE DEG..HANGUL SYLLABLE DEH + if (0xb371 <= code && code <= 0xb38b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DYEO + if (0xb38c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb3a9) { + if (code < 0xb3a8) { + // Lo [27] HANGUL SYLLABLE DYEOG..HANGUL SYLLABLE DYEOH + if (0xb38d <= code && code <= 0xb3a7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DYE + if (0xb3a8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb3c4) { + // Lo [27] HANGUL SYLLABLE DYEG..HANGUL SYLLABLE DYEH + if (0xb3a9 <= code && code <= 0xb3c3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb3c5) { + // Lo HANGUL SYLLABLE DO + if (0xb3c4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DOG..HANGUL SYLLABLE DOH + if (0xb3c5 <= code && code <= 0xb3df) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xb419) { + if (code < 0xb3fc) { + if (code < 0xb3e1) { + // Lo HANGUL SYLLABLE DWA + if (0xb3e0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DWAG..HANGUL SYLLABLE DWAH + if (0xb3e1 <= code && code <= 0xb3fb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb3fd) { + // Lo HANGUL SYLLABLE DWAE + if (0xb3fc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb418) { + // Lo [27] HANGUL SYLLABLE DWAEG..HANGUL SYLLABLE DWAEH + if (0xb3fd <= code && code <= 0xb417) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DOE + if (0xb418 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb450) { + if (code < 0xb434) { + // Lo [27] HANGUL SYLLABLE DOEG..HANGUL SYLLABLE DOEH + if (0xb419 <= code && code <= 0xb433) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb435) { + // Lo HANGUL SYLLABLE DYO + if (0xb434 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DYOG..HANGUL SYLLABLE DYOH + if (0xb435 <= code && code <= 0xb44f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb451) { + // Lo HANGUL SYLLABLE DU + if (0xb450 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb46c) { + // Lo [27] HANGUL SYLLABLE DUG..HANGUL SYLLABLE DUH + if (0xb451 <= code && code <= 0xb46b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DWEO + if (0xb46c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xb514) { + if (code < 0xb4c0) { + if (code < 0xb489) { + if (code < 0xb488) { + // Lo [27] HANGUL SYLLABLE DWEOG..HANGUL SYLLABLE DWEOH + if (0xb46d <= code && code <= 0xb487) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DWE + if (0xb488 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb4a4) { + // Lo [27] HANGUL SYLLABLE DWEG..HANGUL SYLLABLE DWEH + if (0xb489 <= code && code <= 0xb4a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb4a5) { + // Lo HANGUL SYLLABLE DWI + if (0xb4a4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DWIG..HANGUL SYLLABLE DWIH + if (0xb4a5 <= code && code <= 0xb4bf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb4dd) { + if (code < 0xb4c1) { + // Lo HANGUL SYLLABLE DYU + if (0xb4c0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb4dc) { + // Lo [27] HANGUL SYLLABLE DYUG..HANGUL SYLLABLE DYUH + if (0xb4c1 <= code && code <= 0xb4db) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DEU + if (0xb4dc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb4f8) { + // Lo [27] HANGUL SYLLABLE DEUG..HANGUL SYLLABLE DEUH + if (0xb4dd <= code && code <= 0xb4f7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb4f9) { + // Lo HANGUL SYLLABLE DYI + if (0xb4f8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DYIG..HANGUL SYLLABLE DYIH + if (0xb4f9 <= code && code <= 0xb513) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xb54d) { + if (code < 0xb530) { + if (code < 0xb515) { + // Lo HANGUL SYLLABLE DI + if (0xb514 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DIG..HANGUL SYLLABLE DIH + if (0xb515 <= code && code <= 0xb52f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb531) { + // Lo HANGUL SYLLABLE DDA + if (0xb530 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb54c) { + // Lo [27] HANGUL SYLLABLE DDAG..HANGUL SYLLABLE DDAH + if (0xb531 <= code && code <= 0xb54b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDAE + if (0xb54c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb584) { + if (code < 0xb568) { + // Lo [27] HANGUL SYLLABLE DDAEG..HANGUL SYLLABLE DDAEH + if (0xb54d <= code && code <= 0xb567) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb569) { + // Lo HANGUL SYLLABLE DDYA + if (0xb568 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDYAG..HANGUL SYLLABLE DDYAH + if (0xb569 <= code && code <= 0xb583) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb585) { + // Lo HANGUL SYLLABLE DDYAE + if (0xb584 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb5a0) { + // Lo [27] HANGUL SYLLABLE DDYAEG..HANGUL SYLLABLE DDYAEH + if (0xb585 <= code && code <= 0xb59f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDEO + if (0xb5a0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0xba55) { + if (code < 0xb808) { + if (code < 0xb6d4) { + if (code < 0xb62d) { + if (code < 0xb5f4) { + if (code < 0xb5bd) { + if (code < 0xb5bc) { + // Lo [27] HANGUL SYLLABLE DDEOG..HANGUL SYLLABLE DDEOH + if (0xb5a1 <= code && code <= 0xb5bb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDE + if (0xb5bc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb5d8) { + // Lo [27] HANGUL SYLLABLE DDEG..HANGUL SYLLABLE DDEH + if (0xb5bd <= code && code <= 0xb5d7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb5d9) { + // Lo HANGUL SYLLABLE DDYEO + if (0xb5d8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDYEOG..HANGUL SYLLABLE DDYEOH + if (0xb5d9 <= code && code <= 0xb5f3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb610) { + if (code < 0xb5f5) { + // Lo HANGUL SYLLABLE DDYE + if (0xb5f4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDYEG..HANGUL SYLLABLE DDYEH + if (0xb5f5 <= code && code <= 0xb60f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb611) { + // Lo HANGUL SYLLABLE DDO + if (0xb610 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb62c) { + // Lo [27] HANGUL SYLLABLE DDOG..HANGUL SYLLABLE DDOH + if (0xb611 <= code && code <= 0xb62b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDWA + if (0xb62c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xb680) { + if (code < 0xb649) { + if (code < 0xb648) { + // Lo [27] HANGUL SYLLABLE DDWAG..HANGUL SYLLABLE DDWAH + if (0xb62d <= code && code <= 0xb647) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDWAE + if (0xb648 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb664) { + // Lo [27] HANGUL SYLLABLE DDWAEG..HANGUL SYLLABLE DDWAEH + if (0xb649 <= code && code <= 0xb663) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb665) { + // Lo HANGUL SYLLABLE DDOE + if (0xb664 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDOEG..HANGUL SYLLABLE DDOEH + if (0xb665 <= code && code <= 0xb67f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb69d) { + if (code < 0xb681) { + // Lo HANGUL SYLLABLE DDYO + if (0xb680 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb69c) { + // Lo [27] HANGUL SYLLABLE DDYOG..HANGUL SYLLABLE DDYOH + if (0xb681 <= code && code <= 0xb69b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDU + if (0xb69c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb6b8) { + // Lo [27] HANGUL SYLLABLE DDUG..HANGUL SYLLABLE DDUH + if (0xb69d <= code && code <= 0xb6b7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb6b9) { + // Lo HANGUL SYLLABLE DDWEO + if (0xb6b8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDWEOG..HANGUL SYLLABLE DDWEOH + if (0xb6b9 <= code && code <= 0xb6d3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xb761) { + if (code < 0xb70d) { + if (code < 0xb6f0) { + if (code < 0xb6d5) { + // Lo HANGUL SYLLABLE DDWE + if (0xb6d4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDWEG..HANGUL SYLLABLE DDWEH + if (0xb6d5 <= code && code <= 0xb6ef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb6f1) { + // Lo HANGUL SYLLABLE DDWI + if (0xb6f0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb70c) { + // Lo [27] HANGUL SYLLABLE DDWIG..HANGUL SYLLABLE DDWIH + if (0xb6f1 <= code && code <= 0xb70b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDYU + if (0xb70c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb744) { + if (code < 0xb728) { + // Lo [27] HANGUL SYLLABLE DDYUG..HANGUL SYLLABLE DDYUH + if (0xb70d <= code && code <= 0xb727) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb729) { + // Lo HANGUL SYLLABLE DDEU + if (0xb728 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDEUG..HANGUL SYLLABLE DDEUH + if (0xb729 <= code && code <= 0xb743) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb745) { + // Lo HANGUL SYLLABLE DDYI + if (0xb744 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb760) { + // Lo [27] HANGUL SYLLABLE DDYIG..HANGUL SYLLABLE DDYIH + if (0xb745 <= code && code <= 0xb75f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDI + if (0xb760 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xb7b4) { + if (code < 0xb77d) { + if (code < 0xb77c) { + // Lo [27] HANGUL SYLLABLE DDIG..HANGUL SYLLABLE DDIH + if (0xb761 <= code && code <= 0xb77b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RA + if (0xb77c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb798) { + // Lo [27] HANGUL SYLLABLE RAG..HANGUL SYLLABLE RAH + if (0xb77d <= code && code <= 0xb797) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb799) { + // Lo HANGUL SYLLABLE RAE + if (0xb798 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RAEG..HANGUL SYLLABLE RAEH + if (0xb799 <= code && code <= 0xb7b3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb7d1) { + if (code < 0xb7b5) { + // Lo HANGUL SYLLABLE RYA + if (0xb7b4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb7d0) { + // Lo [27] HANGUL SYLLABLE RYAG..HANGUL SYLLABLE RYAH + if (0xb7b5 <= code && code <= 0xb7cf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RYAE + if (0xb7d0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb7ec) { + // Lo [27] HANGUL SYLLABLE RYAEG..HANGUL SYLLABLE RYAEH + if (0xb7d1 <= code && code <= 0xb7eb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb7ed) { + // Lo HANGUL SYLLABLE REO + if (0xb7ec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE REOG..HANGUL SYLLABLE REOH + if (0xb7ed <= code && code <= 0xb807) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xb921) { + if (code < 0xb894) { + if (code < 0xb841) { + if (code < 0xb824) { + if (code < 0xb809) { + // Lo HANGUL SYLLABLE RE + if (0xb808 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE REG..HANGUL SYLLABLE REH + if (0xb809 <= code && code <= 0xb823) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb825) { + // Lo HANGUL SYLLABLE RYEO + if (0xb824 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb840) { + // Lo [27] HANGUL SYLLABLE RYEOG..HANGUL SYLLABLE RYEOH + if (0xb825 <= code && code <= 0xb83f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RYE + if (0xb840 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb85d) { + if (code < 0xb85c) { + // Lo [27] HANGUL SYLLABLE RYEG..HANGUL SYLLABLE RYEH + if (0xb841 <= code && code <= 0xb85b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RO + if (0xb85c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb878) { + // Lo [27] HANGUL SYLLABLE ROG..HANGUL SYLLABLE ROH + if (0xb85d <= code && code <= 0xb877) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb879) { + // Lo HANGUL SYLLABLE RWA + if (0xb878 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RWAG..HANGUL SYLLABLE RWAH + if (0xb879 <= code && code <= 0xb893) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xb8cd) { + if (code < 0xb8b0) { + if (code < 0xb895) { + // Lo HANGUL SYLLABLE RWAE + if (0xb894 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RWAEG..HANGUL SYLLABLE RWAEH + if (0xb895 <= code && code <= 0xb8af) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb8b1) { + // Lo HANGUL SYLLABLE ROE + if (0xb8b0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb8cc) { + // Lo [27] HANGUL SYLLABLE ROEG..HANGUL SYLLABLE ROEH + if (0xb8b1 <= code && code <= 0xb8cb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RYO + if (0xb8cc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb904) { + if (code < 0xb8e8) { + // Lo [27] HANGUL SYLLABLE RYOG..HANGUL SYLLABLE RYOH + if (0xb8cd <= code && code <= 0xb8e7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb8e9) { + // Lo HANGUL SYLLABLE RU + if (0xb8e8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RUG..HANGUL SYLLABLE RUH + if (0xb8e9 <= code && code <= 0xb903) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb905) { + // Lo HANGUL SYLLABLE RWEO + if (0xb904 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb920) { + // Lo [27] HANGUL SYLLABLE RWEOG..HANGUL SYLLABLE RWEOH + if (0xb905 <= code && code <= 0xb91f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RWE + if (0xb920 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xb9c8) { + if (code < 0xb974) { + if (code < 0xb93d) { + if (code < 0xb93c) { + // Lo [27] HANGUL SYLLABLE RWEG..HANGUL SYLLABLE RWEH + if (0xb921 <= code && code <= 0xb93b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RWI + if (0xb93c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb958) { + // Lo [27] HANGUL SYLLABLE RWIG..HANGUL SYLLABLE RWIH + if (0xb93d <= code && code <= 0xb957) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb959) { + // Lo HANGUL SYLLABLE RYU + if (0xb958 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RYUG..HANGUL SYLLABLE RYUH + if (0xb959 <= code && code <= 0xb973) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb991) { + if (code < 0xb975) { + // Lo HANGUL SYLLABLE REU + if (0xb974 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb990) { + // Lo [27] HANGUL SYLLABLE REUG..HANGUL SYLLABLE REUH + if (0xb975 <= code && code <= 0xb98f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RYI + if (0xb990 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb9ac) { + // Lo [27] HANGUL SYLLABLE RYIG..HANGUL SYLLABLE RYIH + if (0xb991 <= code && code <= 0xb9ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb9ad) { + // Lo HANGUL SYLLABLE RI + if (0xb9ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RIG..HANGUL SYLLABLE RIH + if (0xb9ad <= code && code <= 0xb9c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xba01) { + if (code < 0xb9e4) { + if (code < 0xb9c9) { + // Lo HANGUL SYLLABLE MA + if (0xb9c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MAG..HANGUL SYLLABLE MAH + if (0xb9c9 <= code && code <= 0xb9e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb9e5) { + // Lo HANGUL SYLLABLE MAE + if (0xb9e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xba00) { + // Lo [27] HANGUL SYLLABLE MAEG..HANGUL SYLLABLE MAEH + if (0xb9e5 <= code && code <= 0xb9ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MYA + if (0xba00 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xba38) { + if (code < 0xba1c) { + // Lo [27] HANGUL SYLLABLE MYAG..HANGUL SYLLABLE MYAH + if (0xba01 <= code && code <= 0xba1b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xba1d) { + // Lo HANGUL SYLLABLE MYAE + if (0xba1c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MYAEG..HANGUL SYLLABLE MYAEH + if (0xba1d <= code && code <= 0xba37) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xba39) { + // Lo HANGUL SYLLABLE MEO + if (0xba38 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xba54) { + // Lo [27] HANGUL SYLLABLE MEOG..HANGUL SYLLABLE MEOH + if (0xba39 <= code && code <= 0xba53) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE ME + if (0xba54 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xbcbc) { + if (code < 0xbb88) { + if (code < 0xbae1) { + if (code < 0xbaa8) { + if (code < 0xba71) { + if (code < 0xba70) { + // Lo [27] HANGUL SYLLABLE MEG..HANGUL SYLLABLE MEH + if (0xba55 <= code && code <= 0xba6f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MYEO + if (0xba70 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xba8c) { + // Lo [27] HANGUL SYLLABLE MYEOG..HANGUL SYLLABLE MYEOH + if (0xba71 <= code && code <= 0xba8b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xba8d) { + // Lo HANGUL SYLLABLE MYE + if (0xba8c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MYEG..HANGUL SYLLABLE MYEH + if (0xba8d <= code && code <= 0xbaa7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbac4) { + if (code < 0xbaa9) { + // Lo HANGUL SYLLABLE MO + if (0xbaa8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MOG..HANGUL SYLLABLE MOH + if (0xbaa9 <= code && code <= 0xbac3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbac5) { + // Lo HANGUL SYLLABLE MWA + if (0xbac4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbae0) { + // Lo [27] HANGUL SYLLABLE MWAG..HANGUL SYLLABLE MWAH + if (0xbac5 <= code && code <= 0xbadf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MWAE + if (0xbae0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xbb34) { + if (code < 0xbafd) { + if (code < 0xbafc) { + // Lo [27] HANGUL SYLLABLE MWAEG..HANGUL SYLLABLE MWAEH + if (0xbae1 <= code && code <= 0xbafb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MOE + if (0xbafc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbb18) { + // Lo [27] HANGUL SYLLABLE MOEG..HANGUL SYLLABLE MOEH + if (0xbafd <= code && code <= 0xbb17) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbb19) { + // Lo HANGUL SYLLABLE MYO + if (0xbb18 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MYOG..HANGUL SYLLABLE MYOH + if (0xbb19 <= code && code <= 0xbb33) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbb51) { + if (code < 0xbb35) { + // Lo HANGUL SYLLABLE MU + if (0xbb34 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbb50) { + // Lo [27] HANGUL SYLLABLE MUG..HANGUL SYLLABLE MUH + if (0xbb35 <= code && code <= 0xbb4f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MWEO + if (0xbb50 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xbb6c) { + // Lo [27] HANGUL SYLLABLE MWEOG..HANGUL SYLLABLE MWEOH + if (0xbb51 <= code && code <= 0xbb6b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbb6d) { + // Lo HANGUL SYLLABLE MWE + if (0xbb6c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MWEG..HANGUL SYLLABLE MWEH + if (0xbb6d <= code && code <= 0xbb87) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xbc15) { + if (code < 0xbbc1) { + if (code < 0xbba4) { + if (code < 0xbb89) { + // Lo HANGUL SYLLABLE MWI + if (0xbb88 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MWIG..HANGUL SYLLABLE MWIH + if (0xbb89 <= code && code <= 0xbba3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbba5) { + // Lo HANGUL SYLLABLE MYU + if (0xbba4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbbc0) { + // Lo [27] HANGUL SYLLABLE MYUG..HANGUL SYLLABLE MYUH + if (0xbba5 <= code && code <= 0xbbbf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MEU + if (0xbbc0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xbbf8) { + if (code < 0xbbdc) { + // Lo [27] HANGUL SYLLABLE MEUG..HANGUL SYLLABLE MEUH + if (0xbbc1 <= code && code <= 0xbbdb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbbdd) { + // Lo HANGUL SYLLABLE MYI + if (0xbbdc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MYIG..HANGUL SYLLABLE MYIH + if (0xbbdd <= code && code <= 0xbbf7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xbbf9) { + // Lo HANGUL SYLLABLE MI + if (0xbbf8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbc14) { + // Lo [27] HANGUL SYLLABLE MIG..HANGUL SYLLABLE MIH + if (0xbbf9 <= code && code <= 0xbc13) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BA + if (0xbc14 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xbc68) { + if (code < 0xbc31) { + if (code < 0xbc30) { + // Lo [27] HANGUL SYLLABLE BAG..HANGUL SYLLABLE BAH + if (0xbc15 <= code && code <= 0xbc2f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BAE + if (0xbc30 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbc4c) { + // Lo [27] HANGUL SYLLABLE BAEG..HANGUL SYLLABLE BAEH + if (0xbc31 <= code && code <= 0xbc4b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbc4d) { + // Lo HANGUL SYLLABLE BYA + if (0xbc4c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BYAG..HANGUL SYLLABLE BYAH + if (0xbc4d <= code && code <= 0xbc67) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbc85) { + if (code < 0xbc69) { + // Lo HANGUL SYLLABLE BYAE + if (0xbc68 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbc84) { + // Lo [27] HANGUL SYLLABLE BYAEG..HANGUL SYLLABLE BYAEH + if (0xbc69 <= code && code <= 0xbc83) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BEO + if (0xbc84 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xbca0) { + // Lo [27] HANGUL SYLLABLE BEOG..HANGUL SYLLABLE BEOH + if (0xbc85 <= code && code <= 0xbc9f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbca1) { + // Lo HANGUL SYLLABLE BE + if (0xbca0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BEG..HANGUL SYLLABLE BEH + if (0xbca1 <= code && code <= 0xbcbb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xbdd5) { + if (code < 0xbd48) { + if (code < 0xbcf5) { + if (code < 0xbcd8) { + if (code < 0xbcbd) { + // Lo HANGUL SYLLABLE BYEO + if (0xbcbc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BYEOG..HANGUL SYLLABLE BYEOH + if (0xbcbd <= code && code <= 0xbcd7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbcd9) { + // Lo HANGUL SYLLABLE BYE + if (0xbcd8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbcf4) { + // Lo [27] HANGUL SYLLABLE BYEG..HANGUL SYLLABLE BYEH + if (0xbcd9 <= code && code <= 0xbcf3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BO + if (0xbcf4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xbd11) { + if (code < 0xbd10) { + // Lo [27] HANGUL SYLLABLE BOG..HANGUL SYLLABLE BOH + if (0xbcf5 <= code && code <= 0xbd0f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BWA + if (0xbd10 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbd2c) { + // Lo [27] HANGUL SYLLABLE BWAG..HANGUL SYLLABLE BWAH + if (0xbd11 <= code && code <= 0xbd2b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbd2d) { + // Lo HANGUL SYLLABLE BWAE + if (0xbd2c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BWAEG..HANGUL SYLLABLE BWAEH + if (0xbd2d <= code && code <= 0xbd47) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xbd81) { + if (code < 0xbd64) { + if (code < 0xbd49) { + // Lo HANGUL SYLLABLE BOE + if (0xbd48 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BOEG..HANGUL SYLLABLE BOEH + if (0xbd49 <= code && code <= 0xbd63) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbd65) { + // Lo HANGUL SYLLABLE BYO + if (0xbd64 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbd80) { + // Lo [27] HANGUL SYLLABLE BYOG..HANGUL SYLLABLE BYOH + if (0xbd65 <= code && code <= 0xbd7f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BU + if (0xbd80 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xbdb8) { + if (code < 0xbd9c) { + // Lo [27] HANGUL SYLLABLE BUG..HANGUL SYLLABLE BUH + if (0xbd81 <= code && code <= 0xbd9b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbd9d) { + // Lo HANGUL SYLLABLE BWEO + if (0xbd9c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BWEOG..HANGUL SYLLABLE BWEOH + if (0xbd9d <= code && code <= 0xbdb7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xbdb9) { + // Lo HANGUL SYLLABLE BWE + if (0xbdb8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbdd4) { + // Lo [27] HANGUL SYLLABLE BWEG..HANGUL SYLLABLE BWEH + if (0xbdb9 <= code && code <= 0xbdd3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BWI + if (0xbdd4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xbe7c) { + if (code < 0xbe28) { + if (code < 0xbdf1) { + if (code < 0xbdf0) { + // Lo [27] HANGUL SYLLABLE BWIG..HANGUL SYLLABLE BWIH + if (0xbdd5 <= code && code <= 0xbdef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BYU + if (0xbdf0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbe0c) { + // Lo [27] HANGUL SYLLABLE BYUG..HANGUL SYLLABLE BYUH + if (0xbdf1 <= code && code <= 0xbe0b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbe0d) { + // Lo HANGUL SYLLABLE BEU + if (0xbe0c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BEUG..HANGUL SYLLABLE BEUH + if (0xbe0d <= code && code <= 0xbe27) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbe45) { + if (code < 0xbe29) { + // Lo HANGUL SYLLABLE BYI + if (0xbe28 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbe44) { + // Lo [27] HANGUL SYLLABLE BYIG..HANGUL SYLLABLE BYIH + if (0xbe29 <= code && code <= 0xbe43) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BI + if (0xbe44 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xbe60) { + // Lo [27] HANGUL SYLLABLE BIG..HANGUL SYLLABLE BIH + if (0xbe45 <= code && code <= 0xbe5f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbe61) { + // Lo HANGUL SYLLABLE BBA + if (0xbe60 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBAG..HANGUL SYLLABLE BBAH + if (0xbe61 <= code && code <= 0xbe7b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xbeb5) { + if (code < 0xbe98) { + if (code < 0xbe7d) { + // Lo HANGUL SYLLABLE BBAE + if (0xbe7c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBAEG..HANGUL SYLLABLE BBAEH + if (0xbe7d <= code && code <= 0xbe97) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbe99) { + // Lo HANGUL SYLLABLE BBYA + if (0xbe98 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbeb4) { + // Lo [27] HANGUL SYLLABLE BBYAG..HANGUL SYLLABLE BBYAH + if (0xbe99 <= code && code <= 0xbeb3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYAE + if (0xbeb4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xbeec) { + if (code < 0xbed0) { + // Lo [27] HANGUL SYLLABLE BBYAEG..HANGUL SYLLABLE BBYAEH + if (0xbeb5 <= code && code <= 0xbecf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbed1) { + // Lo HANGUL SYLLABLE BBEO + if (0xbed0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBEOG..HANGUL SYLLABLE BBEOH + if (0xbed1 <= code && code <= 0xbeeb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xbeed) { + // Lo HANGUL SYLLABLE BBE + if (0xbeec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbf08) { + // Lo [27] HANGUL SYLLABLE BBEG..HANGUL SYLLABLE BBEH + if (0xbeed <= code && code <= 0xbf07) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYEO + if (0xbf08 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0xd1d8) { + if (code < 0xc870) { + if (code < 0xc3bc) { + if (code < 0xc155) { + if (code < 0xc03c) { + if (code < 0xbf95) { + if (code < 0xbf5c) { + if (code < 0xbf25) { + if (code < 0xbf24) { + // Lo [27] HANGUL SYLLABLE BBYEOG..HANGUL SYLLABLE BBYEOH + if (0xbf09 <= code && code <= 0xbf23) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYE + if (0xbf24 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbf40) { + // Lo [27] HANGUL SYLLABLE BBYEG..HANGUL SYLLABLE BBYEH + if (0xbf25 <= code && code <= 0xbf3f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbf41) { + // Lo HANGUL SYLLABLE BBO + if (0xbf40 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBOG..HANGUL SYLLABLE BBOH + if (0xbf41 <= code && code <= 0xbf5b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbf78) { + if (code < 0xbf5d) { + // Lo HANGUL SYLLABLE BBWA + if (0xbf5c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBWAG..HANGUL SYLLABLE BBWAH + if (0xbf5d <= code && code <= 0xbf77) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbf79) { + // Lo HANGUL SYLLABLE BBWAE + if (0xbf78 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbf94) { + // Lo [27] HANGUL SYLLABLE BBWAEG..HANGUL SYLLABLE BBWAEH + if (0xbf79 <= code && code <= 0xbf93) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBOE + if (0xbf94 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xbfe8) { + if (code < 0xbfb1) { + if (code < 0xbfb0) { + // Lo [27] HANGUL SYLLABLE BBOEG..HANGUL SYLLABLE BBOEH + if (0xbf95 <= code && code <= 0xbfaf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYO + if (0xbfb0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbfcc) { + // Lo [27] HANGUL SYLLABLE BBYOG..HANGUL SYLLABLE BBYOH + if (0xbfb1 <= code && code <= 0xbfcb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbfcd) { + // Lo HANGUL SYLLABLE BBU + if (0xbfcc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBUG..HANGUL SYLLABLE BBUH + if (0xbfcd <= code && code <= 0xbfe7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc005) { + if (code < 0xbfe9) { + // Lo HANGUL SYLLABLE BBWEO + if (0xbfe8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc004) { + // Lo [27] HANGUL SYLLABLE BBWEOG..HANGUL SYLLABLE BBWEOH + if (0xbfe9 <= code && code <= 0xc003) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBWE + if (0xc004 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc020) { + // Lo [27] HANGUL SYLLABLE BBWEG..HANGUL SYLLABLE BBWEH + if (0xc005 <= code && code <= 0xc01f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc021) { + // Lo HANGUL SYLLABLE BBWI + if (0xc020 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBWIG..HANGUL SYLLABLE BBWIH + if (0xc021 <= code && code <= 0xc03b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xc0c8) { + if (code < 0xc075) { + if (code < 0xc058) { + if (code < 0xc03d) { + // Lo HANGUL SYLLABLE BBYU + if (0xc03c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBYUG..HANGUL SYLLABLE BBYUH + if (0xc03d <= code && code <= 0xc057) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc059) { + // Lo HANGUL SYLLABLE BBEU + if (0xc058 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc074) { + // Lo [27] HANGUL SYLLABLE BBEUG..HANGUL SYLLABLE BBEUH + if (0xc059 <= code && code <= 0xc073) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYI + if (0xc074 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc091) { + if (code < 0xc090) { + // Lo [27] HANGUL SYLLABLE BBYIG..HANGUL SYLLABLE BBYIH + if (0xc075 <= code && code <= 0xc08f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBI + if (0xc090 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc0ac) { + // Lo [27] HANGUL SYLLABLE BBIG..HANGUL SYLLABLE BBIH + if (0xc091 <= code && code <= 0xc0ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc0ad) { + // Lo HANGUL SYLLABLE SA + if (0xc0ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SAG..HANGUL SYLLABLE SAH + if (0xc0ad <= code && code <= 0xc0c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xc101) { + if (code < 0xc0e4) { + if (code < 0xc0c9) { + // Lo HANGUL SYLLABLE SAE + if (0xc0c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SAEG..HANGUL SYLLABLE SAEH + if (0xc0c9 <= code && code <= 0xc0e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc0e5) { + // Lo HANGUL SYLLABLE SYA + if (0xc0e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc100) { + // Lo [27] HANGUL SYLLABLE SYAG..HANGUL SYLLABLE SYAH + if (0xc0e5 <= code && code <= 0xc0ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYAE + if (0xc100 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc138) { + if (code < 0xc11c) { + // Lo [27] HANGUL SYLLABLE SYAEG..HANGUL SYLLABLE SYAEH + if (0xc101 <= code && code <= 0xc11b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc11d) { + // Lo HANGUL SYLLABLE SEO + if (0xc11c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SEOG..HANGUL SYLLABLE SEOH + if (0xc11d <= code && code <= 0xc137) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc139) { + // Lo HANGUL SYLLABLE SE + if (0xc138 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc154) { + // Lo [27] HANGUL SYLLABLE SEG..HANGUL SYLLABLE SEH + if (0xc139 <= code && code <= 0xc153) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYEO + if (0xc154 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + else { + if (code < 0xc288) { + if (code < 0xc1e1) { + if (code < 0xc1a8) { + if (code < 0xc171) { + if (code < 0xc170) { + // Lo [27] HANGUL SYLLABLE SYEOG..HANGUL SYLLABLE SYEOH + if (0xc155 <= code && code <= 0xc16f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYE + if (0xc170 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc18c) { + // Lo [27] HANGUL SYLLABLE SYEG..HANGUL SYLLABLE SYEH + if (0xc171 <= code && code <= 0xc18b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc18d) { + // Lo HANGUL SYLLABLE SO + if (0xc18c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SOG..HANGUL SYLLABLE SOH + if (0xc18d <= code && code <= 0xc1a7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc1c4) { + if (code < 0xc1a9) { + // Lo HANGUL SYLLABLE SWA + if (0xc1a8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SWAG..HANGUL SYLLABLE SWAH + if (0xc1a9 <= code && code <= 0xc1c3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc1c5) { + // Lo HANGUL SYLLABLE SWAE + if (0xc1c4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc1e0) { + // Lo [27] HANGUL SYLLABLE SWAEG..HANGUL SYLLABLE SWAEH + if (0xc1c5 <= code && code <= 0xc1df) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SOE + if (0xc1e0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xc234) { + if (code < 0xc1fd) { + if (code < 0xc1fc) { + // Lo [27] HANGUL SYLLABLE SOEG..HANGUL SYLLABLE SOEH + if (0xc1e1 <= code && code <= 0xc1fb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYO + if (0xc1fc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc218) { + // Lo [27] HANGUL SYLLABLE SYOG..HANGUL SYLLABLE SYOH + if (0xc1fd <= code && code <= 0xc217) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc219) { + // Lo HANGUL SYLLABLE SU + if (0xc218 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SUG..HANGUL SYLLABLE SUH + if (0xc219 <= code && code <= 0xc233) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc251) { + if (code < 0xc235) { + // Lo HANGUL SYLLABLE SWEO + if (0xc234 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc250) { + // Lo [27] HANGUL SYLLABLE SWEOG..HANGUL SYLLABLE SWEOH + if (0xc235 <= code && code <= 0xc24f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SWE + if (0xc250 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc26c) { + // Lo [27] HANGUL SYLLABLE SWEG..HANGUL SYLLABLE SWEH + if (0xc251 <= code && code <= 0xc26b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc26d) { + // Lo HANGUL SYLLABLE SWI + if (0xc26c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SWIG..HANGUL SYLLABLE SWIH + if (0xc26d <= code && code <= 0xc287) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xc315) { + if (code < 0xc2c1) { + if (code < 0xc2a4) { + if (code < 0xc289) { + // Lo HANGUL SYLLABLE SYU + if (0xc288 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SYUG..HANGUL SYLLABLE SYUH + if (0xc289 <= code && code <= 0xc2a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc2a5) { + // Lo HANGUL SYLLABLE SEU + if (0xc2a4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc2c0) { + // Lo [27] HANGUL SYLLABLE SEUG..HANGUL SYLLABLE SEUH + if (0xc2a5 <= code && code <= 0xc2bf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYI + if (0xc2c0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc2f8) { + if (code < 0xc2dc) { + // Lo [27] HANGUL SYLLABLE SYIG..HANGUL SYLLABLE SYIH + if (0xc2c1 <= code && code <= 0xc2db) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc2dd) { + // Lo HANGUL SYLLABLE SI + if (0xc2dc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SIG..HANGUL SYLLABLE SIH + if (0xc2dd <= code && code <= 0xc2f7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc2f9) { + // Lo HANGUL SYLLABLE SSA + if (0xc2f8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc314) { + // Lo [27] HANGUL SYLLABLE SSAG..HANGUL SYLLABLE SSAH + if (0xc2f9 <= code && code <= 0xc313) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSAE + if (0xc314 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xc368) { + if (code < 0xc331) { + if (code < 0xc330) { + // Lo [27] HANGUL SYLLABLE SSAEG..HANGUL SYLLABLE SSAEH + if (0xc315 <= code && code <= 0xc32f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSYA + if (0xc330 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc34c) { + // Lo [27] HANGUL SYLLABLE SSYAG..HANGUL SYLLABLE SSYAH + if (0xc331 <= code && code <= 0xc34b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc34d) { + // Lo HANGUL SYLLABLE SSYAE + if (0xc34c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYAEG..HANGUL SYLLABLE SSYAEH + if (0xc34d <= code && code <= 0xc367) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc385) { + if (code < 0xc369) { + // Lo HANGUL SYLLABLE SSEO + if (0xc368 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc384) { + // Lo [27] HANGUL SYLLABLE SSEOG..HANGUL SYLLABLE SSEOH + if (0xc369 <= code && code <= 0xc383) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSE + if (0xc384 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc3a0) { + // Lo [27] HANGUL SYLLABLE SSEG..HANGUL SYLLABLE SSEH + if (0xc385 <= code && code <= 0xc39f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc3a1) { + // Lo HANGUL SYLLABLE SSYEO + if (0xc3a0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYEOG..HANGUL SYLLABLE SSYEOH + if (0xc3a1 <= code && code <= 0xc3bb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xc609) { + if (code < 0xc4d5) { + if (code < 0xc448) { + if (code < 0xc3f5) { + if (code < 0xc3d8) { + if (code < 0xc3bd) { + // Lo HANGUL SYLLABLE SSYE + if (0xc3bc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYEG..HANGUL SYLLABLE SSYEH + if (0xc3bd <= code && code <= 0xc3d7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc3d9) { + // Lo HANGUL SYLLABLE SSO + if (0xc3d8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc3f4) { + // Lo [27] HANGUL SYLLABLE SSOG..HANGUL SYLLABLE SSOH + if (0xc3d9 <= code && code <= 0xc3f3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSWA + if (0xc3f4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc411) { + if (code < 0xc410) { + // Lo [27] HANGUL SYLLABLE SSWAG..HANGUL SYLLABLE SSWAH + if (0xc3f5 <= code && code <= 0xc40f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSWAE + if (0xc410 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc42c) { + // Lo [27] HANGUL SYLLABLE SSWAEG..HANGUL SYLLABLE SSWAEH + if (0xc411 <= code && code <= 0xc42b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc42d) { + // Lo HANGUL SYLLABLE SSOE + if (0xc42c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSOEG..HANGUL SYLLABLE SSOEH + if (0xc42d <= code && code <= 0xc447) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xc481) { + if (code < 0xc464) { + if (code < 0xc449) { + // Lo HANGUL SYLLABLE SSYO + if (0xc448 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYOG..HANGUL SYLLABLE SSYOH + if (0xc449 <= code && code <= 0xc463) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc465) { + // Lo HANGUL SYLLABLE SSU + if (0xc464 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc480) { + // Lo [27] HANGUL SYLLABLE SSUG..HANGUL SYLLABLE SSUH + if (0xc465 <= code && code <= 0xc47f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSWEO + if (0xc480 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc4b8) { + if (code < 0xc49c) { + // Lo [27] HANGUL SYLLABLE SSWEOG..HANGUL SYLLABLE SSWEOH + if (0xc481 <= code && code <= 0xc49b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc49d) { + // Lo HANGUL SYLLABLE SSWE + if (0xc49c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSWEG..HANGUL SYLLABLE SSWEH + if (0xc49d <= code && code <= 0xc4b7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc4b9) { + // Lo HANGUL SYLLABLE SSWI + if (0xc4b8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc4d4) { + // Lo [27] HANGUL SYLLABLE SSWIG..HANGUL SYLLABLE SSWIH + if (0xc4b9 <= code && code <= 0xc4d3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSYU + if (0xc4d4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xc57c) { + if (code < 0xc528) { + if (code < 0xc4f1) { + if (code < 0xc4f0) { + // Lo [27] HANGUL SYLLABLE SSYUG..HANGUL SYLLABLE SSYUH + if (0xc4d5 <= code && code <= 0xc4ef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSEU + if (0xc4f0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc50c) { + // Lo [27] HANGUL SYLLABLE SSEUG..HANGUL SYLLABLE SSEUH + if (0xc4f1 <= code && code <= 0xc50b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc50d) { + // Lo HANGUL SYLLABLE SSYI + if (0xc50c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYIG..HANGUL SYLLABLE SSYIH + if (0xc50d <= code && code <= 0xc527) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc545) { + if (code < 0xc529) { + // Lo HANGUL SYLLABLE SSI + if (0xc528 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc544) { + // Lo [27] HANGUL SYLLABLE SSIG..HANGUL SYLLABLE SSIH + if (0xc529 <= code && code <= 0xc543) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE A + if (0xc544 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc560) { + // Lo [27] HANGUL SYLLABLE AG..HANGUL SYLLABLE AH + if (0xc545 <= code && code <= 0xc55f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc561) { + // Lo HANGUL SYLLABLE AE + if (0xc560 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE AEG..HANGUL SYLLABLE AEH + if (0xc561 <= code && code <= 0xc57b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xc5b5) { + if (code < 0xc598) { + if (code < 0xc57d) { + // Lo HANGUL SYLLABLE YA + if (0xc57c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE YAG..HANGUL SYLLABLE YAH + if (0xc57d <= code && code <= 0xc597) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc599) { + // Lo HANGUL SYLLABLE YAE + if (0xc598 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc5b4) { + // Lo [27] HANGUL SYLLABLE YAEG..HANGUL SYLLABLE YAEH + if (0xc599 <= code && code <= 0xc5b3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE EO + if (0xc5b4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc5ec) { + if (code < 0xc5d0) { + // Lo [27] HANGUL SYLLABLE EOG..HANGUL SYLLABLE EOH + if (0xc5b5 <= code && code <= 0xc5cf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc5d1) { + // Lo HANGUL SYLLABLE E + if (0xc5d0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE EG..HANGUL SYLLABLE EH + if (0xc5d1 <= code && code <= 0xc5eb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc5ed) { + // Lo HANGUL SYLLABLE YEO + if (0xc5ec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc608) { + // Lo [27] HANGUL SYLLABLE YEOG..HANGUL SYLLABLE YEOH + if (0xc5ed <= code && code <= 0xc607) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE YE + if (0xc608 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + else { + if (code < 0xc73c) { + if (code < 0xc695) { + if (code < 0xc65c) { + if (code < 0xc625) { + if (code < 0xc624) { + // Lo [27] HANGUL SYLLABLE YEG..HANGUL SYLLABLE YEH + if (0xc609 <= code && code <= 0xc623) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE O + if (0xc624 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc640) { + // Lo [27] HANGUL SYLLABLE OG..HANGUL SYLLABLE OH + if (0xc625 <= code && code <= 0xc63f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc641) { + // Lo HANGUL SYLLABLE WA + if (0xc640 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE WAG..HANGUL SYLLABLE WAH + if (0xc641 <= code && code <= 0xc65b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc678) { + if (code < 0xc65d) { + // Lo HANGUL SYLLABLE WAE + if (0xc65c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE WAEG..HANGUL SYLLABLE WAEH + if (0xc65d <= code && code <= 0xc677) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc679) { + // Lo HANGUL SYLLABLE OE + if (0xc678 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc694) { + // Lo [27] HANGUL SYLLABLE OEG..HANGUL SYLLABLE OEH + if (0xc679 <= code && code <= 0xc693) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE YO + if (0xc694 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xc6e8) { + if (code < 0xc6b1) { + if (code < 0xc6b0) { + // Lo [27] HANGUL SYLLABLE YOG..HANGUL SYLLABLE YOH + if (0xc695 <= code && code <= 0xc6af) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE U + if (0xc6b0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc6cc) { + // Lo [27] HANGUL SYLLABLE UG..HANGUL SYLLABLE UH + if (0xc6b1 <= code && code <= 0xc6cb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc6cd) { + // Lo HANGUL SYLLABLE WEO + if (0xc6cc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE WEOG..HANGUL SYLLABLE WEOH + if (0xc6cd <= code && code <= 0xc6e7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc705) { + if (code < 0xc6e9) { + // Lo HANGUL SYLLABLE WE + if (0xc6e8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc704) { + // Lo [27] HANGUL SYLLABLE WEG..HANGUL SYLLABLE WEH + if (0xc6e9 <= code && code <= 0xc703) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE WI + if (0xc704 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc720) { + // Lo [27] HANGUL SYLLABLE WIG..HANGUL SYLLABLE WIH + if (0xc705 <= code && code <= 0xc71f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc721) { + // Lo HANGUL SYLLABLE YU + if (0xc720 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE YUG..HANGUL SYLLABLE YUH + if (0xc721 <= code && code <= 0xc73b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xc7c9) { + if (code < 0xc775) { + if (code < 0xc758) { + if (code < 0xc73d) { + // Lo HANGUL SYLLABLE EU + if (0xc73c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE EUG..HANGUL SYLLABLE EUH + if (0xc73d <= code && code <= 0xc757) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc759) { + // Lo HANGUL SYLLABLE YI + if (0xc758 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc774) { + // Lo [27] HANGUL SYLLABLE YIG..HANGUL SYLLABLE YIH + if (0xc759 <= code && code <= 0xc773) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE I + if (0xc774 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc7ac) { + if (code < 0xc790) { + // Lo [27] HANGUL SYLLABLE IG..HANGUL SYLLABLE IH + if (0xc775 <= code && code <= 0xc78f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc791) { + // Lo HANGUL SYLLABLE JA + if (0xc790 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JAG..HANGUL SYLLABLE JAH + if (0xc791 <= code && code <= 0xc7ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc7ad) { + // Lo HANGUL SYLLABLE JAE + if (0xc7ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc7c8) { + // Lo [27] HANGUL SYLLABLE JAEG..HANGUL SYLLABLE JAEH + if (0xc7ad <= code && code <= 0xc7c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JYA + if (0xc7c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xc81c) { + if (code < 0xc7e5) { + if (code < 0xc7e4) { + // Lo [27] HANGUL SYLLABLE JYAG..HANGUL SYLLABLE JYAH + if (0xc7c9 <= code && code <= 0xc7e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JYAE + if (0xc7e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc800) { + // Lo [27] HANGUL SYLLABLE JYAEG..HANGUL SYLLABLE JYAEH + if (0xc7e5 <= code && code <= 0xc7ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc801) { + // Lo HANGUL SYLLABLE JEO + if (0xc800 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JEOG..HANGUL SYLLABLE JEOH + if (0xc801 <= code && code <= 0xc81b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc839) { + if (code < 0xc81d) { + // Lo HANGUL SYLLABLE JE + if (0xc81c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc838) { + // Lo [27] HANGUL SYLLABLE JEG..HANGUL SYLLABLE JEH + if (0xc81d <= code && code <= 0xc837) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JYEO + if (0xc838 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc854) { + // Lo [27] HANGUL SYLLABLE JYEOG..HANGUL SYLLABLE JYEOH + if (0xc839 <= code && code <= 0xc853) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc855) { + // Lo HANGUL SYLLABLE JYE + if (0xc854 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JYEG..HANGUL SYLLABLE JYEH + if (0xc855 <= code && code <= 0xc86f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0xcd24) { + if (code < 0xcabd) { + if (code < 0xc989) { + if (code < 0xc8fc) { + if (code < 0xc8a9) { + if (code < 0xc88c) { + if (code < 0xc871) { + // Lo HANGUL SYLLABLE JO + if (0xc870 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JOG..HANGUL SYLLABLE JOH + if (0xc871 <= code && code <= 0xc88b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc88d) { + // Lo HANGUL SYLLABLE JWA + if (0xc88c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc8a8) { + // Lo [27] HANGUL SYLLABLE JWAG..HANGUL SYLLABLE JWAH + if (0xc88d <= code && code <= 0xc8a7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JWAE + if (0xc8a8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc8c5) { + if (code < 0xc8c4) { + // Lo [27] HANGUL SYLLABLE JWAEG..HANGUL SYLLABLE JWAEH + if (0xc8a9 <= code && code <= 0xc8c3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JOE + if (0xc8c4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc8e0) { + // Lo [27] HANGUL SYLLABLE JOEG..HANGUL SYLLABLE JOEH + if (0xc8c5 <= code && code <= 0xc8df) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc8e1) { + // Lo HANGUL SYLLABLE JYO + if (0xc8e0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JYOG..HANGUL SYLLABLE JYOH + if (0xc8e1 <= code && code <= 0xc8fb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xc935) { + if (code < 0xc918) { + if (code < 0xc8fd) { + // Lo HANGUL SYLLABLE JU + if (0xc8fc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JUG..HANGUL SYLLABLE JUH + if (0xc8fd <= code && code <= 0xc917) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc919) { + // Lo HANGUL SYLLABLE JWEO + if (0xc918 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc934) { + // Lo [27] HANGUL SYLLABLE JWEOG..HANGUL SYLLABLE JWEOH + if (0xc919 <= code && code <= 0xc933) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JWE + if (0xc934 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc96c) { + if (code < 0xc950) { + // Lo [27] HANGUL SYLLABLE JWEG..HANGUL SYLLABLE JWEH + if (0xc935 <= code && code <= 0xc94f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc951) { + // Lo HANGUL SYLLABLE JWI + if (0xc950 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JWIG..HANGUL SYLLABLE JWIH + if (0xc951 <= code && code <= 0xc96b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc96d) { + // Lo HANGUL SYLLABLE JYU + if (0xc96c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc988) { + // Lo [27] HANGUL SYLLABLE JYUG..HANGUL SYLLABLE JYUH + if (0xc96d <= code && code <= 0xc987) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JEU + if (0xc988 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xca30) { + if (code < 0xc9dc) { + if (code < 0xc9a5) { + if (code < 0xc9a4) { + // Lo [27] HANGUL SYLLABLE JEUG..HANGUL SYLLABLE JEUH + if (0xc989 <= code && code <= 0xc9a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JYI + if (0xc9a4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc9c0) { + // Lo [27] HANGUL SYLLABLE JYIG..HANGUL SYLLABLE JYIH + if (0xc9a5 <= code && code <= 0xc9bf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc9c1) { + // Lo HANGUL SYLLABLE JI + if (0xc9c0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JIG..HANGUL SYLLABLE JIH + if (0xc9c1 <= code && code <= 0xc9db) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc9f9) { + if (code < 0xc9dd) { + // Lo HANGUL SYLLABLE JJA + if (0xc9dc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc9f8) { + // Lo [27] HANGUL SYLLABLE JJAG..HANGUL SYLLABLE JJAH + if (0xc9dd <= code && code <= 0xc9f7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJAE + if (0xc9f8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xca14) { + // Lo [27] HANGUL SYLLABLE JJAEG..HANGUL SYLLABLE JJAEH + if (0xc9f9 <= code && code <= 0xca13) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xca15) { + // Lo HANGUL SYLLABLE JJYA + if (0xca14 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJYAG..HANGUL SYLLABLE JJYAH + if (0xca15 <= code && code <= 0xca2f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xca69) { + if (code < 0xca4c) { + if (code < 0xca31) { + // Lo HANGUL SYLLABLE JJYAE + if (0xca30 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJYAEG..HANGUL SYLLABLE JJYAEH + if (0xca31 <= code && code <= 0xca4b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xca4d) { + // Lo HANGUL SYLLABLE JJEO + if (0xca4c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xca68) { + // Lo [27] HANGUL SYLLABLE JJEOG..HANGUL SYLLABLE JJEOH + if (0xca4d <= code && code <= 0xca67) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJE + if (0xca68 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xcaa0) { + if (code < 0xca84) { + // Lo [27] HANGUL SYLLABLE JJEG..HANGUL SYLLABLE JJEH + if (0xca69 <= code && code <= 0xca83) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xca85) { + // Lo HANGUL SYLLABLE JJYEO + if (0xca84 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJYEOG..HANGUL SYLLABLE JJYEOH + if (0xca85 <= code && code <= 0xca9f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xcaa1) { + // Lo HANGUL SYLLABLE JJYE + if (0xcaa0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcabc) { + // Lo [27] HANGUL SYLLABLE JJYEG..HANGUL SYLLABLE JJYEH + if (0xcaa1 <= code && code <= 0xcabb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJO + if (0xcabc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + else { + if (code < 0xcbf0) { + if (code < 0xcb49) { + if (code < 0xcb10) { + if (code < 0xcad9) { + if (code < 0xcad8) { + // Lo [27] HANGUL SYLLABLE JJOG..HANGUL SYLLABLE JJOH + if (0xcabd <= code && code <= 0xcad7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJWA + if (0xcad8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xcaf4) { + // Lo [27] HANGUL SYLLABLE JJWAG..HANGUL SYLLABLE JJWAH + if (0xcad9 <= code && code <= 0xcaf3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcaf5) { + // Lo HANGUL SYLLABLE JJWAE + if (0xcaf4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJWAEG..HANGUL SYLLABLE JJWAEH + if (0xcaf5 <= code && code <= 0xcb0f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcb2c) { + if (code < 0xcb11) { + // Lo HANGUL SYLLABLE JJOE + if (0xcb10 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJOEG..HANGUL SYLLABLE JJOEH + if (0xcb11 <= code && code <= 0xcb2b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcb2d) { + // Lo HANGUL SYLLABLE JJYO + if (0xcb2c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcb48) { + // Lo [27] HANGUL SYLLABLE JJYOG..HANGUL SYLLABLE JJYOH + if (0xcb2d <= code && code <= 0xcb47) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJU + if (0xcb48 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xcb9c) { + if (code < 0xcb65) { + if (code < 0xcb64) { + // Lo [27] HANGUL SYLLABLE JJUG..HANGUL SYLLABLE JJUH + if (0xcb49 <= code && code <= 0xcb63) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJWEO + if (0xcb64 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xcb80) { + // Lo [27] HANGUL SYLLABLE JJWEOG..HANGUL SYLLABLE JJWEOH + if (0xcb65 <= code && code <= 0xcb7f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcb81) { + // Lo HANGUL SYLLABLE JJWE + if (0xcb80 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJWEG..HANGUL SYLLABLE JJWEH + if (0xcb81 <= code && code <= 0xcb9b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcbb9) { + if (code < 0xcb9d) { + // Lo HANGUL SYLLABLE JJWI + if (0xcb9c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcbb8) { + // Lo [27] HANGUL SYLLABLE JJWIG..HANGUL SYLLABLE JJWIH + if (0xcb9d <= code && code <= 0xcbb7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJYU + if (0xcbb8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xcbd4) { + // Lo [27] HANGUL SYLLABLE JJYUG..HANGUL SYLLABLE JJYUH + if (0xcbb9 <= code && code <= 0xcbd3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcbd5) { + // Lo HANGUL SYLLABLE JJEU + if (0xcbd4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJEUG..HANGUL SYLLABLE JJEUH + if (0xcbd5 <= code && code <= 0xcbef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xcc7d) { + if (code < 0xcc29) { + if (code < 0xcc0c) { + if (code < 0xcbf1) { + // Lo HANGUL SYLLABLE JJYI + if (0xcbf0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJYIG..HANGUL SYLLABLE JJYIH + if (0xcbf1 <= code && code <= 0xcc0b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcc0d) { + // Lo HANGUL SYLLABLE JJI + if (0xcc0c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcc28) { + // Lo [27] HANGUL SYLLABLE JJIG..HANGUL SYLLABLE JJIH + if (0xcc0d <= code && code <= 0xcc27) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CA + if (0xcc28 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xcc60) { + if (code < 0xcc44) { + // Lo [27] HANGUL SYLLABLE CAG..HANGUL SYLLABLE CAH + if (0xcc29 <= code && code <= 0xcc43) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcc45) { + // Lo HANGUL SYLLABLE CAE + if (0xcc44 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CAEG..HANGUL SYLLABLE CAEH + if (0xcc45 <= code && code <= 0xcc5f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xcc61) { + // Lo HANGUL SYLLABLE CYA + if (0xcc60 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcc7c) { + // Lo [27] HANGUL SYLLABLE CYAG..HANGUL SYLLABLE CYAH + if (0xcc61 <= code && code <= 0xcc7b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CYAE + if (0xcc7c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xccd0) { + if (code < 0xcc99) { + if (code < 0xcc98) { + // Lo [27] HANGUL SYLLABLE CYAEG..HANGUL SYLLABLE CYAEH + if (0xcc7d <= code && code <= 0xcc97) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CEO + if (0xcc98 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xccb4) { + // Lo [27] HANGUL SYLLABLE CEOG..HANGUL SYLLABLE CEOH + if (0xcc99 <= code && code <= 0xccb3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xccb5) { + // Lo HANGUL SYLLABLE CE + if (0xccb4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CEG..HANGUL SYLLABLE CEH + if (0xccb5 <= code && code <= 0xcccf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcced) { + if (code < 0xccd1) { + // Lo HANGUL SYLLABLE CYEO + if (0xccd0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xccec) { + // Lo [27] HANGUL SYLLABLE CYEOG..HANGUL SYLLABLE CYEOH + if (0xccd1 <= code && code <= 0xcceb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CYE + if (0xccec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xcd08) { + // Lo [27] HANGUL SYLLABLE CYEG..HANGUL SYLLABLE CYEH + if (0xcced <= code && code <= 0xcd07) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcd09) { + // Lo HANGUL SYLLABLE CO + if (0xcd08 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE COG..HANGUL SYLLABLE COH + if (0xcd09 <= code && code <= 0xcd23) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xcf71) { + if (code < 0xce3d) { + if (code < 0xcdb0) { + if (code < 0xcd5d) { + if (code < 0xcd40) { + if (code < 0xcd25) { + // Lo HANGUL SYLLABLE CWA + if (0xcd24 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CWAG..HANGUL SYLLABLE CWAH + if (0xcd25 <= code && code <= 0xcd3f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcd41) { + // Lo HANGUL SYLLABLE CWAE + if (0xcd40 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcd5c) { + // Lo [27] HANGUL SYLLABLE CWAEG..HANGUL SYLLABLE CWAEH + if (0xcd41 <= code && code <= 0xcd5b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE COE + if (0xcd5c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xcd79) { + if (code < 0xcd78) { + // Lo [27] HANGUL SYLLABLE COEG..HANGUL SYLLABLE COEH + if (0xcd5d <= code && code <= 0xcd77) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CYO + if (0xcd78 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xcd94) { + // Lo [27] HANGUL SYLLABLE CYOG..HANGUL SYLLABLE CYOH + if (0xcd79 <= code && code <= 0xcd93) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcd95) { + // Lo HANGUL SYLLABLE CU + if (0xcd94 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CUG..HANGUL SYLLABLE CUH + if (0xcd95 <= code && code <= 0xcdaf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xcde9) { + if (code < 0xcdcc) { + if (code < 0xcdb1) { + // Lo HANGUL SYLLABLE CWEO + if (0xcdb0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CWEOG..HANGUL SYLLABLE CWEOH + if (0xcdb1 <= code && code <= 0xcdcb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcdcd) { + // Lo HANGUL SYLLABLE CWE + if (0xcdcc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcde8) { + // Lo [27] HANGUL SYLLABLE CWEG..HANGUL SYLLABLE CWEH + if (0xcdcd <= code && code <= 0xcde7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CWI + if (0xcde8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xce20) { + if (code < 0xce04) { + // Lo [27] HANGUL SYLLABLE CWIG..HANGUL SYLLABLE CWIH + if (0xcde9 <= code && code <= 0xce03) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xce05) { + // Lo HANGUL SYLLABLE CYU + if (0xce04 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CYUG..HANGUL SYLLABLE CYUH + if (0xce05 <= code && code <= 0xce1f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xce21) { + // Lo HANGUL SYLLABLE CEU + if (0xce20 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xce3c) { + // Lo [27] HANGUL SYLLABLE CEUG..HANGUL SYLLABLE CEUH + if (0xce21 <= code && code <= 0xce3b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CYI + if (0xce3c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xcee4) { + if (code < 0xce90) { + if (code < 0xce59) { + if (code < 0xce58) { + // Lo [27] HANGUL SYLLABLE CYIG..HANGUL SYLLABLE CYIH + if (0xce3d <= code && code <= 0xce57) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CI + if (0xce58 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xce74) { + // Lo [27] HANGUL SYLLABLE CIG..HANGUL SYLLABLE CIH + if (0xce59 <= code && code <= 0xce73) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xce75) { + // Lo HANGUL SYLLABLE KA + if (0xce74 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KAG..HANGUL SYLLABLE KAH + if (0xce75 <= code && code <= 0xce8f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcead) { + if (code < 0xce91) { + // Lo HANGUL SYLLABLE KAE + if (0xce90 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xceac) { + // Lo [27] HANGUL SYLLABLE KAEG..HANGUL SYLLABLE KAEH + if (0xce91 <= code && code <= 0xceab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KYA + if (0xceac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xcec8) { + // Lo [27] HANGUL SYLLABLE KYAG..HANGUL SYLLABLE KYAH + if (0xcead <= code && code <= 0xcec7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcec9) { + // Lo HANGUL SYLLABLE KYAE + if (0xcec8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KYAEG..HANGUL SYLLABLE KYAEH + if (0xcec9 <= code && code <= 0xcee3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xcf1d) { + if (code < 0xcf00) { + if (code < 0xcee5) { + // Lo HANGUL SYLLABLE KEO + if (0xcee4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KEOG..HANGUL SYLLABLE KEOH + if (0xcee5 <= code && code <= 0xceff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcf01) { + // Lo HANGUL SYLLABLE KE + if (0xcf00 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcf1c) { + // Lo [27] HANGUL SYLLABLE KEG..HANGUL SYLLABLE KEH + if (0xcf01 <= code && code <= 0xcf1b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KYEO + if (0xcf1c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xcf54) { + if (code < 0xcf38) { + // Lo [27] HANGUL SYLLABLE KYEOG..HANGUL SYLLABLE KYEOH + if (0xcf1d <= code && code <= 0xcf37) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcf39) { + // Lo HANGUL SYLLABLE KYE + if (0xcf38 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KYEG..HANGUL SYLLABLE KYEH + if (0xcf39 <= code && code <= 0xcf53) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xcf55) { + // Lo HANGUL SYLLABLE KO + if (0xcf54 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcf70) { + // Lo [27] HANGUL SYLLABLE KOG..HANGUL SYLLABLE KOH + if (0xcf55 <= code && code <= 0xcf6f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KWA + if (0xcf70 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + else { + if (code < 0xd0a4) { + if (code < 0xcffd) { + if (code < 0xcfc4) { + if (code < 0xcf8d) { + if (code < 0xcf8c) { + // Lo [27] HANGUL SYLLABLE KWAG..HANGUL SYLLABLE KWAH + if (0xcf71 <= code && code <= 0xcf8b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KWAE + if (0xcf8c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xcfa8) { + // Lo [27] HANGUL SYLLABLE KWAEG..HANGUL SYLLABLE KWAEH + if (0xcf8d <= code && code <= 0xcfa7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcfa9) { + // Lo HANGUL SYLLABLE KOE + if (0xcfa8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KOEG..HANGUL SYLLABLE KOEH + if (0xcfa9 <= code && code <= 0xcfc3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcfe0) { + if (code < 0xcfc5) { + // Lo HANGUL SYLLABLE KYO + if (0xcfc4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KYOG..HANGUL SYLLABLE KYOH + if (0xcfc5 <= code && code <= 0xcfdf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcfe1) { + // Lo HANGUL SYLLABLE KU + if (0xcfe0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcffc) { + // Lo [27] HANGUL SYLLABLE KUG..HANGUL SYLLABLE KUH + if (0xcfe1 <= code && code <= 0xcffb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KWEO + if (0xcffc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xd050) { + if (code < 0xd019) { + if (code < 0xd018) { + // Lo [27] HANGUL SYLLABLE KWEOG..HANGUL SYLLABLE KWEOH + if (0xcffd <= code && code <= 0xd017) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KWE + if (0xd018 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd034) { + // Lo [27] HANGUL SYLLABLE KWEG..HANGUL SYLLABLE KWEH + if (0xd019 <= code && code <= 0xd033) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd035) { + // Lo HANGUL SYLLABLE KWI + if (0xd034 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KWIG..HANGUL SYLLABLE KWIH + if (0xd035 <= code && code <= 0xd04f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd06d) { + if (code < 0xd051) { + // Lo HANGUL SYLLABLE KYU + if (0xd050 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd06c) { + // Lo [27] HANGUL SYLLABLE KYUG..HANGUL SYLLABLE KYUH + if (0xd051 <= code && code <= 0xd06b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KEU + if (0xd06c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd088) { + // Lo [27] HANGUL SYLLABLE KEUG..HANGUL SYLLABLE KEUH + if (0xd06d <= code && code <= 0xd087) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd089) { + // Lo HANGUL SYLLABLE KYI + if (0xd088 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KYIG..HANGUL SYLLABLE KYIH + if (0xd089 <= code && code <= 0xd0a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xd131) { + if (code < 0xd0dd) { + if (code < 0xd0c0) { + if (code < 0xd0a5) { + // Lo HANGUL SYLLABLE KI + if (0xd0a4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KIG..HANGUL SYLLABLE KIH + if (0xd0a5 <= code && code <= 0xd0bf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd0c1) { + // Lo HANGUL SYLLABLE TA + if (0xd0c0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd0dc) { + // Lo [27] HANGUL SYLLABLE TAG..HANGUL SYLLABLE TAH + if (0xd0c1 <= code && code <= 0xd0db) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TAE + if (0xd0dc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd114) { + if (code < 0xd0f8) { + // Lo [27] HANGUL SYLLABLE TAEG..HANGUL SYLLABLE TAEH + if (0xd0dd <= code && code <= 0xd0f7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd0f9) { + // Lo HANGUL SYLLABLE TYA + if (0xd0f8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TYAG..HANGUL SYLLABLE TYAH + if (0xd0f9 <= code && code <= 0xd113) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xd115) { + // Lo HANGUL SYLLABLE TYAE + if (0xd114 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd130) { + // Lo [27] HANGUL SYLLABLE TYAEG..HANGUL SYLLABLE TYAEH + if (0xd115 <= code && code <= 0xd12f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TEO + if (0xd130 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xd184) { + if (code < 0xd14d) { + if (code < 0xd14c) { + // Lo [27] HANGUL SYLLABLE TEOG..HANGUL SYLLABLE TEOH + if (0xd131 <= code && code <= 0xd14b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TE + if (0xd14c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd168) { + // Lo [27] HANGUL SYLLABLE TEG..HANGUL SYLLABLE TEH + if (0xd14d <= code && code <= 0xd167) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd169) { + // Lo HANGUL SYLLABLE TYEO + if (0xd168 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TYEOG..HANGUL SYLLABLE TYEOH + if (0xd169 <= code && code <= 0xd183) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd1a1) { + if (code < 0xd185) { + // Lo HANGUL SYLLABLE TYE + if (0xd184 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd1a0) { + // Lo [27] HANGUL SYLLABLE TYEG..HANGUL SYLLABLE TYEH + if (0xd185 <= code && code <= 0xd19f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TO + if (0xd1a0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd1bc) { + // Lo [27] HANGUL SYLLABLE TOG..HANGUL SYLLABLE TOH + if (0xd1a1 <= code && code <= 0xd1bb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd1bd) { + // Lo HANGUL SYLLABLE TWA + if (0xd1bc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TWAG..HANGUL SYLLABLE TWAH + if (0xd1bd <= code && code <= 0xd1d7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0x1133b) { + if (code < 0xd671) { + if (code < 0xd424) { + if (code < 0xd2f1) { + if (code < 0xd264) { + if (code < 0xd211) { + if (code < 0xd1f4) { + if (code < 0xd1d9) { + // Lo HANGUL SYLLABLE TWAE + if (0xd1d8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TWAEG..HANGUL SYLLABLE TWAEH + if (0xd1d9 <= code && code <= 0xd1f3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd1f5) { + // Lo HANGUL SYLLABLE TOE + if (0xd1f4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd210) { + // Lo [27] HANGUL SYLLABLE TOEG..HANGUL SYLLABLE TOEH + if (0xd1f5 <= code && code <= 0xd20f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TYO + if (0xd210 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd22d) { + if (code < 0xd22c) { + // Lo [27] HANGUL SYLLABLE TYOG..HANGUL SYLLABLE TYOH + if (0xd211 <= code && code <= 0xd22b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TU + if (0xd22c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd248) { + // Lo [27] HANGUL SYLLABLE TUG..HANGUL SYLLABLE TUH + if (0xd22d <= code && code <= 0xd247) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd249) { + // Lo HANGUL SYLLABLE TWEO + if (0xd248 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TWEOG..HANGUL SYLLABLE TWEOH + if (0xd249 <= code && code <= 0xd263) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xd29d) { + if (code < 0xd280) { + if (code < 0xd265) { + // Lo HANGUL SYLLABLE TWE + if (0xd264 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TWEG..HANGUL SYLLABLE TWEH + if (0xd265 <= code && code <= 0xd27f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd281) { + // Lo HANGUL SYLLABLE TWI + if (0xd280 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd29c) { + // Lo [27] HANGUL SYLLABLE TWIG..HANGUL SYLLABLE TWIH + if (0xd281 <= code && code <= 0xd29b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TYU + if (0xd29c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd2d4) { + if (code < 0xd2b8) { + // Lo [27] HANGUL SYLLABLE TYUG..HANGUL SYLLABLE TYUH + if (0xd29d <= code && code <= 0xd2b7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd2b9) { + // Lo HANGUL SYLLABLE TEU + if (0xd2b8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TEUG..HANGUL SYLLABLE TEUH + if (0xd2b9 <= code && code <= 0xd2d3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xd2d5) { + // Lo HANGUL SYLLABLE TYI + if (0xd2d4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd2f0) { + // Lo [27] HANGUL SYLLABLE TYIG..HANGUL SYLLABLE TYIH + if (0xd2d5 <= code && code <= 0xd2ef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TI + if (0xd2f0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xd37d) { + if (code < 0xd344) { + if (code < 0xd30d) { + if (code < 0xd30c) { + // Lo [27] HANGUL SYLLABLE TIG..HANGUL SYLLABLE TIH + if (0xd2f1 <= code && code <= 0xd30b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PA + if (0xd30c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd328) { + // Lo [27] HANGUL SYLLABLE PAG..HANGUL SYLLABLE PAH + if (0xd30d <= code && code <= 0xd327) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd329) { + // Lo HANGUL SYLLABLE PAE + if (0xd328 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PAEG..HANGUL SYLLABLE PAEH + if (0xd329 <= code && code <= 0xd343) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd360) { + if (code < 0xd345) { + // Lo HANGUL SYLLABLE PYA + if (0xd344 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PYAG..HANGUL SYLLABLE PYAH + if (0xd345 <= code && code <= 0xd35f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd361) { + // Lo HANGUL SYLLABLE PYAE + if (0xd360 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd37c) { + // Lo [27] HANGUL SYLLABLE PYAEG..HANGUL SYLLABLE PYAEH + if (0xd361 <= code && code <= 0xd37b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PEO + if (0xd37c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xd3d0) { + if (code < 0xd399) { + if (code < 0xd398) { + // Lo [27] HANGUL SYLLABLE PEOG..HANGUL SYLLABLE PEOH + if (0xd37d <= code && code <= 0xd397) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PE + if (0xd398 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd3b4) { + // Lo [27] HANGUL SYLLABLE PEG..HANGUL SYLLABLE PEH + if (0xd399 <= code && code <= 0xd3b3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd3b5) { + // Lo HANGUL SYLLABLE PYEO + if (0xd3b4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PYEOG..HANGUL SYLLABLE PYEOH + if (0xd3b5 <= code && code <= 0xd3cf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd3ed) { + if (code < 0xd3d1) { + // Lo HANGUL SYLLABLE PYE + if (0xd3d0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd3ec) { + // Lo [27] HANGUL SYLLABLE PYEG..HANGUL SYLLABLE PYEH + if (0xd3d1 <= code && code <= 0xd3eb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PO + if (0xd3ec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd408) { + // Lo [27] HANGUL SYLLABLE POG..HANGUL SYLLABLE POH + if (0xd3ed <= code && code <= 0xd407) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd409) { + // Lo HANGUL SYLLABLE PWA + if (0xd408 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PWAG..HANGUL SYLLABLE PWAH + if (0xd409 <= code && code <= 0xd423) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xd53d) { + if (code < 0xd4b0) { + if (code < 0xd45d) { + if (code < 0xd440) { + if (code < 0xd425) { + // Lo HANGUL SYLLABLE PWAE + if (0xd424 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PWAEG..HANGUL SYLLABLE PWAEH + if (0xd425 <= code && code <= 0xd43f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd441) { + // Lo HANGUL SYLLABLE POE + if (0xd440 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd45c) { + // Lo [27] HANGUL SYLLABLE POEG..HANGUL SYLLABLE POEH + if (0xd441 <= code && code <= 0xd45b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PYO + if (0xd45c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd479) { + if (code < 0xd478) { + // Lo [27] HANGUL SYLLABLE PYOG..HANGUL SYLLABLE PYOH + if (0xd45d <= code && code <= 0xd477) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PU + if (0xd478 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd494) { + // Lo [27] HANGUL SYLLABLE PUG..HANGUL SYLLABLE PUH + if (0xd479 <= code && code <= 0xd493) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd495) { + // Lo HANGUL SYLLABLE PWEO + if (0xd494 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PWEOG..HANGUL SYLLABLE PWEOH + if (0xd495 <= code && code <= 0xd4af) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xd4e9) { + if (code < 0xd4cc) { + if (code < 0xd4b1) { + // Lo HANGUL SYLLABLE PWE + if (0xd4b0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PWEG..HANGUL SYLLABLE PWEH + if (0xd4b1 <= code && code <= 0xd4cb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd4cd) { + // Lo HANGUL SYLLABLE PWI + if (0xd4cc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd4e8) { + // Lo [27] HANGUL SYLLABLE PWIG..HANGUL SYLLABLE PWIH + if (0xd4cd <= code && code <= 0xd4e7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PYU + if (0xd4e8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd520) { + if (code < 0xd504) { + // Lo [27] HANGUL SYLLABLE PYUG..HANGUL SYLLABLE PYUH + if (0xd4e9 <= code && code <= 0xd503) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd505) { + // Lo HANGUL SYLLABLE PEU + if (0xd504 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PEUG..HANGUL SYLLABLE PEUH + if (0xd505 <= code && code <= 0xd51f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xd521) { + // Lo HANGUL SYLLABLE PYI + if (0xd520 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd53c) { + // Lo [27] HANGUL SYLLABLE PYIG..HANGUL SYLLABLE PYIH + if (0xd521 <= code && code <= 0xd53b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PI + if (0xd53c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xd5e4) { + if (code < 0xd590) { + if (code < 0xd559) { + if (code < 0xd558) { + // Lo [27] HANGUL SYLLABLE PIG..HANGUL SYLLABLE PIH + if (0xd53d <= code && code <= 0xd557) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HA + if (0xd558 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd574) { + // Lo [27] HANGUL SYLLABLE HAG..HANGUL SYLLABLE HAH + if (0xd559 <= code && code <= 0xd573) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd575) { + // Lo HANGUL SYLLABLE HAE + if (0xd574 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HAEG..HANGUL SYLLABLE HAEH + if (0xd575 <= code && code <= 0xd58f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd5ad) { + if (code < 0xd591) { + // Lo HANGUL SYLLABLE HYA + if (0xd590 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd5ac) { + // Lo [27] HANGUL SYLLABLE HYAG..HANGUL SYLLABLE HYAH + if (0xd591 <= code && code <= 0xd5ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HYAE + if (0xd5ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd5c8) { + // Lo [27] HANGUL SYLLABLE HYAEG..HANGUL SYLLABLE HYAEH + if (0xd5ad <= code && code <= 0xd5c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd5c9) { + // Lo HANGUL SYLLABLE HEO + if (0xd5c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HEOG..HANGUL SYLLABLE HEOH + if (0xd5c9 <= code && code <= 0xd5e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xd61d) { + if (code < 0xd600) { + if (code < 0xd5e5) { + // Lo HANGUL SYLLABLE HE + if (0xd5e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HEG..HANGUL SYLLABLE HEH + if (0xd5e5 <= code && code <= 0xd5ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd601) { + // Lo HANGUL SYLLABLE HYEO + if (0xd600 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd61c) { + // Lo [27] HANGUL SYLLABLE HYEOG..HANGUL SYLLABLE HYEOH + if (0xd601 <= code && code <= 0xd61b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HYE + if (0xd61c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd654) { + if (code < 0xd638) { + // Lo [27] HANGUL SYLLABLE HYEG..HANGUL SYLLABLE HYEH + if (0xd61d <= code && code <= 0xd637) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd639) { + // Lo HANGUL SYLLABLE HO + if (0xd638 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HOG..HANGUL SYLLABLE HOH + if (0xd639 <= code && code <= 0xd653) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xd655) { + // Lo HANGUL SYLLABLE HWA + if (0xd654 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd670) { + // Lo [27] HANGUL SYLLABLE HWAG..HANGUL SYLLABLE HWAH + if (0xd655 <= code && code <= 0xd66f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HWAE + if (0xd670 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + else { + if (code < 0x11000) { + if (code < 0xd7b0) { + if (code < 0xd6fd) { + if (code < 0xd6c4) { + if (code < 0xd68d) { + if (code < 0xd68c) { + // Lo [27] HANGUL SYLLABLE HWAEG..HANGUL SYLLABLE HWAEH + if (0xd671 <= code && code <= 0xd68b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HOE + if (0xd68c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd6a8) { + // Lo [27] HANGUL SYLLABLE HOEG..HANGUL SYLLABLE HOEH + if (0xd68d <= code && code <= 0xd6a7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd6a9) { + // Lo HANGUL SYLLABLE HYO + if (0xd6a8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HYOG..HANGUL SYLLABLE HYOH + if (0xd6a9 <= code && code <= 0xd6c3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd6e0) { + if (code < 0xd6c5) { + // Lo HANGUL SYLLABLE HU + if (0xd6c4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HUG..HANGUL SYLLABLE HUH + if (0xd6c5 <= code && code <= 0xd6df) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd6e1) { + // Lo HANGUL SYLLABLE HWEO + if (0xd6e0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd6fc) { + // Lo [27] HANGUL SYLLABLE HWEOG..HANGUL SYLLABLE HWEOH + if (0xd6e1 <= code && code <= 0xd6fb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HWE + if (0xd6fc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xd750) { + if (code < 0xd719) { + if (code < 0xd718) { + // Lo [27] HANGUL SYLLABLE HWEG..HANGUL SYLLABLE HWEH + if (0xd6fd <= code && code <= 0xd717) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HWI + if (0xd718 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd734) { + // Lo [27] HANGUL SYLLABLE HWIG..HANGUL SYLLABLE HWIH + if (0xd719 <= code && code <= 0xd733) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd735) { + // Lo HANGUL SYLLABLE HYU + if (0xd734 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HYUG..HANGUL SYLLABLE HYUH + if (0xd735 <= code && code <= 0xd74f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd76d) { + if (code < 0xd751) { + // Lo HANGUL SYLLABLE HEU + if (0xd750 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd76c) { + // Lo [27] HANGUL SYLLABLE HEUG..HANGUL SYLLABLE HEUH + if (0xd751 <= code && code <= 0xd76b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HYI + if (0xd76c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd788) { + // Lo [27] HANGUL SYLLABLE HYIG..HANGUL SYLLABLE HYIH + if (0xd76d <= code && code <= 0xd787) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd789) { + // Lo HANGUL SYLLABLE HI + if (0xd788 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HIG..HANGUL SYLLABLE HIH + if (0xd789 <= code && code <= 0xd7a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0x10a01) { + if (code < 0xfeff) { + if (code < 0xfb1e) { + if (code < 0xd7cb) { + // Lo [23] HANGUL JUNGSEONG O-YEO..HANGUL JUNGSEONG ARAEA-E + if (0xd7b0 <= code && code <= 0xd7c6) { + return boundaries_1.CLUSTER_BREAK.V; + } + } + else { + // Lo [49] HANGUL JONGSEONG NIEUN-RIEUL..HANGUL JONGSEONG PHIEUPH-THIEUTH + if (0xd7cb <= code && code <= 0xd7fb) { + return boundaries_1.CLUSTER_BREAK.T; + } + } + } + else { + if (code < 0xfe00) { + // Mn HEBREW POINT JUDEO-SPANISH VARIKA + if (0xfb1e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xfe20) { + // Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16 + if (0xfe00 <= code && code <= 0xfe0f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [16] COMBINING LIGATURE LEFT HALF..COMBINING CYRILLIC TITLO RIGHT HALF + if (0xfe20 <= code && code <= 0xfe2f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x101fd) { + if (code < 0xff9e) { + // Cf ZERO WIDTH NO-BREAK SPACE + if (0xfeff === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0xfff0) { + // Lm [2] HALFWIDTH KATAKANA VOICED SOUND MARK..HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK + if (0xff9e <= code && code <= 0xff9f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cn [9] .. + // Cf [3] INTERLINEAR ANNOTATION ANCHOR..INTERLINEAR ANNOTATION TERMINATOR + if (0xfff0 <= code && code <= 0xfffb) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + } + else { + if (code < 0x102e0) { + // Mn PHAISTOS DISC SIGN COMBINING OBLIQUE STROKE + if (0x101fd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x10376) { + // Mn COPTIC EPACT THOUSANDS MARK + if (0x102e0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [5] COMBINING OLD PERMIC LETTER AN..COMBINING OLD PERMIC LETTER SII + if (0x10376 <= code && code <= 0x1037a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x10ae5) { + if (code < 0x10a0c) { + if (code < 0x10a05) { + // Mn [3] KHAROSHTHI VOWEL SIGN I..KHAROSHTHI VOWEL SIGN VOCALIC R + if (0x10a01 <= code && code <= 0x10a03) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] KHAROSHTHI VOWEL SIGN E..KHAROSHTHI VOWEL SIGN O + if (0x10a05 <= code && code <= 0x10a06) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x10a38) { + // Mn [4] KHAROSHTHI VOWEL LENGTH MARK..KHAROSHTHI SIGN VISARGA + if (0x10a0c <= code && code <= 0x10a0f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x10a3f) { + // Mn [3] KHAROSHTHI SIGN BAR ABOVE..KHAROSHTHI SIGN DOT BELOW + if (0x10a38 <= code && code <= 0x10a3a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn KHAROSHTHI VIRAMA + if (0x10a3f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x10efd) { + if (code < 0x10d24) { + // Mn [2] MANICHAEAN ABBREVIATION MARK ABOVE..MANICHAEAN ABBREVIATION MARK BELOW + if (0x10ae5 <= code && code <= 0x10ae6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x10eab) { + // Mn [4] HANIFI ROHINGYA SIGN HARBAHAY..HANIFI ROHINGYA SIGN TASSI + if (0x10d24 <= code && code <= 0x10d27) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] YEZIDI COMBINING HAMZA MARK..YEZIDI COMBINING MADDA MARK + if (0x10eab <= code && code <= 0x10eac) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x10f46) { + // Mn [3] ARABIC SMALL LOW WORD SAKTA..ARABIC SMALL LOW WORD MADDA + if (0x10efd <= code && code <= 0x10eff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x10f82) { + // Mn [11] SOGDIAN COMBINING DOT BELOW..SOGDIAN COMBINING STROKE BELOW + if (0x10f46 <= code && code <= 0x10f50) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [4] OLD UYGHUR COMBINING DOT ABOVE..OLD UYGHUR COMBINING TWO DOTS BELOW + if (0x10f82 <= code && code <= 0x10f85) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0x11180) { + if (code < 0x110b7) { + if (code < 0x11073) { + if (code < 0x11002) { + // Mc BRAHMI SIGN CANDRABINDU + if (0x11000 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn BRAHMI SIGN ANUSVARA + if (0x11001 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11038) { + // Mc BRAHMI SIGN VISARGA + if (0x11002 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11070) { + // Mn [15] BRAHMI VOWEL SIGN AA..BRAHMI VIRAMA + if (0x11038 <= code && code <= 0x11046) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn BRAHMI SIGN OLD TAMIL VIRAMA + if (0x11070 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x11082) { + if (code < 0x1107f) { + // Mn [2] BRAHMI VOWEL SIGN OLD TAMIL SHORT E..BRAHMI VOWEL SIGN OLD TAMIL SHORT O + if (0x11073 <= code && code <= 0x11074) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] BRAHMI NUMBER JOINER..KAITHI SIGN ANUSVARA + if (0x1107f <= code && code <= 0x11081) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x110b0) { + // Mc KAITHI SIGN VISARGA + if (0x11082 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x110b3) { + // Mc [3] KAITHI VOWEL SIGN AA..KAITHI VOWEL SIGN II + if (0x110b0 <= code && code <= 0x110b2) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] KAITHI VOWEL SIGN U..KAITHI VOWEL SIGN AI + if (0x110b3 <= code && code <= 0x110b6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11100) { + if (code < 0x110bd) { + if (code < 0x110b9) { + // Mc [2] KAITHI VOWEL SIGN O..KAITHI VOWEL SIGN AU + if (0x110b7 <= code && code <= 0x110b8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] KAITHI SIGN VIRAMA..KAITHI SIGN NUKTA + if (0x110b9 <= code && code <= 0x110ba) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x110c2) { + // Cf KAITHI NUMBER SIGN + if (0x110bd === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + // Mn KAITHI VOWEL SIGN VOCALIC R + if (0x110c2 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Cf KAITHI NUMBER SIGN ABOVE + if (0x110cd === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + else { + if (code < 0x1112d) { + if (code < 0x11127) { + // Mn [3] CHAKMA SIGN CANDRABINDU..CHAKMA SIGN VISARGA + if (0x11100 <= code && code <= 0x11102) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1112c) { + // Mn [5] CHAKMA VOWEL SIGN A..CHAKMA VOWEL SIGN UU + if (0x11127 <= code && code <= 0x1112b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc CHAKMA VOWEL SIGN E + if (0x1112c === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x11145) { + // Mn [8] CHAKMA VOWEL SIGN AI..CHAKMA MAAYYAA + if (0x1112d <= code && code <= 0x11134) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11173) { + // Mc [2] CHAKMA VOWEL SIGN AA..CHAKMA VOWEL SIGN EI + if (0x11145 <= code && code <= 0x11146) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MAHAJANI SIGN NUKTA + if (0x11173 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0x11232) { + if (code < 0x111c2) { + if (code < 0x111b3) { + if (code < 0x11182) { + // Mn [2] SHARADA SIGN CANDRABINDU..SHARADA SIGN ANUSVARA + if (0x11180 <= code && code <= 0x11181) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc SHARADA SIGN VISARGA + if (0x11182 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x111b6) { + // Mc [3] SHARADA VOWEL SIGN AA..SHARADA VOWEL SIGN II + if (0x111b3 <= code && code <= 0x111b5) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x111bf) { + // Mn [9] SHARADA VOWEL SIGN U..SHARADA VOWEL SIGN O + if (0x111b6 <= code && code <= 0x111be) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SHARADA VOWEL SIGN AU..SHARADA SIGN VIRAMA + if (0x111bf <= code && code <= 0x111c0) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x111cf) { + if (code < 0x111c9) { + // Lo [2] SHARADA SIGN JIHVAMULIYA..SHARADA SIGN UPADHMANIYA + if (0x111c2 <= code && code <= 0x111c3) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + if (code < 0x111ce) { + // Mn [4] SHARADA SANDHI MARK..SHARADA EXTRA SHORT VOWEL MARK + if (0x111c9 <= code && code <= 0x111cc) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc SHARADA VOWEL SIGN PRISHTHAMATRA E + if (0x111ce === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1122c) { + // Mn SHARADA SIGN INVERTED CANDRABINDU + if (0x111cf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1122f) { + // Mc [3] KHOJKI VOWEL SIGN AA..KHOJKI VOWEL SIGN II + if (0x1122c <= code && code <= 0x1122e) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [3] KHOJKI VOWEL SIGN U..KHOJKI VOWEL SIGN AI + if (0x1122f <= code && code <= 0x11231) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11241) { + if (code < 0x11235) { + if (code < 0x11234) { + // Mc [2] KHOJKI VOWEL SIGN O..KHOJKI VOWEL SIGN AU + if (0x11232 <= code && code <= 0x11233) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn KHOJKI SIGN ANUSVARA + if (0x11234 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11236) { + // Mc KHOJKI SIGN VIRAMA + if (0x11235 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1123e) { + // Mn [2] KHOJKI SIGN NUKTA..KHOJKI SIGN SHADDA + if (0x11236 <= code && code <= 0x11237) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn KHOJKI SIGN SUKUN + if (0x1123e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x112e3) { + if (code < 0x112df) { + // Mn KHOJKI VOWEL SIGN VOCALIC R + if (0x11241 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x112e0) { + // Mn KHUDAWADI SIGN ANUSVARA + if (0x112df === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] KHUDAWADI VOWEL SIGN AA..KHUDAWADI VOWEL SIGN II + if (0x112e0 <= code && code <= 0x112e2) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x11300) { + // Mn [8] KHUDAWADI VOWEL SIGN U..KHUDAWADI SIGN VIRAMA + if (0x112e3 <= code && code <= 0x112ea) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11302) { + // Mn [2] GRANTHA SIGN COMBINING ANUSVARA ABOVE..GRANTHA SIGN CANDRABINDU + if (0x11300 <= code && code <= 0x11301) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] GRANTHA SIGN ANUSVARA..GRANTHA SIGN VISARGA + if (0x11302 <= code && code <= 0x11303) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0x11a97) { + if (code < 0x116ab) { + if (code < 0x114b9) { + if (code < 0x11370) { + if (code < 0x11347) { + if (code < 0x1133f) { + if (code < 0x1133e) { + // Mn [2] COMBINING BINDU BELOW..GRANTHA SIGN NUKTA + if (0x1133b <= code && code <= 0x1133c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc GRANTHA VOWEL SIGN AA + if (0x1133e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11340) { + // Mc GRANTHA VOWEL SIGN I + if (0x1133f === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11341) { + // Mn GRANTHA VOWEL SIGN II + if (0x11340 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [4] GRANTHA VOWEL SIGN U..GRANTHA VOWEL SIGN VOCALIC RR + if (0x11341 <= code && code <= 0x11344) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x11357) { + if (code < 0x1134b) { + // Mc [2] GRANTHA VOWEL SIGN EE..GRANTHA VOWEL SIGN AI + if (0x11347 <= code && code <= 0x11348) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [3] GRANTHA VOWEL SIGN OO..GRANTHA SIGN VIRAMA + if (0x1134b <= code && code <= 0x1134d) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11362) { + // Mc GRANTHA AU LENGTH MARK + if (0x11357 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11366) { + // Mc [2] GRANTHA VOWEL SIGN VOCALIC L..GRANTHA VOWEL SIGN VOCALIC LL + if (0x11362 <= code && code <= 0x11363) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [7] COMBINING GRANTHA DIGIT ZERO..COMBINING GRANTHA DIGIT SIX + if (0x11366 <= code && code <= 0x1136c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11445) { + if (code < 0x11438) { + if (code < 0x11435) { + // Mn [5] COMBINING GRANTHA LETTER A..COMBINING GRANTHA LETTER PA + if (0x11370 <= code && code <= 0x11374) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] NEWA VOWEL SIGN AA..NEWA VOWEL SIGN II + if (0x11435 <= code && code <= 0x11437) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11440) { + // Mn [8] NEWA VOWEL SIGN U..NEWA VOWEL SIGN AI + if (0x11438 <= code && code <= 0x1143f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11442) { + // Mc [2] NEWA VOWEL SIGN O..NEWA VOWEL SIGN AU + if (0x11440 <= code && code <= 0x11441) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [3] NEWA SIGN VIRAMA..NEWA SIGN ANUSVARA + if (0x11442 <= code && code <= 0x11444) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x114b0) { + if (code < 0x11446) { + // Mc NEWA SIGN VISARGA + if (0x11445 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn NEWA SIGN NUKTA + if (0x11446 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn NEWA SANDHI MARK + if (0x1145e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x114b1) { + // Mc TIRHUTA VOWEL SIGN AA + if (0x114b0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x114b3) { + // Mc [2] TIRHUTA VOWEL SIGN I..TIRHUTA VOWEL SIGN II + if (0x114b1 <= code && code <= 0x114b2) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [6] TIRHUTA VOWEL SIGN U..TIRHUTA VOWEL SIGN VOCALIC LL + if (0x114b3 <= code && code <= 0x114b8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0x115b8) { + if (code < 0x114bf) { + if (code < 0x114bb) { + // Mc TIRHUTA VOWEL SIGN E + if (0x114b9 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn TIRHUTA VOWEL SIGN SHORT E + if (0x114ba === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x114bd) { + // Mc [2] TIRHUTA VOWEL SIGN AI..TIRHUTA VOWEL SIGN O + if (0x114bb <= code && code <= 0x114bc) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc TIRHUTA VOWEL SIGN SHORT O + if (0x114bd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc TIRHUTA VOWEL SIGN AU + if (0x114be === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x115af) { + if (code < 0x114c1) { + // Mn [2] TIRHUTA SIGN CANDRABINDU..TIRHUTA SIGN ANUSVARA + if (0x114bf <= code && code <= 0x114c0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x114c2) { + // Mc TIRHUTA SIGN VISARGA + if (0x114c1 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] TIRHUTA SIGN VIRAMA..TIRHUTA SIGN NUKTA + if (0x114c2 <= code && code <= 0x114c3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x115b0) { + // Mc SIDDHAM VOWEL SIGN AA + if (0x115af === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x115b2) { + // Mc [2] SIDDHAM VOWEL SIGN I..SIDDHAM VOWEL SIGN II + if (0x115b0 <= code && code <= 0x115b1) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] SIDDHAM VOWEL SIGN U..SIDDHAM VOWEL SIGN VOCALIC RR + if (0x115b2 <= code && code <= 0x115b5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11630) { + if (code < 0x115be) { + if (code < 0x115bc) { + // Mc [4] SIDDHAM VOWEL SIGN E..SIDDHAM VOWEL SIGN AU + if (0x115b8 <= code && code <= 0x115bb) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] SIDDHAM SIGN CANDRABINDU..SIDDHAM SIGN ANUSVARA + if (0x115bc <= code && code <= 0x115bd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x115bf) { + // Mc SIDDHAM SIGN VISARGA + if (0x115be === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x115dc) { + // Mn [2] SIDDHAM SIGN VIRAMA..SIDDHAM SIGN NUKTA + if (0x115bf <= code && code <= 0x115c0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] SIDDHAM VOWEL SIGN ALTERNATE U..SIDDHAM VOWEL SIGN ALTERNATE UU + if (0x115dc <= code && code <= 0x115dd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1163d) { + if (code < 0x11633) { + // Mc [3] MODI VOWEL SIGN AA..MODI VOWEL SIGN II + if (0x11630 <= code && code <= 0x11632) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1163b) { + // Mn [8] MODI VOWEL SIGN U..MODI VOWEL SIGN AI + if (0x11633 <= code && code <= 0x1163a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] MODI VOWEL SIGN O..MODI VOWEL SIGN AU + if (0x1163b <= code && code <= 0x1163c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1163e) { + // Mn MODI SIGN ANUSVARA + if (0x1163d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1163f) { + // Mc MODI SIGN VISARGA + if (0x1163e === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] MODI SIGN VIRAMA..MODI SIGN ARDHACANDRA + if (0x1163f <= code && code <= 0x11640) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0x1193f) { + if (code < 0x11727) { + if (code < 0x116b6) { + if (code < 0x116ad) { + // Mn TAKRI SIGN ANUSVARA + if (0x116ab === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc TAKRI SIGN VISARGA + if (0x116ac === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x116ae) { + // Mn TAKRI VOWEL SIGN AA + if (0x116ad === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x116b0) { + // Mc [2] TAKRI VOWEL SIGN I..TAKRI VOWEL SIGN II + if (0x116ae <= code && code <= 0x116af) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [6] TAKRI VOWEL SIGN U..TAKRI VOWEL SIGN AU + if (0x116b0 <= code && code <= 0x116b5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1171d) { + // Mc TAKRI SIGN VIRAMA + if (0x116b6 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn TAKRI SIGN NUKTA + if (0x116b7 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11722) { + // Mn [3] AHOM CONSONANT SIGN MEDIAL LA..AHOM CONSONANT SIGN MEDIAL LIGATING RA + if (0x1171d <= code && code <= 0x1171f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11726) { + // Mn [4] AHOM VOWEL SIGN I..AHOM VOWEL SIGN UU + if (0x11722 <= code && code <= 0x11725) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc AHOM VOWEL SIGN E + if (0x11726 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0x11930) { + if (code < 0x1182f) { + if (code < 0x1182c) { + // Mn [5] AHOM VOWEL SIGN AW..AHOM SIGN KILLER + if (0x11727 <= code && code <= 0x1172b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] DOGRA VOWEL SIGN AA..DOGRA VOWEL SIGN II + if (0x1182c <= code && code <= 0x1182e) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11838) { + // Mn [9] DOGRA VOWEL SIGN U..DOGRA SIGN ANUSVARA + if (0x1182f <= code && code <= 0x11837) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11839) { + // Mc DOGRA SIGN VISARGA + if (0x11838 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] DOGRA SIGN VIRAMA..DOGRA SIGN NUKTA + if (0x11839 <= code && code <= 0x1183a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1193b) { + if (code < 0x11931) { + // Mc DIVES AKURU VOWEL SIGN AA + if (0x11930 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11937) { + // Mc [5] DIVES AKURU VOWEL SIGN I..DIVES AKURU VOWEL SIGN E + if (0x11931 <= code && code <= 0x11935) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [2] DIVES AKURU VOWEL SIGN AI..DIVES AKURU VOWEL SIGN O + if (0x11937 <= code && code <= 0x11938) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1193d) { + // Mn [2] DIVES AKURU SIGN ANUSVARA..DIVES AKURU SIGN CANDRABINDU + if (0x1193b <= code && code <= 0x1193c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc DIVES AKURU SIGN HALANTA + if (0x1193d === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn DIVES AKURU VIRAMA + if (0x1193e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11a01) { + if (code < 0x119d1) { + if (code < 0x11941) { + // Lo DIVES AKURU PREFIXED NASAL SIGN + if (0x1193f === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + // Mc DIVES AKURU MEDIAL YA + if (0x11940 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11942) { + // Lo DIVES AKURU INITIAL RA + if (0x11941 === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + // Mc DIVES AKURU MEDIAL RA + if (0x11942 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn DIVES AKURU SIGN NUKTA + if (0x11943 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x119dc) { + if (code < 0x119d4) { + // Mc [3] NANDINAGARI VOWEL SIGN AA..NANDINAGARI VOWEL SIGN II + if (0x119d1 <= code && code <= 0x119d3) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x119da) { + // Mn [4] NANDINAGARI VOWEL SIGN U..NANDINAGARI VOWEL SIGN VOCALIC RR + if (0x119d4 <= code && code <= 0x119d7) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] NANDINAGARI VOWEL SIGN E..NANDINAGARI VOWEL SIGN AI + if (0x119da <= code && code <= 0x119db) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x119e0) { + // Mc [4] NANDINAGARI VOWEL SIGN O..NANDINAGARI SIGN VISARGA + if (0x119dc <= code && code <= 0x119df) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn NANDINAGARI SIGN VIRAMA + if (0x119e0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc NANDINAGARI VOWEL SIGN PRISHTHAMATRA E + if (0x119e4 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x11a47) { + if (code < 0x11a39) { + if (code < 0x11a33) { + // Mn [10] ZANABAZAR SQUARE VOWEL SIGN I..ZANABAZAR SQUARE VOWEL LENGTH MARK + if (0x11a01 <= code && code <= 0x11a0a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [6] ZANABAZAR SQUARE FINAL CONSONANT MARK..ZANABAZAR SQUARE SIGN ANUSVARA + if (0x11a33 <= code && code <= 0x11a38) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11a3a) { + // Mc ZANABAZAR SQUARE SIGN VISARGA + if (0x11a39 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11a3b) { + // Lo ZANABAZAR SQUARE CLUSTER-INITIAL LETTER RA + if (0x11a3a === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + // Mn [4] ZANABAZAR SQUARE CLUSTER-FINAL LETTER YA..ZANABAZAR SQUARE CLUSTER-FINAL LETTER VA + if (0x11a3b <= code && code <= 0x11a3e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x11a59) { + if (code < 0x11a51) { + // Mn ZANABAZAR SQUARE SUBJOINER + if (0x11a47 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11a57) { + // Mn [6] SOYOMBO VOWEL SIGN I..SOYOMBO VOWEL SIGN OE + if (0x11a51 <= code && code <= 0x11a56) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SOYOMBO VOWEL SIGN AI..SOYOMBO VOWEL SIGN AU + if (0x11a57 <= code && code <= 0x11a58) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x11a84) { + // Mn [3] SOYOMBO VOWEL SIGN VOCALIC R..SOYOMBO VOWEL LENGTH MARK + if (0x11a59 <= code && code <= 0x11a5b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11a8a) { + // Lo [6] SOYOMBO SIGN JIHVAMULIYA..SOYOMBO CLUSTER-INITIAL LETTER SA + if (0x11a84 <= code && code <= 0x11a89) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + // Mn [13] SOYOMBO FINAL CONSONANT SIGN G..SOYOMBO SIGN ANUSVARA + if (0x11a8a <= code && code <= 0x11a96) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + } + else { + if (code < 0x16f51) { + if (code < 0x11d90) { + if (code < 0x11cb1) { + if (code < 0x11c3e) { + if (code < 0x11c2f) { + if (code < 0x11a98) { + // Mc SOYOMBO SIGN VISARGA + if (0x11a97 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] SOYOMBO GEMINATION MARK..SOYOMBO SUBJOINER + if (0x11a98 <= code && code <= 0x11a99) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11c30) { + // Mc BHAIKSUKI VOWEL SIGN AA + if (0x11c2f === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11c38) { + // Mn [7] BHAIKSUKI VOWEL SIGN I..BHAIKSUKI VOWEL SIGN VOCALIC L + if (0x11c30 <= code && code <= 0x11c36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [6] BHAIKSUKI VOWEL SIGN E..BHAIKSUKI SIGN ANUSVARA + if (0x11c38 <= code && code <= 0x11c3d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x11c92) { + // Mc BHAIKSUKI SIGN VISARGA + if (0x11c3e === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn BHAIKSUKI SIGN VIRAMA + if (0x11c3f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11ca9) { + // Mn [22] MARCHEN SUBJOINED LETTER KA..MARCHEN SUBJOINED LETTER ZA + if (0x11c92 <= code && code <= 0x11ca7) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11caa) { + // Mc MARCHEN SUBJOINED LETTER YA + if (0x11ca9 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [7] MARCHEN SUBJOINED LETTER RA..MARCHEN VOWEL SIGN AA + if (0x11caa <= code && code <= 0x11cb0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11d3a) { + if (code < 0x11cb4) { + if (code < 0x11cb2) { + // Mc MARCHEN VOWEL SIGN I + if (0x11cb1 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] MARCHEN VOWEL SIGN U..MARCHEN VOWEL SIGN E + if (0x11cb2 <= code && code <= 0x11cb3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11cb5) { + // Mc MARCHEN VOWEL SIGN O + if (0x11cb4 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11d31) { + // Mn [2] MARCHEN SIGN ANUSVARA..MARCHEN SIGN CANDRABINDU + if (0x11cb5 <= code && code <= 0x11cb6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [6] MASARAM GONDI VOWEL SIGN AA..MASARAM GONDI VOWEL SIGN VOCALIC R + if (0x11d31 <= code && code <= 0x11d36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x11d46) { + if (code < 0x11d3c) { + // Mn MASARAM GONDI VOWEL SIGN E + if (0x11d3a === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11d3f) { + // Mn [2] MASARAM GONDI VOWEL SIGN AI..MASARAM GONDI VOWEL SIGN O + if (0x11d3c <= code && code <= 0x11d3d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [7] MASARAM GONDI VOWEL SIGN AU..MASARAM GONDI VIRAMA + if (0x11d3f <= code && code <= 0x11d45) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x11d47) { + // Lo MASARAM GONDI REPHA + if (0x11d46 === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + if (code < 0x11d8a) { + // Mn MASARAM GONDI RA-KARA + if (0x11d47 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [5] GUNJALA GONDI VOWEL SIGN AA..GUNJALA GONDI VOWEL SIGN UU + if (0x11d8a <= code && code <= 0x11d8e) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + else { + if (code < 0x11f36) { + if (code < 0x11ef3) { + if (code < 0x11d95) { + if (code < 0x11d93) { + // Mn [2] GUNJALA GONDI VOWEL SIGN EE..GUNJALA GONDI VOWEL SIGN AI + if (0x11d90 <= code && code <= 0x11d91) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] GUNJALA GONDI VOWEL SIGN OO..GUNJALA GONDI VOWEL SIGN AU + if (0x11d93 <= code && code <= 0x11d94) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11d96) { + // Mn GUNJALA GONDI SIGN ANUSVARA + if (0x11d95 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc GUNJALA GONDI SIGN VISARGA + if (0x11d96 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn GUNJALA GONDI VIRAMA + if (0x11d97 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x11f02) { + if (code < 0x11ef5) { + // Mn [2] MAKASAR VOWEL SIGN I..MAKASAR VOWEL SIGN U + if (0x11ef3 <= code && code <= 0x11ef4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11f00) { + // Mc [2] MAKASAR VOWEL SIGN E..MAKASAR VOWEL SIGN O + if (0x11ef5 <= code && code <= 0x11ef6) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] KAWI SIGN CANDRABINDU..KAWI SIGN ANUSVARA + if (0x11f00 <= code && code <= 0x11f01) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x11f03) { + // Lo KAWI SIGN REPHA + if (0x11f02 === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + if (code < 0x11f34) { + // Mc KAWI SIGN VISARGA + if (0x11f03 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [2] KAWI VOWEL SIGN AA..KAWI VOWEL SIGN ALTERNATE AA + if (0x11f34 <= code && code <= 0x11f35) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0x13430) { + if (code < 0x11f40) { + if (code < 0x11f3e) { + // Mn [5] KAWI VOWEL SIGN I..KAWI VOWEL SIGN VOCALIC R + if (0x11f36 <= code && code <= 0x11f3a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] KAWI VOWEL SIGN E..KAWI VOWEL SIGN AI + if (0x11f3e <= code && code <= 0x11f3f) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11f41) { + // Mn KAWI VOWEL SIGN EU + if (0x11f40 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc KAWI SIGN KILLER + if (0x11f41 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn KAWI CONJOINER + if (0x11f42 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x16af0) { + if (code < 0x13440) { + // Cf [16] EGYPTIAN HIEROGLYPH VERTICAL JOINER..EGYPTIAN HIEROGLYPH END WALLED ENCLOSURE + if (0x13430 <= code && code <= 0x1343f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0x13447) { + // Mn EGYPTIAN HIEROGLYPH MIRROR HORIZONTALLY + if (0x13440 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [15] EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT TOP START..EGYPTIAN HIEROGLYPH MODIFIER DAMAGED + if (0x13447 <= code && code <= 0x13455) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x16b30) { + // Mn [5] BASSA VAH COMBINING HIGH TONE..BASSA VAH COMBINING HIGH-LOW TONE + if (0x16af0 <= code && code <= 0x16af4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x16f4f) { + // Mn [7] PAHAWH HMONG MARK CIM TUB..PAHAWH HMONG MARK CIM TAUM + if (0x16b30 <= code && code <= 0x16b36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn MIAO SIGN CONSONANT MODIFIER BAR + if (0x16f4f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0x1da84) { + if (code < 0x1d167) { + if (code < 0x1bca0) { + if (code < 0x16fe4) { + if (code < 0x16f8f) { + // Mc [55] MIAO SIGN ASPIRATION..MIAO VOWEL SIGN UI + if (0x16f51 <= code && code <= 0x16f87) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] MIAO TONE RIGHT..MIAO TONE BELOW + if (0x16f8f <= code && code <= 0x16f92) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x16ff0) { + // Mn KHITAN SMALL SCRIPT FILLER + if (0x16fe4 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1bc9d) { + // Mc [2] VIETNAMESE ALTERNATE READING MARK CA..VIETNAMESE ALTERNATE READING MARK NHAY + if (0x16ff0 <= code && code <= 0x16ff1) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] DUPLOYAN THICK LETTER SELECTOR..DUPLOYAN DOUBLE MARK + if (0x1bc9d <= code && code <= 0x1bc9e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1cf30) { + if (code < 0x1cf00) { + // Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP + if (0x1bca0 <= code && code <= 0x1bca3) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Mn [46] ZNAMENNY COMBINING MARK GORAZDO NIZKO S KRYZHEM ON LEFT..ZNAMENNY COMBINING MARK KRYZH ON LEFT + if (0x1cf00 <= code && code <= 0x1cf2d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1d165) { + // Mn [23] ZNAMENNY COMBINING TONAL RANGE MARK MRACHNO..ZNAMENNY PRIZNAK MODIFIER ROG + if (0x1cf30 <= code && code <= 0x1cf46) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc MUSICAL SYMBOL COMBINING STEM + if (0x1d165 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc MUSICAL SYMBOL COMBINING SPRECHGESANG STEM + if (0x1d166 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1d185) { + if (code < 0x1d16e) { + if (code < 0x1d16d) { + // Mn [3] MUSICAL SYMBOL COMBINING TREMOLO-1..MUSICAL SYMBOL COMBINING TREMOLO-3 + if (0x1d167 <= code && code <= 0x1d169) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc MUSICAL SYMBOL COMBINING AUGMENTATION DOT + if (0x1d16d === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1d173) { + // Mc [5] MUSICAL SYMBOL COMBINING FLAG-1..MUSICAL SYMBOL COMBINING FLAG-5 + if (0x1d16e <= code && code <= 0x1d172) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1d17b) { + // Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE + if (0x1d173 <= code && code <= 0x1d17a) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Mn [8] MUSICAL SYMBOL COMBINING ACCENT..MUSICAL SYMBOL COMBINING LOURE + if (0x1d17b <= code && code <= 0x1d182) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1da00) { + if (code < 0x1d1aa) { + // Mn [7] MUSICAL SYMBOL COMBINING DOIT..MUSICAL SYMBOL COMBINING TRIPLE TONGUE + if (0x1d185 <= code && code <= 0x1d18b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1d242) { + // Mn [4] MUSICAL SYMBOL COMBINING DOWN BOW..MUSICAL SYMBOL COMBINING SNAP PIZZICATO + if (0x1d1aa <= code && code <= 0x1d1ad) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] COMBINING GREEK MUSICAL TRISEME..COMBINING GREEK MUSICAL PENTASEME + if (0x1d242 <= code && code <= 0x1d244) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1da3b) { + // Mn [55] SIGNWRITING HEAD RIM..SIGNWRITING AIR SUCKING IN + if (0x1da00 <= code && code <= 0x1da36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1da75) { + // Mn [50] SIGNWRITING MOUTH CLOSED NEUTRAL..SIGNWRITING EXCITEMENT + if (0x1da3b <= code && code <= 0x1da6c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn SIGNWRITING UPPER BODY TILTING FROM HIP JOINTS + if (0x1da75 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0x1e2ec) { + if (code < 0x1e01b) { + if (code < 0x1daa1) { + if (code < 0x1da9b) { + // Mn SIGNWRITING LOCATION HEAD NECK + if (0x1da84 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [5] SIGNWRITING FILL MODIFIER-2..SIGNWRITING FILL MODIFIER-6 + if (0x1da9b <= code && code <= 0x1da9f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1e000) { + // Mn [15] SIGNWRITING ROTATION MODIFIER-2..SIGNWRITING ROTATION MODIFIER-16 + if (0x1daa1 <= code && code <= 0x1daaf) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1e008) { + // Mn [7] COMBINING GLAGOLITIC LETTER AZU..COMBINING GLAGOLITIC LETTER ZHIVETE + if (0x1e000 <= code && code <= 0x1e006) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [17] COMBINING GLAGOLITIC LETTER ZEMLJA..COMBINING GLAGOLITIC LETTER HERU + if (0x1e008 <= code && code <= 0x1e018) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1e08f) { + if (code < 0x1e023) { + // Mn [7] COMBINING GLAGOLITIC LETTER SHTA..COMBINING GLAGOLITIC LETTER YATI + if (0x1e01b <= code && code <= 0x1e021) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1e026) { + // Mn [2] COMBINING GLAGOLITIC LETTER YU..COMBINING GLAGOLITIC LETTER SMALL YUS + if (0x1e023 <= code && code <= 0x1e024) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [5] COMBINING GLAGOLITIC LETTER YO..COMBINING GLAGOLITIC LETTER FITA + if (0x1e026 <= code && code <= 0x1e02a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1e130) { + // Mn COMBINING CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I + if (0x1e08f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1e2ae) { + // Mn [7] NYIAKENG PUACHUE HMONG TONE-B..NYIAKENG PUACHUE HMONG TONE-D + if (0x1e130 <= code && code <= 0x1e136) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn TOTO SIGN RISING TONE + if (0x1e2ae === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x1f3fb) { + if (code < 0x1e8d0) { + if (code < 0x1e4ec) { + // Mn [4] WANCHO TONE TUP..WANCHO TONE KOINI + if (0x1e2ec <= code && code <= 0x1e2ef) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [4] NAG MUNDARI SIGN MUHOR..NAG MUNDARI SIGN SUTUH + if (0x1e4ec <= code && code <= 0x1e4ef) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1e944) { + // Mn [7] MENDE KIKAKUI COMBINING NUMBER TEENS..MENDE KIKAKUI COMBINING NUMBER MILLIONS + if (0x1e8d0 <= code && code <= 0x1e8d6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1f1e6) { + // Mn [7] ADLAM ALIF LENGTHENER..ADLAM NUKTA + if (0x1e944 <= code && code <= 0x1e94a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // So [26] REGIONAL INDICATOR SYMBOL LETTER A..REGIONAL INDICATOR SYMBOL LETTER Z + if (0x1f1e6 <= code && code <= 0x1f1ff) { + return boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR; + } + } + } + } + } + else { + if (code < 0xe0080) { + if (code < 0xe0000) { + // Sk [5] EMOJI MODIFIER FITZPATRICK TYPE-1-2..EMOJI MODIFIER FITZPATRICK TYPE-6 + if (0x1f3fb <= code && code <= 0x1f3ff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xe0020) { + // Cn + // Cf LANGUAGE TAG + // Cn [30] .. + if (0xe0000 <= code && code <= 0xe001f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Cf [96] TAG SPACE..CANCEL TAG + if (0xe0020 <= code && code <= 0xe007f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xe0100) { + // Cn [128] .. + if (0xe0080 <= code && code <= 0xe00ff) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0xe01f0) { + // Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256 + if (0xe0100 <= code && code <= 0xe01ef) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cn [3600] .. + if (0xe01f0 <= code && code <= 0xe0fff) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + } + } + } + } + } + } + } + } + } + // unlisted code points are treated as a break property of "Other" + return boundaries_1.CLUSTER_BREAK.OTHER; + } + /** + * Given a Unicode code point, returns if symbol is an extended pictographic or some other break + * @param code {number} Unicode code point + * @returns {number} + */ + static getEmojiProperty(code) { + // emoji property taken from: + // https://www.unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt + // and generated by + // node ./scripts/generate-emoji-extended-pictographic.js + if (code < 0x27b0) { + if (code < 0x2600) { + if (code < 0x2328) { + if (code < 0x2122) { + if (code < 0x203c) { + // E0.6 [1] (©️) copyright + if (0xa9 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (®️) registered + if (0xae === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (‼️) double exclamation mark + if (0x203c === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (⁉️) exclamation question mark + if (0x2049 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x2194) { + // E0.6 [1] (™️) trade mark + if (0x2122 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (ℹ️) information + if (0x2139 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x21a9) { + // E0.6 [6] (↔️..↙️) left-right arrow..down-left arrow + if (0x2194 <= code && code <= 0x2199) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x231a) { + // E0.6 [2] (↩️..↪️) right arrow curving left..left arrow curving right + if (0x21a9 <= code && code <= 0x21aa) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [2] (⌚..⌛) watch..hourglass done + if (0x231a <= code && code <= 0x231b) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + else { + if (code < 0x24c2) { + if (code < 0x23cf) { + // E1.0 [1] (⌨️) keyboard + if (0x2328 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.0 [1] (⎈) HELM SYMBOL + if (0x2388 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x23e9) { + // E1.0 [1] (⏏️) eject button + if (0x23cf === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x23f8) { + // E0.6 [4] (⏩..⏬) fast-forward button..fast down button + // E0.7 [2] (⏭️..⏮️) next track button..last track button + // E1.0 [1] (⏯️) play or pause button + // E0.6 [1] (⏰) alarm clock + // E1.0 [2] (⏱️..⏲️) stopwatch..timer clock + // E0.6 [1] (⏳) hourglass not done + if (0x23e9 <= code && code <= 0x23f3) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.7 [3] (⏸️..⏺️) pause button..record button + if (0x23f8 <= code && code <= 0x23fa) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x25b6) { + if (code < 0x25aa) { + // E0.6 [1] (Ⓜ️) circled M + if (0x24c2 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [2] (▪️..▫️) black small square..white small square + if (0x25aa <= code && code <= 0x25ab) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x25c0) { + // E0.6 [1] (▶️) play button + if (0x25b6 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x25fb) { + // E0.6 [1] (◀️) reverse button + if (0x25c0 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [4] (◻️..◾) white medium square..black medium-small square + if (0x25fb <= code && code <= 0x25fe) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + } + else { + if (code < 0x2733) { + if (code < 0x2714) { + if (code < 0x2614) { + if (code < 0x2607) { + // E0.6 [2] (☀️..☁️) sun..cloud + // E0.7 [2] (☂️..☃️) umbrella..snowman + // E1.0 [1] (☄️) comet + // E0.0 [1] (★) BLACK STAR + if (0x2600 <= code && code <= 0x2605) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [7] (☇..☍) LIGHTNING..OPPOSITION + // E0.6 [1] (☎️) telephone + // E0.0 [2] (☏..☐) WHITE TELEPHONE..BALLOT BOX + // E0.6 [1] (☑️) check box with check + // E0.0 [1] (☒) BALLOT BOX WITH X + if (0x2607 <= code && code <= 0x2612) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x2690) { + // E0.6 [2] (☔..☕) umbrella with rain drops..hot beverage + // E0.0 [2] (☖..☗) WHITE SHOGI PIECE..BLACK SHOGI PIECE + // E1.0 [1] (☘️) shamrock + // E0.0 [4] (☙..☜) REVERSED ROTATED FLORAL HEART BULLET..WHITE LEFT POINTING INDEX + // E0.6 [1] (☝️) index pointing up + // E0.0 [2] (☞..☟) WHITE RIGHT POINTING INDEX..WHITE DOWN POINTING INDEX + // E1.0 [1] (☠️) skull and crossbones + // E0.0 [1] (☡) CAUTION SIGN + // E1.0 [2] (☢️..☣️) radioactive..biohazard + // E0.0 [2] (☤..☥) CADUCEUS..ANKH + // E1.0 [1] (☦️) orthodox cross + // E0.0 [3] (☧..☩) CHI RHO..CROSS OF JERUSALEM + // E0.7 [1] (☪️) star and crescent + // E0.0 [3] (☫..☭) FARSI SYMBOL..HAMMER AND SICKLE + // E1.0 [1] (☮️) peace symbol + // E0.7 [1] (☯️) yin yang + // E0.0 [8] (☰..☷) TRIGRAM FOR HEAVEN..TRIGRAM FOR EARTH + // E0.7 [2] (☸️..☹️) wheel of dharma..frowning face + // E0.6 [1] (☺️) smiling face + // E0.0 [5] (☻..☿) BLACK SMILING FACE..MERCURY + // E4.0 [1] (♀️) female sign + // E0.0 [1] (♁) EARTH + // E4.0 [1] (♂️) male sign + // E0.0 [5] (♃..♇) JUPITER..PLUTO + // E0.6 [12] (♈..♓) Aries..Pisces + // E0.0 [11] (♔..♞) WHITE CHESS KING..BLACK CHESS KNIGHT + // E11.0 [1] (♟️) chess pawn + // E0.6 [1] (♠️) spade suit + // E0.0 [2] (♡..♢) WHITE HEART SUIT..WHITE DIAMOND SUIT + // E0.6 [1] (♣️) club suit + // E0.0 [1] (♤) WHITE SPADE SUIT + // E0.6 [2] (♥️..♦️) heart suit..diamond suit + // E0.0 [1] (♧) WHITE CLUB SUIT + // E0.6 [1] (♨️) hot springs + // E0.0 [18] (♩..♺) QUARTER NOTE..RECYCLING SYMBOL FOR GENERIC MATERIALS + // E0.6 [1] (♻️) recycling symbol + // E0.0 [2] (♼..♽) RECYCLED PAPER SYMBOL..PARTIALLY-RECYCLED PAPER SYMBOL + // E11.0 [1] (♾️) infinity + // E0.6 [1] (♿) wheelchair symbol + // E0.0 [6] (⚀..⚅) DIE FACE-1..DIE FACE-6 + if (0x2614 <= code && code <= 0x2685) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x2708) { + // E0.0 [2] (⚐..⚑) WHITE FLAG..BLACK FLAG + // E1.0 [1] (⚒️) hammer and pick + // E0.6 [1] (⚓) anchor + // E1.0 [1] (⚔️) crossed swords + // E4.0 [1] (⚕️) medical symbol + // E1.0 [2] (⚖️..⚗️) balance scale..alembic + // E0.0 [1] (⚘) FLOWER + // E1.0 [1] (⚙️) gear + // E0.0 [1] (⚚) STAFF OF HERMES + // E1.0 [2] (⚛️..⚜️) atom symbol..fleur-de-lis + // E0.0 [3] (⚝..⚟) OUTLINED WHITE STAR..THREE LINES CONVERGING LEFT + // E0.6 [2] (⚠️..⚡) warning..high voltage + // E0.0 [5] (⚢..⚦) DOUBLED FEMALE SIGN..MALE WITH STROKE SIGN + // E13.0 [1] (⚧️) transgender symbol + // E0.0 [2] (⚨..⚩) VERTICAL MALE WITH STROKE SIGN..HORIZONTAL MALE WITH STROKE SIGN + // E0.6 [2] (⚪..⚫) white circle..black circle + // E0.0 [4] (⚬..⚯) MEDIUM SMALL WHITE CIRCLE..UNMARRIED PARTNERSHIP SYMBOL + // E1.0 [2] (⚰️..⚱️) coffin..funeral urn + // E0.0 [11] (⚲..⚼) NEUTER..SESQUIQUADRATE + // E0.6 [2] (⚽..⚾) soccer ball..baseball + // E0.0 [5] (⚿..⛃) SQUARED KEY..BLACK DRAUGHTS KING + // E0.6 [2] (⛄..⛅) snowman without snow..sun behind cloud + // E0.0 [2] (⛆..⛇) RAIN..BLACK SNOWMAN + // E0.7 [1] (⛈️) cloud with lightning and rain + // E0.0 [5] (⛉..⛍) TURNED WHITE SHOGI PIECE..DISABLED CAR + // E0.6 [1] (⛎) Ophiuchus + // E0.7 [1] (⛏️) pick + // E0.0 [1] (⛐) CAR SLIDING + // E0.7 [1] (⛑️) rescue worker’s helmet + // E0.0 [1] (⛒) CIRCLED CROSSING LANES + // E0.7 [1] (⛓️) chains + // E0.6 [1] (⛔) no entry + // E0.0 [20] (⛕..⛨) ALTERNATE ONE-WAY LEFT WAY TRAFFIC..BLACK CROSS ON SHIELD + // E0.7 [1] (⛩️) shinto shrine + // E0.6 [1] (⛪) church + // E0.0 [5] (⛫..⛯) CASTLE..MAP SYMBOL FOR LIGHTHOUSE + // E0.7 [2] (⛰️..⛱️) mountain..umbrella on ground + // E0.6 [2] (⛲..⛳) fountain..flag in hole + // E0.7 [1] (⛴️) ferry + // E0.6 [1] (⛵) sailboat + // E0.0 [1] (⛶) SQUARE FOUR CORNERS + // E0.7 [3] (⛷️..⛹️) skier..person bouncing ball + // E0.6 [1] (⛺) tent + // E0.0 [2] (⛻..⛼) JAPANESE BANK SYMBOL..HEADSTONE GRAVEYARD SYMBOL + // E0.6 [1] (⛽) fuel pump + // E0.0 [4] (⛾..✁) CUP ON BLACK SQUARE..UPPER BLADE SCISSORS + // E0.6 [1] (✂️) scissors + // E0.0 [2] (✃..✄) LOWER BLADE SCISSORS..WHITE SCISSORS + // E0.6 [1] (✅) check mark button + if (0x2690 <= code && code <= 0x2705) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [5] (✈️..✌️) airplane..victory hand + // E0.7 [1] (✍️) writing hand + // E0.0 [1] (✎) LOWER RIGHT PENCIL + // E0.6 [1] (✏️) pencil + // E0.0 [2] (✐..✑) UPPER RIGHT PENCIL..WHITE NIB + // E0.6 [1] (✒️) black nib + if (0x2708 <= code && code <= 0x2712) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x271d) { + // E0.6 [1] (✔️) check mark + if (0x2714 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (✖️) multiply + if (0x2716 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x2721) { + // E0.7 [1] (✝️) latin cross + if (0x271d === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.7 [1] (✡️) star of David + if (0x2721 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (✨) sparkles + if (0x2728 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x2753) { + if (code < 0x2747) { + if (code < 0x2744) { + // E0.6 [2] (✳️..✴️) eight-spoked asterisk..eight-pointed star + if (0x2733 <= code && code <= 0x2734) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (❄️) snowflake + if (0x2744 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x274c) { + // E0.6 [1] (❇️) sparkle + if (0x2747 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (❌) cross mark + if (0x274c === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (❎) cross mark button + if (0x274e === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + else { + if (code < 0x2763) { + if (code < 0x2757) { + // E0.6 [3] (❓..❕) red question mark..white exclamation mark + if (0x2753 <= code && code <= 0x2755) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (❗) red exclamation mark + if (0x2757 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x2795) { + // E1.0 [1] (❣️) heart exclamation + // E0.6 [1] (❤️) red heart + // E0.0 [3] (❥..❧) ROTATED HEAVY BLACK HEART BULLET..ROTATED FLORAL HEART BULLET + if (0x2763 <= code && code <= 0x2767) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x27a1) { + // E0.6 [3] (➕..➗) plus..divide + if (0x2795 <= code && code <= 0x2797) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (➡️) right arrow + if (0x27a1 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + } + } + else { + if (code < 0x1f201) { + if (code < 0x3297) { + if (code < 0x2b1b) { + if (code < 0x2934) { + // E0.6 [1] (➰) curly loop + if (0x27b0 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E1.0 [1] (➿) double curly loop + if (0x27bf === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x2b05) { + // E0.6 [2] (⤴️..⤵️) right arrow curving up..right arrow curving down + if (0x2934 <= code && code <= 0x2935) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [3] (⬅️..⬇️) left arrow..down arrow + if (0x2b05 <= code && code <= 0x2b07) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + else { + if (code < 0x2b55) { + if (code < 0x2b50) { + // E0.6 [2] (⬛..⬜) black large square..white large square + if (0x2b1b <= code && code <= 0x2b1c) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (⭐) star + if (0x2b50 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x3030) { + // E0.6 [1] (⭕) hollow red circle + if (0x2b55 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (〰️) wavy dash + if (0x3030 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (〽️) part alternation mark + if (0x303d === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x1f16c) { + if (code < 0x1f000) { + // E0.6 [1] (㊗️) Japanese “congratulations” button + if (0x3297 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (㊙️) Japanese “secret” button + if (0x3299 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f10d) { + // E0.0 [4] (🀀..🀃) MAHJONG TILE EAST WIND..MAHJONG TILE NORTH WIND + // E0.6 [1] (🀄) mahjong red dragon + // E0.0 [202] (🀅..🃎) MAHJONG TILE GREEN DRAGON..PLAYING CARD KING OF DIAMONDS + // E0.6 [1] (🃏) joker + // E0.0 [48] (🃐..🃿) .. + if (0x1f000 <= code && code <= 0x1f0ff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f12f) { + // E0.0 [3] (🄍..🄏) CIRCLED ZERO WITH SLASH..CIRCLED DOLLAR SIGN WITH OVERLAID BACKSLASH + if (0x1f10d <= code && code <= 0x1f10f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [1] (🄯) COPYLEFT SYMBOL + if (0x1f12f === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x1f18e) { + if (code < 0x1f17e) { + // E0.0 [4] (🅬..🅯) RAISED MR SIGN..CIRCLED HUMAN FIGURE + // E0.6 [2] (🅰️..🅱️) A button (blood type)..B button (blood type) + if (0x1f16c <= code && code <= 0x1f171) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [2] (🅾️..🅿️) O button (blood type)..P button + if (0x1f17e <= code && code <= 0x1f17f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f191) { + // E0.6 [1] (🆎) AB button (blood type) + if (0x1f18e === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f1ad) { + // E0.6 [10] (🆑..🆚) CL button..VS button + if (0x1f191 <= code && code <= 0x1f19a) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [57] (🆭..🇥) MASK WORK SYMBOL.. + if (0x1f1ad <= code && code <= 0x1f1e5) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + } + else { + if (code < 0x1f7d5) { + if (code < 0x1f249) { + if (code < 0x1f22f) { + if (code < 0x1f21a) { + // E0.6 [2] (🈁..🈂️) Japanese “here” button..Japanese “service charge” button + // E0.0 [13] (🈃..🈏) .. + if (0x1f201 <= code && code <= 0x1f20f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (🈚) Japanese “free of charge” button + if (0x1f21a === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f232) { + // E0.6 [1] (🈯) Japanese “reserved” button + if (0x1f22f === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f23c) { + // E0.6 [9] (🈲..🈺) Japanese “prohibited” button..Japanese “open for business” button + if (0x1f232 <= code && code <= 0x1f23a) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [4] (🈼..🈿) .. + if (0x1f23c <= code && code <= 0x1f23f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x1f546) { + if (code < 0x1f400) { + // E0.0 [7] (🉉..🉏) .. + // E0.6 [2] (🉐..🉑) Japanese “bargain” button..Japanese “acceptable” button + // E0.0 [174] (🉒..🋿) .. + // E0.6 [13] (🌀..🌌) cyclone..milky way + // E0.7 [2] (🌍..🌎) globe showing Europe-Africa..globe showing Americas + // E0.6 [1] (🌏) globe showing Asia-Australia + // E1.0 [1] (🌐) globe with meridians + // E0.6 [1] (🌑) new moon + // E1.0 [1] (🌒) waxing crescent moon + // E0.6 [3] (🌓..🌕) first quarter moon..full moon + // E1.0 [3] (🌖..🌘) waning gibbous moon..waning crescent moon + // E0.6 [1] (🌙) crescent moon + // E1.0 [1] (🌚) new moon face + // E0.6 [1] (🌛) first quarter moon face + // E0.7 [1] (🌜) last quarter moon face + // E1.0 [2] (🌝..🌞) full moon face..sun with face + // E0.6 [2] (🌟..🌠) glowing star..shooting star + // E0.7 [1] (🌡️) thermometer + // E0.0 [2] (🌢..🌣) BLACK DROPLET..WHITE SUN + // E0.7 [9] (🌤️..🌬️) sun behind small cloud..wind face + // E1.0 [3] (🌭..🌯) hot dog..burrito + // E0.6 [2] (🌰..🌱) chestnut..seedling + // E1.0 [2] (🌲..🌳) evergreen tree..deciduous tree + // E0.6 [2] (🌴..🌵) palm tree..cactus + // E0.7 [1] (🌶️) hot pepper + // E0.6 [20] (🌷..🍊) tulip..tangerine + // E1.0 [1] (🍋) lemon + // E0.6 [4] (🍌..🍏) banana..green apple + // E1.0 [1] (🍐) pear + // E0.6 [43] (🍑..🍻) peach..clinking beer mugs + // E1.0 [1] (🍼) baby bottle + // E0.7 [1] (🍽️) fork and knife with plate + // E1.0 [2] (🍾..🍿) bottle with popping cork..popcorn + // E0.6 [20] (🎀..🎓) ribbon..graduation cap + // E0.0 [2] (🎔..🎕) HEART WITH TIP ON THE LEFT..BOUQUET OF FLOWERS + // E0.7 [2] (🎖️..🎗️) military medal..reminder ribbon + // E0.0 [1] (🎘) MUSICAL KEYBOARD WITH JACKS + // E0.7 [3] (🎙️..🎛️) studio microphone..control knobs + // E0.0 [2] (🎜..🎝) BEAMED ASCENDING MUSICAL NOTES..BEAMED DESCENDING MUSICAL NOTES + // E0.7 [2] (🎞️..🎟️) film frames..admission tickets + // E0.6 [37] (🎠..🏄) carousel horse..person surfing + // E1.0 [1] (🏅) sports medal + // E0.6 [1] (🏆) trophy + // E1.0 [1] (🏇) horse racing + // E0.6 [1] (🏈) american football + // E1.0 [1] (🏉) rugby football + // E0.6 [1] (🏊) person swimming + // E0.7 [4] (🏋️..🏎️) person lifting weights..racing car + // E1.0 [5] (🏏..🏓) cricket game..ping pong + // E0.7 [12] (🏔️..🏟️) snow-capped mountain..stadium + // E0.6 [4] (🏠..🏣) house..Japanese post office + // E1.0 [1] (🏤) post office + // E0.6 [12] (🏥..🏰) hospital..castle + // E0.0 [2] (🏱..🏲) WHITE PENNANT..BLACK PENNANT + // E0.7 [1] (🏳️) white flag + // E1.0 [1] (🏴) black flag + // E0.7 [1] (🏵️) rosette + // E0.0 [1] (🏶) BLACK ROSETTE + // E0.7 [1] (🏷️) label + // E1.0 [3] (🏸..🏺) badminton..amphora + if (0x1f249 <= code && code <= 0x1f3fa) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E1.0 [8] (🐀..🐇) rat..rabbit + // E0.7 [1] (🐈) cat + // E1.0 [3] (🐉..🐋) dragon..whale + // E0.6 [3] (🐌..🐎) snail..horse + // E1.0 [2] (🐏..🐐) ram..goat + // E0.6 [2] (🐑..🐒) ewe..monkey + // E1.0 [1] (🐓) rooster + // E0.6 [1] (🐔) chicken + // E0.7 [1] (🐕) dog + // E1.0 [1] (🐖) pig + // E0.6 [19] (🐗..🐩) boar..poodle + // E1.0 [1] (🐪) camel + // E0.6 [20] (🐫..🐾) two-hump camel..paw prints + // E0.7 [1] (🐿️) chipmunk + // E0.6 [1] (👀) eyes + // E0.7 [1] (👁️) eye + // E0.6 [35] (👂..👤) ear..bust in silhouette + // E1.0 [1] (👥) busts in silhouette + // E0.6 [6] (👦..👫) boy..woman and man holding hands + // E1.0 [2] (👬..👭) men holding hands..women holding hands + // E0.6 [63] (👮..💬) police officer..speech balloon + // E1.0 [1] (💭) thought balloon + // E0.6 [8] (💮..💵) white flower..dollar banknote + // E1.0 [2] (💶..💷) euro banknote..pound banknote + // E0.6 [52] (💸..📫) money with wings..closed mailbox with raised flag + // E0.7 [2] (📬..📭) open mailbox with raised flag..open mailbox with lowered flag + // E0.6 [1] (📮) postbox + // E1.0 [1] (📯) postal horn + // E0.6 [5] (📰..📴) newspaper..mobile phone off + // E1.0 [1] (📵) no mobile phones + // E0.6 [2] (📶..📷) antenna bars..camera + // E1.0 [1] (📸) camera with flash + // E0.6 [4] (📹..📼) video camera..videocassette + // E0.7 [1] (📽️) film projector + // E0.0 [1] (📾) PORTABLE STEREO + // E1.0 [4] (📿..🔂) prayer beads..repeat single button + // E0.6 [1] (🔃) clockwise vertical arrows + // E1.0 [4] (🔄..🔇) counterclockwise arrows button..muted speaker + // E0.7 [1] (🔈) speaker low volume + // E1.0 [1] (🔉) speaker medium volume + // E0.6 [11] (🔊..🔔) speaker high volume..bell + // E1.0 [1] (🔕) bell with slash + // E0.6 [22] (🔖..🔫) bookmark..water pistol + // E1.0 [2] (🔬..🔭) microscope..telescope + // E0.6 [16] (🔮..🔽) crystal ball..downwards button + if (0x1f400 <= code && code <= 0x1f53d) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f680) { + // E0.0 [3] (🕆..🕈) WHITE LATIN CROSS..CELTIC CROSS + // E0.7 [2] (🕉️..🕊️) om..dove + // E1.0 [4] (🕋..🕎) kaaba..menorah + // E0.0 [1] (🕏) BOWL OF HYGIEIA + // E0.6 [12] (🕐..🕛) one o’clock..twelve o’clock + // E0.7 [12] (🕜..🕧) one-thirty..twelve-thirty + // E0.0 [7] (🕨..🕮) RIGHT SPEAKER..BOOK + // E0.7 [2] (🕯️..🕰️) candle..mantelpiece clock + // E0.0 [2] (🕱..🕲) BLACK SKULL AND CROSSBONES..NO PIRACY + // E0.7 [7] (🕳️..🕹️) hole..joystick + // E3.0 [1] (🕺) man dancing + // E0.0 [12] (🕻..🖆) LEFT HAND TELEPHONE RECEIVER..PEN OVER STAMPED ENVELOPE + // E0.7 [1] (🖇️) linked paperclips + // E0.0 [2] (🖈..🖉) BLACK PUSHPIN..LOWER LEFT PENCIL + // E0.7 [4] (🖊️..🖍️) pen..crayon + // E0.0 [2] (🖎..🖏) LEFT WRITING HAND..TURNED OK HAND SIGN + // E0.7 [1] (🖐️) hand with fingers splayed + // E0.0 [4] (🖑..🖔) REVERSED RAISED HAND WITH FINGERS SPLAYED..REVERSED VICTORY HAND + // E1.0 [2] (🖕..🖖) middle finger..vulcan salute + // E0.0 [13] (🖗..🖣) WHITE DOWN POINTING LEFT HAND INDEX..BLACK DOWN POINTING BACKHAND INDEX + // E3.0 [1] (🖤) black heart + // E0.7 [1] (🖥️) desktop computer + // E0.0 [2] (🖦..🖧) KEYBOARD AND MOUSE..THREE NETWORKED COMPUTERS + // E0.7 [1] (🖨️) printer + // E0.0 [8] (🖩..🖰) POCKET CALCULATOR..TWO BUTTON MOUSE + // E0.7 [2] (🖱️..🖲️) computer mouse..trackball + // E0.0 [9] (🖳..🖻) OLD PERSONAL COMPUTER..DOCUMENT WITH PICTURE + // E0.7 [1] (🖼️) framed picture + // E0.0 [5] (🖽..🗁) FRAME WITH TILES..OPEN FOLDER + // E0.7 [3] (🗂️..🗄️) card index dividers..file cabinet + // E0.0 [12] (🗅..🗐) EMPTY NOTE..PAGES + // E0.7 [3] (🗑️..🗓️) wastebasket..spiral calendar + // E0.0 [8] (🗔..🗛) DESKTOP WINDOW..DECREASE FONT SIZE SYMBOL + // E0.7 [3] (🗜️..🗞️) clamp..rolled-up newspaper + // E0.0 [2] (🗟..🗠) PAGE WITH CIRCLED TEXT..STOCK CHART + // E0.7 [1] (🗡️) dagger + // E0.0 [1] (🗢) LIPS + // E0.7 [1] (🗣️) speaking head + // E0.0 [4] (🗤..🗧) THREE RAYS ABOVE..THREE RAYS RIGHT + // E2.0 [1] (🗨️) left speech bubble + // E0.0 [6] (🗩..🗮) RIGHT SPEECH BUBBLE..LEFT ANGER BUBBLE + // E0.7 [1] (🗯️) right anger bubble + // E0.0 [3] (🗰..🗲) MOOD BUBBLE..LIGHTNING MOOD + // E0.7 [1] (🗳️) ballot box with ballot + // E0.0 [6] (🗴..🗹) BALLOT SCRIPT X..BALLOT BOX WITH BOLD CHECK + // E0.7 [1] (🗺️) world map + // E0.6 [5] (🗻..🗿) mount fuji..moai + // E1.0 [1] (😀) grinning face + // E0.6 [6] (😁..😆) beaming face with smiling eyes..grinning squinting face + // E1.0 [2] (😇..😈) smiling face with halo..smiling face with horns + // E0.6 [5] (😉..😍) winking face..smiling face with heart-eyes + // E1.0 [1] (😎) smiling face with sunglasses + // E0.6 [1] (😏) smirking face + // E0.7 [1] (😐) neutral face + // E1.0 [1] (😑) expressionless face + // E0.6 [3] (😒..😔) unamused face..pensive face + // E1.0 [1] (😕) confused face + // E0.6 [1] (😖) confounded face + // E1.0 [1] (😗) kissing face + // E0.6 [1] (😘) face blowing a kiss + // E1.0 [1] (😙) kissing face with smiling eyes + // E0.6 [1] (😚) kissing face with closed eyes + // E1.0 [1] (😛) face with tongue + // E0.6 [3] (😜..😞) winking face with tongue..disappointed face + // E1.0 [1] (😟) worried face + // E0.6 [6] (😠..😥) angry face..sad but relieved face + // E1.0 [2] (😦..😧) frowning face with open mouth..anguished face + // E0.6 [4] (😨..😫) fearful face..tired face + // E1.0 [1] (😬) grimacing face + // E0.6 [1] (😭) loudly crying face + // E1.0 [2] (😮..😯) face with open mouth..hushed face + // E0.6 [4] (😰..😳) anxious face with sweat..flushed face + // E1.0 [1] (😴) sleeping face + // E0.6 [1] (😵) face with crossed-out eyes + // E1.0 [1] (😶) face without mouth + // E0.6 [10] (😷..🙀) face with medical mask..weary cat + // E1.0 [4] (🙁..🙄) slightly frowning face..face with rolling eyes + // E0.6 [11] (🙅..🙏) person gesturing NO..folded hands + if (0x1f546 <= code && code <= 0x1f64f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f774) { + // E0.6 [1] (🚀) rocket + // E1.0 [2] (🚁..🚂) helicopter..locomotive + // E0.6 [3] (🚃..🚅) railway car..bullet train + // E1.0 [1] (🚆) train + // E0.6 [1] (🚇) metro + // E1.0 [1] (🚈) light rail + // E0.6 [1] (🚉) station + // E1.0 [2] (🚊..🚋) tram..tram car + // E0.6 [1] (🚌) bus + // E0.7 [1] (🚍) oncoming bus + // E1.0 [1] (🚎) trolleybus + // E0.6 [1] (🚏) bus stop + // E1.0 [1] (🚐) minibus + // E0.6 [3] (🚑..🚓) ambulance..police car + // E0.7 [1] (🚔) oncoming police car + // E0.6 [1] (🚕) taxi + // E1.0 [1] (🚖) oncoming taxi + // E0.6 [1] (🚗) automobile + // E0.7 [1] (🚘) oncoming automobile + // E0.6 [2] (🚙..🚚) sport utility vehicle..delivery truck + // E1.0 [7] (🚛..🚡) articulated lorry..aerial tramway + // E0.6 [1] (🚢) ship + // E1.0 [1] (🚣) person rowing boat + // E0.6 [2] (🚤..🚥) speedboat..horizontal traffic light + // E1.0 [1] (🚦) vertical traffic light + // E0.6 [7] (🚧..🚭) construction..no smoking + // E1.0 [4] (🚮..🚱) litter in bin sign..non-potable water + // E0.6 [1] (🚲) bicycle + // E1.0 [3] (🚳..🚵) no bicycles..person mountain biking + // E0.6 [1] (🚶) person walking + // E1.0 [2] (🚷..🚸) no pedestrians..children crossing + // E0.6 [6] (🚹..🚾) men’s room..water closet + // E1.0 [1] (🚿) shower + // E0.6 [1] (🛀) person taking bath + // E1.0 [5] (🛁..🛅) bathtub..left luggage + // E0.0 [5] (🛆..🛊) TRIANGLE WITH ROUNDED CORNERS..GIRLS SYMBOL + // E0.7 [1] (🛋️) couch and lamp + // E1.0 [1] (🛌) person in bed + // E0.7 [3] (🛍️..🛏️) shopping bags..bed + // E1.0 [1] (🛐) place of worship + // E3.0 [2] (🛑..🛒) stop sign..shopping cart + // E0.0 [2] (🛓..🛔) STUPA..PAGODA + // E12.0 [1] (🛕) hindu temple + // E13.0 [2] (🛖..🛗) hut..elevator + // E0.0 [4] (🛘..🛛) .. + // E15.0 [1] (🛜) wireless + // E14.0 [3] (🛝..🛟) playground slide..ring buoy + // E0.7 [6] (🛠️..🛥️) hammer and wrench..motor boat + // E0.0 [3] (🛦..🛨) UP-POINTING MILITARY AIRPLANE..UP-POINTING SMALL AIRPLANE + // E0.7 [1] (🛩️) small airplane + // E0.0 [1] (🛪) NORTHEAST-POINTING AIRPLANE + // E1.0 [2] (🛫..🛬) airplane departure..airplane arrival + // E0.0 [3] (🛭..🛯) .. + // E0.7 [1] (🛰️) satellite + // E0.0 [2] (🛱..🛲) ONCOMING FIRE ENGINE..DIESEL LOCOMOTIVE + // E0.7 [1] (🛳️) passenger ship + // E3.0 [3] (🛴..🛶) kick scooter..canoe + // E5.0 [2] (🛷..🛸) sled..flying saucer + // E11.0 [1] (🛹) skateboard + // E12.0 [1] (🛺) auto rickshaw + // E13.0 [2] (🛻..🛼) pickup truck..roller skate + // E0.0 [3] (🛽..🛿) .. + if (0x1f680 <= code && code <= 0x1f6ff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [12] (🝴..🝿) LOT OF FORTUNE..ORCUS + if (0x1f774 <= code && code <= 0x1f77f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + else { + if (code < 0x1f8ae) { + if (code < 0x1f848) { + if (code < 0x1f80c) { + // E0.0 [11] (🟕..🟟) CIRCLED TRIANGLE.. + // E12.0 [12] (🟠..🟫) orange circle..brown square + // E0.0 [4] (🟬..🟯) .. + // E14.0 [1] (🟰) heavy equals sign + // E0.0 [15] (🟱..🟿) .. + if (0x1f7d5 <= code && code <= 0x1f7ff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [4] (🠌..🠏) .. + if (0x1f80c <= code && code <= 0x1f80f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f85a) { + // E0.0 [8] (🡈..🡏) .. + if (0x1f848 <= code && code <= 0x1f84f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f888) { + // E0.0 [6] (🡚..🡟) .. + if (0x1f85a <= code && code <= 0x1f85f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [8] (🢈..🢏) .. + if (0x1f888 <= code && code <= 0x1f88f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x1f93c) { + if (code < 0x1f90c) { + // E0.0 [82] (🢮..🣿) .. + if (0x1f8ae <= code && code <= 0x1f8ff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E13.0 [1] (🤌) pinched fingers + // E12.0 [3] (🤍..🤏) white heart..pinching hand + // E1.0 [9] (🤐..🤘) zipper-mouth face..sign of the horns + // E3.0 [6] (🤙..🤞) call me hand..crossed fingers + // E5.0 [1] (🤟) love-you gesture + // E3.0 [8] (🤠..🤧) cowboy hat face..sneezing face + // E5.0 [8] (🤨..🤯) face with raised eyebrow..exploding head + // E3.0 [1] (🤰) pregnant woman + // E5.0 [2] (🤱..🤲) breast-feeding..palms up together + // E3.0 [8] (🤳..🤺) selfie..person fencing + if (0x1f90c <= code && code <= 0x1f93a) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f947) { + // E3.0 [3] (🤼..🤾) people wrestling..person playing handball + // E12.0 [1] (🤿) diving mask + // E3.0 [6] (🥀..🥅) wilted flower..goal net + if (0x1f93c <= code && code <= 0x1f945) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1fc00) { + // E3.0 [5] (🥇..🥋) 1st place medal..martial arts uniform + // E5.0 [1] (🥌) curling stone + // E11.0 [3] (🥍..🥏) lacrosse..flying disc + // E3.0 [15] (🥐..🥞) croissant..pancakes + // E5.0 [13] (🥟..🥫) dumpling..canned food + // E11.0 [5] (🥬..🥰) leafy green..smiling face with hearts + // E12.0 [1] (🥱) yawning face + // E13.0 [1] (🥲) smiling face with tear + // E11.0 [4] (🥳..🥶) partying face..cold face + // E13.0 [2] (🥷..🥸) ninja..disguised face + // E14.0 [1] (🥹) face holding back tears + // E11.0 [1] (🥺) pleading face + // E12.0 [1] (🥻) sari + // E11.0 [4] (🥼..🥿) lab coat..flat shoe + // E1.0 [5] (🦀..🦄) crab..unicorn + // E3.0 [13] (🦅..🦑) eagle..squid + // E5.0 [6] (🦒..🦗) giraffe..cricket + // E11.0 [11] (🦘..🦢) kangaroo..swan + // E13.0 [2] (🦣..🦤) mammoth..dodo + // E12.0 [6] (🦥..🦪) sloth..oyster + // E13.0 [3] (🦫..🦭) beaver..seal + // E12.0 [2] (🦮..🦯) guide dog..white cane + // E11.0 [10] (🦰..🦹) red hair..supervillain + // E12.0 [6] (🦺..🦿) safety vest..mechanical leg + // E1.0 [1] (🧀) cheese wedge + // E11.0 [2] (🧁..🧂) cupcake..salt + // E12.0 [8] (🧃..🧊) beverage box..ice + // E13.0 [1] (🧋) bubble tea + // E14.0 [1] (🧌) troll + // E12.0 [3] (🧍..🧏) person standing..deaf person + // E5.0 [23] (🧐..🧦) face with monocle..socks + // E11.0 [25] (🧧..🧿) red envelope..nazar amulet + // E0.0 [112] (🨀..🩯) NEUTRAL CHESS KING.. + // E12.0 [4] (🩰..🩳) ballet shoes..shorts + // E13.0 [1] (🩴) thong sandal + // E15.0 [3] (🩵..🩷) light blue heart..pink heart + // E12.0 [3] (🩸..🩺) drop of blood..stethoscope + // E14.0 [2] (🩻..🩼) x-ray..crutch + // E0.0 [3] (🩽..🩿) .. + // E12.0 [3] (🪀..🪂) yo-yo..parachute + // E13.0 [4] (🪃..🪆) boomerang..nesting dolls + // E15.0 [2] (🪇..🪈) maracas..flute + // E0.0 [7] (🪉..🪏) .. + // E12.0 [6] (🪐..🪕) ringed planet..banjo + // E13.0 [19] (🪖..🪨) military helmet..rock + // E14.0 [4] (🪩..🪬) mirror ball..hamsa + // E15.0 [3] (🪭..🪯) folding hand fan..khanda + // E13.0 [7] (🪰..🪶) fly..feather + // E14.0 [4] (🪷..🪺) lotus..nest with eggs + // E15.0 [3] (🪻..🪽) hyacinth..wing + // E0.0 [1] (🪾) + // E15.0 [1] (🪿) goose + // E13.0 [3] (🫀..🫂) anatomical heart..people hugging + // E14.0 [3] (🫃..🫅) pregnant man..person with crown + // E0.0 [8] (🫆..🫍) .. + // E15.0 [2] (🫎..🫏) moose..donkey + // E13.0 [7] (🫐..🫖) blueberries..teapot + // E14.0 [3] (🫗..🫙) pouring liquid..jar + // E15.0 [2] (🫚..🫛) ginger root..pea pod + // E0.0 [4] (🫜..🫟) .. + // E14.0 [8] (🫠..🫧) melting face..bubbles + // E15.0 [1] (🫨) shaking face + // E0.0 [7] (🫩..🫯) .. + // E14.0 [7] (🫰..🫶) hand with index finger and thumb crossed..heart hands + // E15.0 [2] (🫷..🫸) leftwards pushing hand..rightwards pushing hand + // E0.0 [7] (🫹..🫿) .. + if (0x1f947 <= code && code <= 0x1faff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0[1022] (🰀..🿽) .. + if (0x1fc00 <= code && code <= 0x1fffd) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + } + } + // unlisted code points are treated as a break property of "Other" + return boundaries_1.CLUSTER_BREAK.OTHER; + } +} +exports.default = Graphemer; diff --git a/node_modules/graphemer/lib/GraphemerHelper.d.ts b/node_modules/graphemer/lib/GraphemerHelper.d.ts new file mode 100644 index 0000000..64f6c35 --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerHelper.d.ts @@ -0,0 +1,32 @@ +declare class GraphemerHelper { + /** + * Check if the the character at the position {pos} of the string is surrogate + * @param str {string} + * @param pos {number} + * @returns {boolean} + */ + static isSurrogate(str: string, pos: number): boolean; + /** + * The String.prototype.codePointAt polyfill + * Private function, gets a Unicode code point from a JavaScript UTF-16 string + * handling surrogate pairs appropriately + * @param str {string} + * @param idx {number} + * @returns {number} + */ + static codePointAt(str: string, idx: number): number; + /** + * Private function, returns whether a break is allowed between the two given grapheme breaking classes + * Implemented the UAX #29 3.1.1 Grapheme Cluster Boundary Rules on extended grapheme clusters + * @param start {number} + * @param mid {Array} + * @param end {number} + * @param startEmoji {number} + * @param midEmoji {Array} + * @param endEmoji {number} + * @returns {number} + */ + static shouldBreak(start: number, mid: number[], end: number, startEmoji: number, midEmoji: number[], endEmoji: number): number; +} +export default GraphemerHelper; +//# sourceMappingURL=GraphemerHelper.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/GraphemerHelper.d.ts.map b/node_modules/graphemer/lib/GraphemerHelper.d.ts.map new file mode 100644 index 0000000..369421a --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerHelper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GraphemerHelper.d.ts","sourceRoot":"","sources":["../src/GraphemerHelper.ts"],"names":[],"mappings":"AAUA,cAAM,eAAe;IACnB;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO;IASrD;;;;;;;OAOG;IACH,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM;IAgCpD;;;;;;;;;;OAUG;IACH,MAAM,CAAC,WAAW,CAChB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,MAAM,EAAE,EACb,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAAE,EAClB,QAAQ,EAAE,MAAM,GACf,MAAM;CAyHV;AAED,eAAe,eAAe,CAAC"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/GraphemerHelper.js b/node_modules/graphemer/lib/GraphemerHelper.js new file mode 100644 index 0000000..9bc71eb --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerHelper.js @@ -0,0 +1,169 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const boundaries_1 = require("./boundaries"); +// BreakTypes +// @type {BreakType} +const NotBreak = 0; +const BreakStart = 1; +const Break = 2; +const BreakLastRegional = 3; +const BreakPenultimateRegional = 4; +class GraphemerHelper { + /** + * Check if the the character at the position {pos} of the string is surrogate + * @param str {string} + * @param pos {number} + * @returns {boolean} + */ + static isSurrogate(str, pos) { + return (0xd800 <= str.charCodeAt(pos) && + str.charCodeAt(pos) <= 0xdbff && + 0xdc00 <= str.charCodeAt(pos + 1) && + str.charCodeAt(pos + 1) <= 0xdfff); + } + /** + * The String.prototype.codePointAt polyfill + * Private function, gets a Unicode code point from a JavaScript UTF-16 string + * handling surrogate pairs appropriately + * @param str {string} + * @param idx {number} + * @returns {number} + */ + static codePointAt(str, idx) { + if (idx === undefined) { + idx = 0; + } + const code = str.charCodeAt(idx); + // if a high surrogate + if (0xd800 <= code && code <= 0xdbff && idx < str.length - 1) { + const hi = code; + const low = str.charCodeAt(idx + 1); + if (0xdc00 <= low && low <= 0xdfff) { + return (hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000; + } + return hi; + } + // if a low surrogate + if (0xdc00 <= code && code <= 0xdfff && idx >= 1) { + const hi = str.charCodeAt(idx - 1); + const low = code; + if (0xd800 <= hi && hi <= 0xdbff) { + return (hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000; + } + return low; + } + // just return the char if an unmatched surrogate half or a + // single-char codepoint + return code; + } + // + /** + * Private function, returns whether a break is allowed between the two given grapheme breaking classes + * Implemented the UAX #29 3.1.1 Grapheme Cluster Boundary Rules on extended grapheme clusters + * @param start {number} + * @param mid {Array} + * @param end {number} + * @param startEmoji {number} + * @param midEmoji {Array} + * @param endEmoji {number} + * @returns {number} + */ + static shouldBreak(start, mid, end, startEmoji, midEmoji, endEmoji) { + const all = [start].concat(mid).concat([end]); + const allEmoji = [startEmoji].concat(midEmoji).concat([endEmoji]); + const previous = all[all.length - 2]; + const next = end; + const nextEmoji = endEmoji; + // Lookahead terminator for: + // GB12. ^ (RI RI)* RI ? RI + // GB13. [^RI] (RI RI)* RI ? RI + const rIIndex = all.lastIndexOf(boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR); + if (rIIndex > 0 && + all.slice(1, rIIndex).every(function (c) { + return c === boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR; + }) && + [boundaries_1.CLUSTER_BREAK.PREPEND, boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR].indexOf(previous) === -1) { + if (all.filter(function (c) { + return c === boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR; + }).length % + 2 === + 1) { + return BreakLastRegional; + } + else { + return BreakPenultimateRegional; + } + } + // GB3. CR × LF + if (previous === boundaries_1.CLUSTER_BREAK.CR && next === boundaries_1.CLUSTER_BREAK.LF) { + return NotBreak; + } + // GB4. (Control|CR|LF) ÷ + else if (previous === boundaries_1.CLUSTER_BREAK.CONTROL || + previous === boundaries_1.CLUSTER_BREAK.CR || + previous === boundaries_1.CLUSTER_BREAK.LF) { + return BreakStart; + } + // GB5. ÷ (Control|CR|LF) + else if (next === boundaries_1.CLUSTER_BREAK.CONTROL || + next === boundaries_1.CLUSTER_BREAK.CR || + next === boundaries_1.CLUSTER_BREAK.LF) { + return BreakStart; + } + // GB6. L × (L|V|LV|LVT) + else if (previous === boundaries_1.CLUSTER_BREAK.L && + (next === boundaries_1.CLUSTER_BREAK.L || + next === boundaries_1.CLUSTER_BREAK.V || + next === boundaries_1.CLUSTER_BREAK.LV || + next === boundaries_1.CLUSTER_BREAK.LVT)) { + return NotBreak; + } + // GB7. (LV|V) × (V|T) + else if ((previous === boundaries_1.CLUSTER_BREAK.LV || previous === boundaries_1.CLUSTER_BREAK.V) && + (next === boundaries_1.CLUSTER_BREAK.V || next === boundaries_1.CLUSTER_BREAK.T)) { + return NotBreak; + } + // GB8. (LVT|T) × (T) + else if ((previous === boundaries_1.CLUSTER_BREAK.LVT || previous === boundaries_1.CLUSTER_BREAK.T) && + next === boundaries_1.CLUSTER_BREAK.T) { + return NotBreak; + } + // GB9. × (Extend|ZWJ) + else if (next === boundaries_1.CLUSTER_BREAK.EXTEND || next === boundaries_1.CLUSTER_BREAK.ZWJ) { + return NotBreak; + } + // GB9a. × SpacingMark + else if (next === boundaries_1.CLUSTER_BREAK.SPACINGMARK) { + return NotBreak; + } + // GB9b. Prepend × + else if (previous === boundaries_1.CLUSTER_BREAK.PREPEND) { + return NotBreak; + } + // GB11. \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} + const previousNonExtendIndex = allEmoji + .slice(0, -1) + .lastIndexOf(boundaries_1.EXTENDED_PICTOGRAPHIC); + if (previousNonExtendIndex !== -1 && + allEmoji[previousNonExtendIndex] === boundaries_1.EXTENDED_PICTOGRAPHIC && + all.slice(previousNonExtendIndex + 1, -2).every(function (c) { + return c === boundaries_1.CLUSTER_BREAK.EXTEND; + }) && + previous === boundaries_1.CLUSTER_BREAK.ZWJ && + nextEmoji === boundaries_1.EXTENDED_PICTOGRAPHIC) { + return NotBreak; + } + // GB12. ^ (RI RI)* RI × RI + // GB13. [^RI] (RI RI)* RI × RI + if (mid.indexOf(boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR) !== -1) { + return Break; + } + if (previous === boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR && + next === boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR) { + return NotBreak; + } + // GB999. Any ? Any + return BreakStart; + } +} +exports.default = GraphemerHelper; diff --git a/node_modules/graphemer/lib/GraphemerIterator.d.ts b/node_modules/graphemer/lib/GraphemerIterator.d.ts new file mode 100644 index 0000000..4c52d91 --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerIterator.d.ts @@ -0,0 +1,22 @@ +/** + * GraphemerIterator + * + * Takes a string and a "BreakHandler" method during initialisation + * and creates an iterable object that returns individual graphemes. + * + * @param str {string} + * @return GraphemerIterator + */ +declare class GraphemerIterator implements Iterator { + private _index; + private _str; + private _nextBreak; + constructor(str: string, nextBreak: (str: string, index: number) => number); + [Symbol.iterator](): this; + next(): { + value: string; + done: boolean; + }; +} +export default GraphemerIterator; +//# sourceMappingURL=GraphemerIterator.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/GraphemerIterator.d.ts.map b/node_modules/graphemer/lib/GraphemerIterator.d.ts.map new file mode 100644 index 0000000..c65f0ee --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerIterator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GraphemerIterator.d.ts","sourceRoot":"","sources":["../src/GraphemerIterator.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,cAAM,iBAAkB,YAAW,QAAQ,CAAC,MAAM,CAAC;IACjD,OAAO,CAAC,MAAM,CAAa;IAC3B,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,UAAU,CAAyC;gBAE/C,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM;IAK1E,CAAC,MAAM,CAAC,QAAQ,CAAC;IAIjB,IAAI;;;;CAcL;AAED,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/GraphemerIterator.js b/node_modules/graphemer/lib/GraphemerIterator.js new file mode 100644 index 0000000..dd21ce5 --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerIterator.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * GraphemerIterator + * + * Takes a string and a "BreakHandler" method during initialisation + * and creates an iterable object that returns individual graphemes. + * + * @param str {string} + * @return GraphemerIterator + */ +class GraphemerIterator { + constructor(str, nextBreak) { + this._index = 0; + this._str = str; + this._nextBreak = nextBreak; + } + [Symbol.iterator]() { + return this; + } + next() { + let brk; + if ((brk = this._nextBreak(this._str, this._index)) < this._str.length) { + const value = this._str.slice(this._index, brk); + this._index = brk; + return { value: value, done: false }; + } + if (this._index < this._str.length) { + const value = this._str.slice(this._index); + this._index = this._str.length; + return { value: value, done: false }; + } + return { value: undefined, done: true }; + } +} +exports.default = GraphemerIterator; diff --git a/node_modules/graphemer/lib/boundaries.d.ts b/node_modules/graphemer/lib/boundaries.d.ts new file mode 100644 index 0000000..330aed1 --- /dev/null +++ b/node_modules/graphemer/lib/boundaries.d.ts @@ -0,0 +1,35 @@ +/** + * The Grapheme_Cluster_Break property value + * @see https://www.unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table + */ +export declare enum CLUSTER_BREAK { + CR = 0, + LF = 1, + CONTROL = 2, + EXTEND = 3, + REGIONAL_INDICATOR = 4, + SPACINGMARK = 5, + L = 6, + V = 7, + T = 8, + LV = 9, + LVT = 10, + OTHER = 11, + PREPEND = 12, + E_BASE = 13, + E_MODIFIER = 14, + ZWJ = 15, + GLUE_AFTER_ZWJ = 16, + E_BASE_GAZ = 17 +} +/** + * The Emoji character property is an extension of UCD but shares the same namespace and structure + * @see http://www.unicode.org/reports/tr51/tr51-14.html#Emoji_Properties_and_Data_Files + * + * Here we model Extended_Pictograhpic only to implement UAX #29 GB11 + * \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} + * + * The Emoji character property should not be mixed with Grapheme_Cluster_Break since they are not exclusive + */ +export declare const EXTENDED_PICTOGRAPHIC = 101; +//# sourceMappingURL=boundaries.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/boundaries.d.ts.map b/node_modules/graphemer/lib/boundaries.d.ts.map new file mode 100644 index 0000000..5bc59ba --- /dev/null +++ b/node_modules/graphemer/lib/boundaries.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"boundaries.d.ts","sourceRoot":"","sources":["../src/boundaries.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,oBAAY,aAAa;IACvB,EAAE,IAAI;IACN,EAAE,IAAI;IACN,OAAO,IAAI;IACX,MAAM,IAAI;IACV,kBAAkB,IAAI;IACtB,WAAW,IAAI;IACf,CAAC,IAAI;IACL,CAAC,IAAI;IACL,CAAC,IAAI;IACL,EAAE,IAAI;IACN,GAAG,KAAK;IACR,KAAK,KAAK;IACV,OAAO,KAAK;IACZ,MAAM,KAAK;IACX,UAAU,KAAK;IACf,GAAG,KAAK;IACR,cAAc,KAAK;IACnB,UAAU,KAAK;CAChB;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/boundaries.js b/node_modules/graphemer/lib/boundaries.js new file mode 100644 index 0000000..2c98c14 --- /dev/null +++ b/node_modules/graphemer/lib/boundaries.js @@ -0,0 +1,38 @@ +"use strict"; +/** + * The Grapheme_Cluster_Break property value + * @see https://www.unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EXTENDED_PICTOGRAPHIC = exports.CLUSTER_BREAK = void 0; +var CLUSTER_BREAK; +(function (CLUSTER_BREAK) { + CLUSTER_BREAK[CLUSTER_BREAK["CR"] = 0] = "CR"; + CLUSTER_BREAK[CLUSTER_BREAK["LF"] = 1] = "LF"; + CLUSTER_BREAK[CLUSTER_BREAK["CONTROL"] = 2] = "CONTROL"; + CLUSTER_BREAK[CLUSTER_BREAK["EXTEND"] = 3] = "EXTEND"; + CLUSTER_BREAK[CLUSTER_BREAK["REGIONAL_INDICATOR"] = 4] = "REGIONAL_INDICATOR"; + CLUSTER_BREAK[CLUSTER_BREAK["SPACINGMARK"] = 5] = "SPACINGMARK"; + CLUSTER_BREAK[CLUSTER_BREAK["L"] = 6] = "L"; + CLUSTER_BREAK[CLUSTER_BREAK["V"] = 7] = "V"; + CLUSTER_BREAK[CLUSTER_BREAK["T"] = 8] = "T"; + CLUSTER_BREAK[CLUSTER_BREAK["LV"] = 9] = "LV"; + CLUSTER_BREAK[CLUSTER_BREAK["LVT"] = 10] = "LVT"; + CLUSTER_BREAK[CLUSTER_BREAK["OTHER"] = 11] = "OTHER"; + CLUSTER_BREAK[CLUSTER_BREAK["PREPEND"] = 12] = "PREPEND"; + CLUSTER_BREAK[CLUSTER_BREAK["E_BASE"] = 13] = "E_BASE"; + CLUSTER_BREAK[CLUSTER_BREAK["E_MODIFIER"] = 14] = "E_MODIFIER"; + CLUSTER_BREAK[CLUSTER_BREAK["ZWJ"] = 15] = "ZWJ"; + CLUSTER_BREAK[CLUSTER_BREAK["GLUE_AFTER_ZWJ"] = 16] = "GLUE_AFTER_ZWJ"; + CLUSTER_BREAK[CLUSTER_BREAK["E_BASE_GAZ"] = 17] = "E_BASE_GAZ"; +})(CLUSTER_BREAK = exports.CLUSTER_BREAK || (exports.CLUSTER_BREAK = {})); +/** + * The Emoji character property is an extension of UCD but shares the same namespace and structure + * @see http://www.unicode.org/reports/tr51/tr51-14.html#Emoji_Properties_and_Data_Files + * + * Here we model Extended_Pictograhpic only to implement UAX #29 GB11 + * \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} + * + * The Emoji character property should not be mixed with Grapheme_Cluster_Break since they are not exclusive + */ +exports.EXTENDED_PICTOGRAPHIC = 101; diff --git a/node_modules/graphemer/lib/index.d.ts b/node_modules/graphemer/lib/index.d.ts new file mode 100644 index 0000000..c7c39af --- /dev/null +++ b/node_modules/graphemer/lib/index.d.ts @@ -0,0 +1,3 @@ +import Graphemer from './Graphemer'; +export default Graphemer; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/index.d.ts.map b/node_modules/graphemer/lib/index.d.ts.map new file mode 100644 index 0000000..a6bacf9 --- /dev/null +++ b/node_modules/graphemer/lib/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,aAAa,CAAC;AAEpC,eAAe,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/index.js b/node_modules/graphemer/lib/index.js new file mode 100644 index 0000000..548bdd0 --- /dev/null +++ b/node_modules/graphemer/lib/index.js @@ -0,0 +1,7 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const Graphemer_1 = __importDefault(require("./Graphemer")); +exports.default = Graphemer_1.default; diff --git a/node_modules/graphemer/package.json b/node_modules/graphemer/package.json new file mode 100644 index 0000000..cf0315d --- /dev/null +++ b/node_modules/graphemer/package.json @@ -0,0 +1,54 @@ +{ + "name": "graphemer", + "version": "1.4.0", + "description": "A JavaScript library that breaks strings into their individual user-perceived characters (including emojis!)", + "homepage": "https://github.com/flmnt/graphemer", + "author": "Matt Davies (https://github.com/mattpauldavies)", + "contributors": [ + "Orlin Georgiev (https://github.com/orling)", + "Huáng Jùnliàng (https://github.com/JLHwung)" + ], + "main": "./lib/index.js", + "types": "./lib/index.d.ts", + "files": [ + "lib" + ], + "license": "MIT", + "keywords": [ + "utf-8", + "strings", + "emoji", + "split" + ], + "scripts": { + "prepublishOnly": "npm run build", + "build": "tsc --project tsconfig.json", + "pretest": "npm run build", + "test": "ts-node node_modules/tape/bin/tape tests/**.ts", + "prettier:check": "prettier --check .", + "prettier:fix": "prettier --write ." + }, + "repository": { + "type": "git", + "url": "https://github.com/flmnt/graphemer.git" + }, + "bugs": "https://github.com/flmnt/graphemer/issues", + "devDependencies": { + "@types/tape": "^4.13.0", + "husky": "^4.3.0", + "lint-staged": "^10.3.0", + "prettier": "^2.1.1", + "tape": "^4.6.3", + "ts-node": "^9.0.0", + "typescript": "^4.0.2" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged", + "pre-push": "npm test" + } + }, + "lint-staged": { + "*.{js,ts,md,json}": "prettier --write" + } +} diff --git a/node_modules/growly/HISTORY.md b/node_modules/growly/HISTORY.md new file mode 100644 index 0000000..1ea94f1 --- /dev/null +++ b/node_modules/growly/HISTORY.md @@ -0,0 +1,5 @@ +1.1.0 / 2012-12-12 +================== + +- Default registration work lazily, and is performed on the first call to `Growly.notify()`. +- Added callback to `Growly.register()`. diff --git a/node_modules/growly/README.md b/node_modules/growly/README.md new file mode 100644 index 0000000..ad4116f --- /dev/null +++ b/node_modules/growly/README.md @@ -0,0 +1,95 @@ +# Growly # + +Simple zero-dependency Growl notifications using GNTP. + +## Installation ## + +Install growly using `npm`: + +``` +npm install growly +``` + +And then require it: + +```javascript +var growly = require('growly'); +``` + +This module uses the Growl Network Transport Protocol (GNTP) which was implemented in Growl since version 1.3, so you **must have an appropriate version of Growl installed** for Growly to work. + +## Example ## + +Sending a minimal Growl notification: + +```javascript +var growly = require('growly'); + +growly.notify('This is as easy as it gets', { title: 'Hello, World!' }); +``` + +More examples can be found in the *example/* directory. + +## Usage ## + +The growly module exposes only three methods: `Growly.register()`, `Growly.notify()`, and `Growly.setHost()`. + +### Growly.register(appname, [appicon], [notifications], [callback]) ### + +Registers a new application with Growl. Registration is completely optional since it will be performed automatically for you with sensible defaults. Useful if you want your application, with its own icon and types of notifications, to show up in Growl's prefence panel. + + - `appname` the name of the application (required.) + - `appicon` url, file path, or Buffer instance for an application icon image. + - `notifications` a list of defined notification types with the following properties: + - `.label` name used to identify the type of notification being used (required.) + - `.dispname` name users will see in Growl's preference panel (defaults to `.label`.) + - `.enabled` whether or not notifications of this type are enabled (defaults to true.) + - `callback` called when the registration completes; if registration fails, the first argument will be an Error object. + +An example: + +```javascript +growly.register('My Application', 'path/to/icon.png', [ + { label: 'success', dispname: 'Success' }, + { label: 'warning', dispname: 'Warning', enabled: false } +], function(err) { + console.log(err || 'Registration successful!'); +}); +``` + +### Growly.notify(text, [opts], [callback]) ### + +Sends a Growl notification. If an application wasn't registered beforehand with `growly.register()`, a default application will automatically be registered beforesending the notification. + + - `text` the body of the notification. + - `opts` an object with the following properties: + - `.title` title of the notification. + - `.icon` url, file path, or Buffer instance for the notification's icon. + - `.sticky` whether or not to sticky the notification (defaults to false.) + - `.label` type of notification to use (defaults to the first registered notification type.) + - `.priority` the priority of the notification from lowest (-2) to highest (2). + - `.coalescingId` replace/update the matching previous notification. May be ignored. + - `callback` called when the user has closed/clicked the notification. The callback is passed an Error object `err` as the first argument when the notification fails; otherwise, the second argument `action` is a string that'll describe which action has been taken by the user (either 'closed' or 'clicked'.) + +An example: + +```javascript +/* Assuming an application was registered with a notification type labeled 'warning'. */ +growly.notify('Stuffs broken!', { label: 'warning' }, function(err, action) { + console.log('Action:', action); +}); +``` + +### Growly.setHost(host, port) ### + +Set the host and port that Growl (GNTP) requests will be sent to. Using this method is optional since GNTP defaults to using host 'localhost' and port 23053. + +## License ## + +Copyright (C) 2014 Ibrahim Al-Rajhi + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/growly/example/bakery.js b/node_modules/growly/example/bakery.js new file mode 100644 index 0000000..bcf47a8 --- /dev/null +++ b/node_modules/growly/example/bakery.js @@ -0,0 +1,22 @@ +var growly = require('../lib/growly.js'); + +var notifications = [ + { label: 'muffin', dispname: 'Muffin' }, + { label: 'cake', dispname: 'Cake' } + ], + muffinopts = { label: 'muffin', icon: 'muffin.png' }, + cakeopts = { label: 'cake', title: 'Cake is ready!', icon: 'cake.png', sticky: true }; + +growly.register('Bakery', 'muffin.png', notifications, function(err) { + if (err) { + console.log(err); + return; + } + + growly.notify('Looks like it is half past muffin time!', muffinopts); + + growly.notify('Click to deliver', cakeopts, function(err, action) { + console.log('You', action, 'the notification, so the cake is on its way!'); + }); +}); + diff --git a/node_modules/growly/example/cake.png b/node_modules/growly/example/cake.png new file mode 100644 index 0000000..bc53679 Binary files /dev/null and b/node_modules/growly/example/cake.png differ diff --git a/node_modules/growly/example/muffin.png b/node_modules/growly/example/muffin.png new file mode 100644 index 0000000..e154228 Binary files /dev/null and b/node_modules/growly/example/muffin.png differ diff --git a/node_modules/growly/example/simple.js b/node_modules/growly/example/simple.js new file mode 100644 index 0000000..e825288 --- /dev/null +++ b/node_modules/growly/example/simple.js @@ -0,0 +1,3 @@ +var growly = require('../lib/growly.js'); + +growly.notify('Hello, world!'); diff --git a/node_modules/growly/lib/gntp.js b/node_modules/growly/lib/gntp.js new file mode 100644 index 0000000..723581e --- /dev/null +++ b/node_modules/growly/lib/gntp.js @@ -0,0 +1,200 @@ +var net = require('net'), + crypto = require('crypto'), + format = require('util').format, + fs = require('fs'); + +var nl = '\r\n'; + +/** + * Create a new GNTP request of the given `type`. + * + * @param {String} type either NOTIFY or REGISTER + * @api private + */ + +function GNTP(type, opts) { + opts = opts || {}; + this.type = type; + this.host = opts.host || 'localhost'; + this.port = opts.port || 23053; + this.request = 'GNTP/1.0 ' + type + ' NONE' + nl; + this.resources = []; + this.attempts = 0; + this.maxAttempts = 5; +} + +/** + * Build a response object from the given `resp` response string. + * + * The response object has a key/value pair for every header in the response, and + * a `.state` property equal to either OK, ERROR, or CALLBACK. + * + * An example GNTP response: + * + * GNTP/1.0 -OK NONE\r\n + * Response-Action: REGISTER\r\n + * \r\n + * + * Which would parse to: + * + * { state: 'OK', 'Response-Action': 'REGISTER' } + * + * @param {String} resp + * @return {Object} + * @api private + */ + +GNTP.prototype.parseResp = function(resp) { + var parsed = {}, head, body; + resp = resp.slice(0, resp.indexOf(nl + nl)).split(nl); + head = resp[0]; + body = resp.slice(1); + + parsed.state = head.match(/-(OK|ERROR|CALLBACK)/)[0].slice(1); + body.forEach(function(ln) { + ln = ln.split(': '); + parsed[ln[0]] = ln[1]; + }); + + return parsed; +}; + +/** + * Call `GNTP.send()` with the given arguments after a certain delay. + * + * @api private + */ + +GNTP.prototype.retry = function() { + var self = this, + args = arguments; + setTimeout(function() { + self.send.apply(self, args); + }, 750); +}; + + +/** + * Add a resource to the GNTP request. + * + * @param {Buffer} file + * @return {String} + * @api private + */ + +GNTP.prototype.addResource = function(file) { + var id = crypto.createHash('md5').update(file).digest('hex'), + header = 'Identifier: ' + id + nl + 'Length: ' + file.length + nl + nl; + this.resources.push({ header: header, file: file }); + return 'x-growl-resource://' + id; +}; + +/** + * Append another header `name` with a value of `val` to the request. If `val` is + * undefined, the header will be left out. + * + * @param {String} name + * @param {String} val + * @api public + */ + +GNTP.prototype.add = function(name, val) { + if (val === undefined) + return; + + /* Handle icon files when they're image paths or Buffers. */ + if (/-Icon/.test(name) && !/^https?:\/\//.test(val) ) { + if (/\.(png|gif|jpe?g)$/.test(val)) + val = this.addResource(fs.readFileSync(val)); + else if (val instanceof Buffer) + val = this.addResource(val); + } + + this.request += name + ': ' + val + nl; +}; + +/** + * Append a newline to the request. + * + * @api public + */ + +GNTP.prototype.newline = function() { + this.request += nl; +}; + +/** + * Send the GNTP request, calling `callback` after successfully sending the + * request. + * + * An example GNTP request: + * + * GNTP/1.0 REGISTER NONE\r\n + * Application-Name: Growly.js\r\n + * Notifications-Count: 1\r\n + * \r\n + * Notification-Name: default\r\n + * Notification-Display-Name: Default Notification\r\n + * Notification-Enabled: True\r\n + * \r\n + * + * @param {Function} callback which will be passed the parsed response + * @api public + */ + +GNTP.prototype.send = function(callback) { + var self = this, + socket = net.connect(this.port, this.host), + resp = ''; + + callback = callback || function() {}; + + this.attempts += 1; + + socket.on('connect', function() { + socket.write(self.request); + + self.resources.forEach(function(res) { + socket.write(res.header); + socket.write(res.file); + socket.write(nl + nl); + }); + }); + + socket.on('data', function(data) { + resp += data.toString(); + + /* Wait until we have a complete response which is signaled by two CRLF's. */ + if (resp.slice(resp.length - 4) !== (nl + nl)) return; + + resp = self.parseResp(resp); + + /* We have to manually close the connection for certain responses; otherwise, + reset `resp` to prepare for the next response chunk. */ + if (resp.state === 'ERROR' || resp.state === 'CALLBACK') + socket.end(); + else + resp = ''; + }); + + socket.on('end', function() { + /* Retry on 200 (timed out), 401 (unknown app), or 402 (unknown notification). */ + if (['200', '401', '402'].indexOf(resp['Error-Code']) >= 0) { + if (self.attempts <= self.maxAttempts) { + self.retry(callback); + } else { + var msg = 'GNTP request to "%s:%d" failed with error code %s (%s)'; + callback(new Error(format(msg, self.host, self.port, resp['Error-Code'], resp['Error-Description']))); + } + } else { + callback(undefined, resp); + } + }); + + socket.on('error', function() { + callback(new Error(format('Error while sending GNTP request to "%s:%d"', self.host, self.port))); + socket.destroy(); + }); +}; + +module.exports = GNTP; diff --git a/node_modules/growly/lib/growly.js b/node_modules/growly/lib/growly.js new file mode 100644 index 0000000..0bed539 --- /dev/null +++ b/node_modules/growly/lib/growly.js @@ -0,0 +1,193 @@ +var GNTP = require('./gntp.js'); + +/** + * Interface for registering Growl applications and sending Growl notifications. + * + * @api private + */ + +function Growly() { + this.appname = 'Growly'; + this.notifications = undefined; + this.labels = undefined; + this.count = 0; + this.registered = false; + this.host = undefined; + this.port = undefined; +} + +/** + * Returns an array of label strings extracted from each notification object in + * `Growly.notifications`. + * + * @param {Array} notifications + * @return {Array} notification labels + * @api private + */ + +Growly.prototype.getLabels = function() { + return this.notifications.map(function(notif) { + return notif.label; + }); +}; + +/** + * Set the host to be used by GNTP requests. + * + * @param {String} host + * @param {Number} port + * @api public + */ + +Growly.prototype.setHost = function(host, port) { + this.host = host; + this.port = port; +}; + +/** + * Register an application with the name `appname` (required), icon `appicon`, and + * a list of notification types `notifications`. If provided, `callback` will be + * called when the request completes with the first argument being an `err` error + * object if the request failed. + * + * Each object in the `notifications` array defines a type of notification the + * application will have with the following properties: + * + * - `.label` name used to identify the type of notification being used (required) + * - `.dispname` name users will see in Growl's preference panel (defaults to `.label`) + * - `.enabled` whether or not notifications of this type are enabled (defaults to true) + * - `.icon` default icon notifications of this type should use (url, file path, or Buffer object) + * + * Example registration: + * + * growl.register('My Application', 'path/to/icon.png', [ + * { label: 'success', dispname: 'Success', icon: 'path/to/success.png' }, + * { label: 'warning', dispname: 'Warning', icon: 'path/to/warning.png', enabled: false } + * ], function(err) { console.log(err || 'Registration successful!'); }); + * + * @param {String} appname + * @param {String|Buffer} appicon + * @param {Array} notifications + * @param {Function} callback + * @api public + */ + +Growly.prototype.register = function(appname, appicon, notifications, callback) { + var gntp; + + if (typeof appicon === 'object') { + notifications = appicon; + appicon = undefined; + } + + if (notifications === undefined || !notifications.length) { + notifications = [{ label: 'default', dispname: 'Default Notification', enabled: true }]; + } + + if (typeof arguments[arguments.length - 1] === 'function') { + callback = arguments[arguments.length - 1]; + } else { + callback = function() {}; + } + + this.appname = appname; + this.notifications = notifications; + this.labels = this.getLabels(); + this.registered = true; + + gntp = new GNTP('REGISTER', { host: this.host, port: this.port }); + gntp.add('Application-Name', appname); + gntp.add('Application-Icon', appicon); + gntp.add('Notifications-Count', notifications.length); + gntp.newline(); + + notifications.forEach(function(notif) { + if (notif.enabled === undefined) notif.enabled = true; + gntp.add('Notification-Name', notif.label); + gntp.add('Notification-Display-Name', notif.dispname); + gntp.add('Notification-Enabled', notif.enabled ? 'True' : 'False'); + gntp.add('Notification-Icon', notif.icon); + gntp.newline(); + }); + + gntp.send(callback); +}; + +/** + * Send a notification with `text` content. Growly will lazily register itself + * if the user hasn't already before sending the notification. + * + * A notification can have the following `opts` options: + * + * - `.label` type of notification to use (defaults to the first registered type) + * - `.title` title of the notification + * - `.icon` url, file path, or Buffer instance for the notification's icon. + * - `.sticky` whether or not to sticky the notification (defaults to false) + * - `.priority` the priority of the notification from lowest (-2) to highest (2) + * - `.coalescingId` replace/update the matching previous notification. May be ignored. + * + * If provided, `callback` will be called when the user interacts with the notification. + * The first argument will be an `err` error object, and the second argument an `action` + * string equal to either 'clicked' or 'closed' (whichever action the user took.) + * + * Example notification: + * + * growl.notify('Stuffs broken!', { label: 'warning' }, function(err, action) { + * console.log('Action:', action); + * }); + * + * @param {String} text + * @param {Object} opts + * @param {Function} callback + * @api public + */ + +Growly.prototype.notify = function(text, opts, callback) { + var self = this, + gntp; + + /* Lazy registration. */ + if (!this.registered) { + this.register(this.appname, function(err) { + if (err) console.log(err); + self.notify.call(self, text, opts, callback); + }); + return; + } + + opts = opts || {}; + + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + gntp = new GNTP('NOTIFY', { host: this.host, port: this.port }); + gntp.add('Application-Name', this.appname); + gntp.add('Notification-Name', opts.label || this.labels[0]); + gntp.add('Notification-ID', ++this.count); + gntp.add('Notification-Title', opts.title); + gntp.add('Notification-Text', text); + gntp.add('Notification-Sticky', opts.sticky ? 'True' : 'False'); + gntp.add('Notification-Priority', opts.priority); + gntp.add('Notification-Icon', opts.icon); + gntp.add('Notification-Coalescing-ID', opts.coalescingId || undefined); + gntp.add('Notification-Callback-Context', callback ? 'context' : undefined); + gntp.add('Notification-Callback-Context-Type', callback ? 'string' : undefined); + gntp.add('Notification-Callback-Target', undefined); + gntp.newline(); + + gntp.send(function(err, resp) { + if (callback && err) { + callback(err); + } else if (callback && resp.state === 'CALLBACK') { + callback(undefined, resp['Notification-Callback-Result'].toLowerCase()); + } + }); +}; + +/** + * Expose an instance of the Growly object. + */ + +module.exports = new Growly(); diff --git a/node_modules/growly/package.json b/node_modules/growly/package.json new file mode 100644 index 0000000..78cca25 --- /dev/null +++ b/node_modules/growly/package.json @@ -0,0 +1,15 @@ +{ + "name": "growly", + "version": "1.3.0", + "description": "Simple zero-dependency Growl notifications using GNTP.", + "keywords": ["growl", "growly", "snarl", "notifications", "gntp", "messages"], + "author": "Ibrahim Al-Rajhi (http://ibrahimalrajhi.com/)", + "repository": "http://github.com/theabraham/growly", + "bugs": "http://github.com/theabraham/growly/issues", + "main": "lib/growly.js", + "directories": { + "example": "example", + "lib": "lib" + }, + "license": "MIT" +} diff --git a/node_modules/has-bigints/.eslintrc b/node_modules/has-bigints/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/has-bigints/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/has-bigints/.github/FUNDING.yml b/node_modules/has-bigints/.github/FUNDING.yml new file mode 100644 index 0000000..5b597c8 --- /dev/null +++ b/node_modules/has-bigints/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-bigints +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-bigints/.nycrc b/node_modules/has-bigints/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/has-bigints/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-bigints/CHANGELOG.md b/node_modules/has-bigints/CHANGELOG.md new file mode 100644 index 0000000..ef24d1e --- /dev/null +++ b/node_modules/has-bigints/CHANGELOG.md @@ -0,0 +1,60 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/inspect-js/has-bigints/compare/v1.0.1...v1.0.2) - 2022-04-19 + +### Commits + +- [actions] reuse common workflows [`a655b7f`](https://github.com/inspect-js/has-bigints/commit/a655b7f7733ba2de078b3a59a704c2795440d08c) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`730a2e5`](https://github.com/inspect-js/has-bigints/commit/730a2e53d3f5f82ac43a11cb9753b11445d06d58) +- [readme] add github actions/codecov badges; update URLs [`9a83788`](https://github.com/inspect-js/has-bigints/commit/9a8378861917b41ebb360a9d8ab3d39aa33acf7b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`b1edc52`](https://github.com/inspect-js/has-bigints/commit/b1edc522ef6c23556e55b9c81b65fe884d1e2cc4) +- [actions] update codecov uploader [`cbb1bd0`](https://github.com/inspect-js/has-bigints/commit/cbb1bd0eff486070a19283238da6afd33ca73b4b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`8717e6d`](https://github.com/inspect-js/has-bigints/commit/8717e6d6ae6b5010aea1fac5e48dfdfaf35d8c72) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `safe-publish-latest`, `tape` [`5f70eab`](https://github.com/inspect-js/has-bigints/commit/5f70eab763118d40415f13e47446ea5c011fbe18) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`a1446bc`](https://github.com/inspect-js/has-bigints/commit/a1446bc3e806ce3911c73d6fbdd981f461c41019) +- [meta] use `prepublishOnly` script for npm 7+ [`f2dd197`](https://github.com/inspect-js/has-bigints/commit/f2dd19716a06ca7a971644761e864f0435db278e) +- [actions] use checkout v3 [`1ba72f1`](https://github.com/inspect-js/has-bigints/commit/1ba72f19ada076791ff193aca9d8537388d67ddb) +- [Refactor] use a global variable to get the original BigInt instead of a global property [`a7ccfac`](https://github.com/inspect-js/has-bigints/commit/a7ccfac0414e56dadd263fd07c0b5141388df502) +- [actions] skip `npm ls` on older nodes [`62d31e7`](https://github.com/inspect-js/has-bigints/commit/62d31e79658b16391458d0728e0dacbee8694ebb) + +## [v1.0.1](https://github.com/inspect-js/has-bigints/compare/v1.0.0...v1.0.1) - 2020-12-13 + +### Commits + +- [Tests] use shared travis-ci configs [`46a0d6b`](https://github.com/inspect-js/has-bigints/commit/46a0d6be7ed83bd7f5ead11e4eab7fc91570a448) +- [Tests] migrate tests to Github Actions [`91a38fa`](https://github.com/inspect-js/has-bigints/commit/91a38fa4b85a420b8cf4926b3799e6ceb60d8690) +- [meta] do not publish github action workflow files [`69aacba`](https://github.com/inspect-js/has-bigints/commit/69aacba320c1221e7fee1c71bde600bce063f24b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`64e2c08`](https://github.com/inspect-js/has-bigints/commit/64e2c0895b21ac91a137452fd2455932f62a2fc1) +- [Tests] run `nyc` on all tests; use `tape` runner [`8009375`](https://github.com/inspect-js/has-bigints/commit/8009375e5ec9faca6bbc09441002af5c5e59ff20) +- [actions] add automatic rebasing / merge commit blocking [`e599917`](https://github.com/inspect-js/has-bigints/commit/e599917fd1f751c9a6c0daac70acb243f8c3a01d) +- [actions] add "Allow Edits" workflow [`bd0126e`](https://github.com/inspect-js/has-bigints/commit/bd0126eba2d67e9b9d588bced34413f507698154) +- [readme] remove travis badge [`8e02a73`](https://github.com/inspect-js/has-bigints/commit/8e02a73db34827d24d2945f2db822973a0b49925) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `safe-publish-latest` [`95859f2`](https://github.com/inspect-js/has-bigints/commit/95859f28f23f5733481c52a501063802cf64f75b) +- [Dev Deps] update `auto-changelog`, `in-publish`, `tape` [`0588f41`](https://github.com/inspect-js/has-bigints/commit/0588f415c6cc01d6b34668680044e03b2998e03f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`5b024a6`](https://github.com/inspect-js/has-bigints/commit/5b024a664a8b7d2d2f750a4c11ce20c395b6f12a) +- [meta] add `version` scripts [`4788d61`](https://github.com/inspect-js/has-bigints/commit/4788d61101c009e4e2c1b4d944c263de06192c6a) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`be0e0de`](https://github.com/inspect-js/has-bigints/commit/be0e0de08298dfe483c5d7a2675e5133abeabc53) +- [Dev Deps] update `auto-changelog`; add `aud` [`13a8d1b`](https://github.com/inspect-js/has-bigints/commit/13a8d1bf1f661871d890bfa174de9514f016cdd9) +- [actions] fix action name [`f873d9a`](https://github.com/inspect-js/has-bigints/commit/f873d9a2f10718662528a755b12c61202f4e4afa) +- [meta] add `funding` field [`1b51f49`](https://github.com/inspect-js/has-bigints/commit/1b51f4921df1faf85d2679a0e4ba97ef015a73b7) +- [Dev Deps] update `auto-changelog` [`2322461`](https://github.com/inspect-js/has-bigints/commit/2322461789810434c447439f155eb3ca23eb29fb) +- [Tests] only audit prod deps [`aabdade`](https://github.com/inspect-js/has-bigints/commit/aabdadeaa1e126b91a2fbd82263cc49651ff5e7b) + +## v1.0.0 - 2019-08-10 + +### Commits + +- [Tests] add `.travis.yml` [`9730412`](https://github.com/inspect-js/has-bigints/commit/973041241dc172474bb9457aad41790fe54fec88) +- Initial commit [`65f7c38`](https://github.com/inspect-js/has-bigints/commit/65f7c3889d9a98e214e26d650723cbfc49338463) +- [Tests] add tests [`e374a78`](https://github.com/inspect-js/has-bigints/commit/e374a78033d457badcd47e06752fdec7f62e6c39) +- readme [`5d39092`](https://github.com/inspect-js/has-bigints/commit/5d3909249da442867180fb747eef27543627d250) +- npm init [`1be2e3d`](https://github.com/inspect-js/has-bigints/commit/1be2e3d69db6718901e6845cfc38a07cc46dfd96) +- implementation [`b7bc812`](https://github.com/inspect-js/has-bigints/commit/b7bc8121db1fb1a827625c4cb0608935e3dcbe31) +- [Tests] add linting [`04533be`](https://github.com/inspect-js/has-bigints/commit/04533bef57f60e322238f71f32ee3ae0c988bac4) +- [meta] create FUNDING.yml [`cf824a7`](https://github.com/inspect-js/has-bigints/commit/cf824a7d02e867957d8db17ee0a4c70c8ee5ff23) +- Only apps should have lockfiles [`64e8242`](https://github.com/inspect-js/has-bigints/commit/64e82429f1dca99f624dc971ff13516dee28d353) diff --git a/node_modules/has-bigints/LICENSE b/node_modules/has-bigints/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/node_modules/has-bigints/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-bigints/README.md b/node_modules/has-bigints/README.md new file mode 100644 index 0000000..69414e4 --- /dev/null +++ b/node_modules/has-bigints/README.md @@ -0,0 +1,39 @@ +# has-bigints [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Determine if the JS environment has BigInt support. + +## Example + +```js +var hasBigInts = require('has-bigints'); + +hasBigInts() === true; // if the environment has native BigInt support. Not polyfillable, not forgeable. +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-bigints +[npm-version-svg]: https://versionbadg.es/inspect-js/has-bigints.svg +[deps-svg]: https://david-dm.org/inspect-js/has-bigints.svg +[deps-url]: https://david-dm.org/inspect-js/has-bigints +[dev-deps-svg]: https://david-dm.org/inspect-js/has-bigints/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-bigints#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-bigints.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-bigints.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-bigints.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-bigints +[codecov-image]: https://codecov.io/gh/inspect-js/has-bigints/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-bigints/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-bigints +[actions-url]: https://github.com/inspect-js/has-bigints/actions diff --git a/node_modules/has-bigints/index.js b/node_modules/has-bigints/index.js new file mode 100644 index 0000000..8942374 --- /dev/null +++ b/node_modules/has-bigints/index.js @@ -0,0 +1,10 @@ +'use strict'; + +var $BigInt = typeof BigInt !== 'undefined' && BigInt; + +module.exports = function hasNativeBigInts() { + return typeof $BigInt === 'function' + && typeof BigInt === 'function' + && typeof $BigInt(42) === 'bigint' // eslint-disable-line no-magic-numbers + && typeof BigInt(42) === 'bigint'; // eslint-disable-line no-magic-numbers +}; diff --git a/node_modules/has-bigints/package.json b/node_modules/has-bigints/package.json new file mode 100644 index 0000000..6bed9af --- /dev/null +++ b/node_modules/has-bigints/package.json @@ -0,0 +1,54 @@ +{ + "name": "has-bigints", + "version": "1.0.2", + "description": "Determine if the JS environment has BigInt support.", + "main": "index.js", + "scripts": { + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/has-bigints.git" + }, + "keywords": [ + "BigInt", + "bigints", + "typeof", + "ES2020" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-bigints/issues" + }, + "homepage": "https://github.com/ljharb/has-bigints#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.3" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/has-bigints/test/index.js b/node_modules/has-bigints/test/index.js new file mode 100644 index 0000000..efbc98b --- /dev/null +++ b/node_modules/has-bigints/test/index.js @@ -0,0 +1,44 @@ +'use strict'; + +var test = require('tape'); +var hasBigInts = require('..'); + +test('interface', function (t) { + t.equal(typeof hasBigInts, 'function', 'is a function'); + t.equal(typeof hasBigInts(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('BigInts are supported', { skip: !hasBigInts() }, function (t) { + t.equal(typeof BigInt, 'function', 'global BigInt is a function'); + if (typeof BigInt !== 'function') { + return; + } + + t.equal(BigInt(42), BigInt(42), '42n === 42n'); + t['throws']( + function () { BigInt(NaN); }, + RangeError, + 'NaN is not an integer; BigInt(NaN) throws' + ); + + t['throws']( + function () { BigInt(Infinity); }, + RangeError, + 'Infinity is not an integer; BigInt(Infinity) throws' + ); + + t['throws']( + function () { BigInt(1.1); }, + RangeError, + '1.1 is not an integer; BigInt(1.1) throws' + ); + + t.end(); +}); + +test('BigInts are not supported', { skip: hasBigInts() }, function (t) { + t.equal(typeof BigInt, 'undefined', 'global BigInt is undefined'); + + t.end(); +}); diff --git a/node_modules/has-flag/index.d.ts b/node_modules/has-flag/index.d.ts new file mode 100644 index 0000000..a0a48c8 --- /dev/null +++ b/node_modules/has-flag/index.d.ts @@ -0,0 +1,39 @@ +/** +Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag. + +@param flag - CLI flag to look for. The `--` prefix is optional. +@param argv - CLI arguments. Default: `process.argv`. +@returns Whether the flag exists. + +@example +``` +// $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow + +// foo.ts +import hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` +*/ +declare function hasFlag(flag: string, argv?: string[]): boolean; + +export = hasFlag; diff --git a/node_modules/has-flag/index.js b/node_modules/has-flag/index.js new file mode 100644 index 0000000..b6f80b1 --- /dev/null +++ b/node_modules/has-flag/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; diff --git a/node_modules/has-flag/license b/node_modules/has-flag/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/has-flag/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/has-flag/package.json b/node_modules/has-flag/package.json new file mode 100644 index 0000000..a9cba4b --- /dev/null +++ b/node_modules/has-flag/package.json @@ -0,0 +1,46 @@ +{ + "name": "has-flag", + "version": "4.0.0", + "description": "Check if argv has a specific flag", + "license": "MIT", + "repository": "sindresorhus/has-flag", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "has", + "check", + "detect", + "contains", + "find", + "flag", + "cli", + "command-line", + "argv", + "process", + "arg", + "args", + "argument", + "arguments", + "getopt", + "minimist", + "optimist" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/has-flag/readme.md b/node_modules/has-flag/readme.md new file mode 100644 index 0000000..3f72dff --- /dev/null +++ b/node_modules/has-flag/readme.md @@ -0,0 +1,89 @@ +# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag) + +> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag + +Correctly stops looking after an `--` argument terminator. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + + +## Install + +``` +$ npm install has-flag +``` + + +## Usage + +```js +// foo.js +const hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` + +``` +$ node foo.js -f --unicorn --foo=bar -- --rainbow +``` + + +## API + +### hasFlag(flag, [argv]) + +Returns a boolean for whether the flag exists. + +#### flag + +Type: `string` + +CLI flag to look for. The `--` prefix is optional. + +#### argv + +Type: `string[]`
+Default: `process.argv` + +CLI arguments. + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/has-property-descriptors/.eslintrc b/node_modules/has-property-descriptors/.eslintrc new file mode 100644 index 0000000..2fcc002 --- /dev/null +++ b/node_modules/has-property-descriptors/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": ["GetIntrinsic"], + }], + }, +} diff --git a/node_modules/has-property-descriptors/.github/FUNDING.yml b/node_modules/has-property-descriptors/.github/FUNDING.yml new file mode 100644 index 0000000..817aacf --- /dev/null +++ b/node_modules/has-property-descriptors/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-property-descriptors +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-property-descriptors/.nycrc b/node_modules/has-property-descriptors/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/has-property-descriptors/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-property-descriptors/CHANGELOG.md b/node_modules/has-property-descriptors/CHANGELOG.md new file mode 100644 index 0000000..ae64b47 --- /dev/null +++ b/node_modules/has-property-descriptors/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2022-04-14 + +### Commits + +- Initial implementation, tests [`303559f`](https://github.com/inspect-js/has-property-descriptors/commit/303559f2a72dfe7111573a1aec475ed4a184c35a) +- Initial commit [`3a7ca2d`](https://github.com/inspect-js/has-property-descriptors/commit/3a7ca2dc49f1fff0279a28bb16265e7615e14749) +- read me [`dd73dce`](https://github.com/inspect-js/has-property-descriptors/commit/dd73dce09d89d0f7a4a6e3b1e562a506f979a767) +- npm init [`c1e6557`](https://github.com/inspect-js/has-property-descriptors/commit/c1e655779de632d68cb944c50da6b71bcb7b8c85) +- Only apps should have lockfiles [`e72f7c6`](https://github.com/inspect-js/has-property-descriptors/commit/e72f7c68de534b2d273ee665f8b18d4ecc7f70b0) diff --git a/node_modules/has-property-descriptors/LICENSE b/node_modules/has-property-descriptors/LICENSE new file mode 100644 index 0000000..2e7b9a3 --- /dev/null +++ b/node_modules/has-property-descriptors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-property-descriptors/README.md b/node_modules/has-property-descriptors/README.md new file mode 100644 index 0000000..d81fbd9 --- /dev/null +++ b/node_modules/has-property-descriptors/README.md @@ -0,0 +1,43 @@ +# has-property-descriptors [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD. + +## Example + +```js +var hasPropertyDescriptors = require('has-property-descriptors'); +var assert = require('assert'); + +assert.equal(hasPropertyDescriptors(), true); // will be `false` in IE 6-8, and ES5 engines + +// Arrays can not have their length `[[Defined]]` in some engines +assert.equal(hasPropertyDescriptors.hasArrayLengthDefineBug(), false); // will be `true` in Firefox 4-22, and node v0.6 +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-property-descriptors +[npm-version-svg]: https://versionbadg.es/inspect-js/has-property-descriptors.svg +[deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors.svg +[deps-url]: https://david-dm.org/inspect-js/has-property-descriptors +[dev-deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-property-descriptors#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-property-descriptors.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-property-descriptors.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-property-descriptors.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-property-descriptors +[codecov-image]: https://codecov.io/gh/inspect-js/has-property-descriptors/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-property-descriptors/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-property-descriptors +[actions-url]: https://github.com/inspect-js/has-property-descriptors/actions diff --git a/node_modules/has-property-descriptors/index.js b/node_modules/has-property-descriptors/index.js new file mode 100644 index 0000000..8e30683 --- /dev/null +++ b/node_modules/has-property-descriptors/index.js @@ -0,0 +1,33 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + return true; + } catch (e) { + // IE 8 has a broken defineProperty + return false; + } + } + return false; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!hasPropertyDescriptors()) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; diff --git a/node_modules/has-property-descriptors/package.json b/node_modules/has-property-descriptors/package.json new file mode 100644 index 0000000..9404b71 --- /dev/null +++ b/node_modules/has-property-descriptors/package.json @@ -0,0 +1,70 @@ +{ + "name": "has-property-descriptors", + "version": "1.0.0", + "description": "Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-property-descriptors.git" + }, + "keywords": [ + "property", + "descriptors", + "has", + "environment", + "env", + "defineProperty", + "getOwnPropertyDescriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/has-property-descriptors/issues" + }, + "homepage": "https://github.com/inspect-js/has-property-descriptors#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "evalmd": "^0.0.19", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.3" + }, + "dependencies": { + "get-intrinsic": "^1.1.1" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/has-property-descriptors/test/index.js b/node_modules/has-property-descriptors/test/index.js new file mode 100644 index 0000000..7f02bd3 --- /dev/null +++ b/node_modules/has-property-descriptors/test/index.js @@ -0,0 +1,57 @@ +'use strict'; + +var test = require('tape'); + +var hasPropertyDescriptors = require('../'); + +var sentinel = {}; + +test('hasPropertyDescriptors', function (t) { + t.equal(typeof hasPropertyDescriptors, 'function', 'is a function'); + t.equal(typeof hasPropertyDescriptors.hasArrayLengthDefineBug, 'function', '`hasArrayLengthDefineBug` property is a function'); + + var yes = hasPropertyDescriptors(); + t.test('property descriptors', { skip: !yes }, function (st) { + var o = { a: sentinel }; + + st.deepEqual( + Object.getOwnPropertyDescriptor(o, 'a'), + { + configurable: true, + enumerable: true, + value: sentinel, + writable: true + }, + 'has expected property descriptor' + ); + + Object.defineProperty(o, 'a', { enumerable: false, writable: false }); + + st.deepEqual( + Object.getOwnPropertyDescriptor(o, 'a'), + { + configurable: true, + enumerable: false, + value: sentinel, + writable: false + }, + 'has expected property descriptor after [[Define]]' + ); + + st.end(); + }); + + var arrayBug = hasPropertyDescriptors.hasArrayLengthDefineBug(); + t.test('defining array lengths', { skip: !yes || arrayBug }, function (st) { + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + st.equal(arr.length, 3, 'array starts with length 3'); + + Object.defineProperty(arr, 'length', { value: 5 }); + + st.equal(arr.length, 5, 'array ends with length 5'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/has-proto/.eslintrc b/node_modules/has-proto/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/has-proto/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/has-proto/.github/FUNDING.yml b/node_modules/has-proto/.github/FUNDING.yml new file mode 100644 index 0000000..613705c --- /dev/null +++ b/node_modules/has-proto/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-proto +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-proto/CHANGELOG.md b/node_modules/has-proto/CHANGELOG.md new file mode 100644 index 0000000..c350e80 --- /dev/null +++ b/node_modules/has-proto/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/inspect-js/has-proto/compare/v1.0.0...v1.0.1) - 2022-12-21 + +### Commits + +- [meta] correct URLs and description [`ef34483`](https://github.com/inspect-js/has-proto/commit/ef34483ca0d35680f271b6b96e35526151b25dfc) +- [patch] add an additional criteria [`e81959e`](https://github.com/inspect-js/has-proto/commit/e81959ed7c7a77fbf459f00cb4ef824f1099497f) +- [Dev Deps] update `aud` [`2bec2c4`](https://github.com/inspect-js/has-proto/commit/2bec2c47b072b122ff5443fba0263f6dc649531f) + +## v1.0.0 - 2022-12-12 + +### Commits + +- Initial implementation, tests, readme [`6886fea`](https://github.com/inspect-js/has-proto/commit/6886fea578f67daf69a7920b2eb7637ea6ebb0bc) +- Initial commit [`99129c8`](https://github.com/inspect-js/has-proto/commit/99129c8f42471ac89cb681ba9cb9d52a583eb94f) +- npm init [`2844ad8`](https://github.com/inspect-js/has-proto/commit/2844ad8e75b84d66a46765b3bab9d2e8ea692e10) +- Only apps should have lockfiles [`c65bc5e`](https://github.com/inspect-js/has-proto/commit/c65bc5e40b9004463f7336d47c67245fb139a36a) diff --git a/node_modules/has-proto/LICENSE b/node_modules/has-proto/LICENSE new file mode 100644 index 0000000..2e7b9a3 --- /dev/null +++ b/node_modules/has-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-proto/README.md b/node_modules/has-proto/README.md new file mode 100644 index 0000000..1456765 --- /dev/null +++ b/node_modules/has-proto/README.md @@ -0,0 +1,38 @@ +# has-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Does this environment have the ability to set the [[Prototype]] of an object on creation with `__proto__`? + +## Example + +```js +var hasProto = require('has-proto'); +var assert = require('assert'); + +assert.equal(typeof hasProto(), 'boolean'); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-proto +[npm-version-svg]: https://versionbadg.es/inspect-js/has-proto.svg +[deps-svg]: https://david-dm.org/inspect-js/has-proto.svg +[deps-url]: https://david-dm.org/inspect-js/has-proto +[dev-deps-svg]: https://david-dm.org/inspect-js/has-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-proto +[codecov-image]: https://codecov.io/gh/inspect-js/has-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-proto +[actions-url]: https://github.com/inspect-js/has-proto/actions diff --git a/node_modules/has-proto/index.js b/node_modules/has-proto/index.js new file mode 100644 index 0000000..d3e4be4 --- /dev/null +++ b/node_modules/has-proto/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var test = { + foo: {} +}; + +var $Object = Object; + +module.exports = function hasProto() { + return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); +}; diff --git a/node_modules/has-proto/package.json b/node_modules/has-proto/package.json new file mode 100644 index 0000000..706f951 --- /dev/null +++ b/node_modules/has-proto/package.json @@ -0,0 +1,74 @@ +{ + "name": "has-proto", + "version": "1.0.1", + "description": "Does this environment have the ability to get the [[Prototype]] of an object on creation with `__proto__`?", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-proto.git" + }, + "keywords": [ + "prototype", + "proto", + "set", + "get", + "__proto__", + "getPrototypeOf", + "setPrototypeOf", + "has" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/has-proto/issues" + }, + "homepage": "https://github.com/inspect-js/has-proto#readme", + "testling": { + "files": "test/index.js" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/has-proto/test/index.js b/node_modules/has-proto/test/index.js new file mode 100644 index 0000000..5da1a3a --- /dev/null +++ b/node_modules/has-proto/test/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('tape'); +var hasProto = require('../'); + +test('hasProto', function (t) { + var result = hasProto(); + t.equal(typeof result, 'boolean', 'returns a boolean (' + result + ')'); + + var obj = { __proto__: null }; + if (result) { + t.notOk('toString' in obj, 'null object lacks toString'); + } else { + t.ok('toString' in obj, 'without proto, null object has toString'); + t.equal(obj.__proto__, null); // eslint-disable-line no-proto + } + + t.end(); +}); diff --git a/node_modules/has-symbols/.eslintrc b/node_modules/has-symbols/.eslintrc new file mode 100644 index 0000000..2d9a66a --- /dev/null +++ b/node_modules/has-symbols/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/node_modules/has-symbols/.github/FUNDING.yml b/node_modules/has-symbols/.github/FUNDING.yml new file mode 100644 index 0000000..04cf87e --- /dev/null +++ b/node_modules/has-symbols/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-symbols +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-symbols/.nycrc b/node_modules/has-symbols/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/has-symbols/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-symbols/CHANGELOG.md b/node_modules/has-symbols/CHANGELOG.md new file mode 100644 index 0000000..cd532a2 --- /dev/null +++ b/node_modules/has-symbols/CHANGELOG.md @@ -0,0 +1,75 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.3](https://github.com/inspect-js/has-symbols/compare/v1.0.2...v1.0.3) - 2022-03-01 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`518b28f`](https://github.com/inspect-js/has-symbols/commit/518b28f6c5a516cbccae30794e40aa9f738b1693) +- [meta] add `bugs` and `homepage` fields; reorder package.json [`c480b13`](https://github.com/inspect-js/has-symbols/commit/c480b13fd6802b557e1cef9749872cb5fdeef744) +- [actions] reuse common workflows [`01d0ee0`](https://github.com/inspect-js/has-symbols/commit/01d0ee0a8d97c0947f5edb73eb722027a77b2b07) +- [actions] update codecov uploader [`6424ebe`](https://github.com/inspect-js/has-symbols/commit/6424ebe86b2c9c7c3d2e9bd4413a4e4f168cb275) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`dfa7e7f`](https://github.com/inspect-js/has-symbols/commit/dfa7e7ff38b594645d8c8222aab895157fa7e282) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0c8d436`](https://github.com/inspect-js/has-symbols/commit/0c8d43685c45189cea9018191d4fd7eca91c9d02) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`9026554`](https://github.com/inspect-js/has-symbols/commit/902655442a1bf88e72b42345494ef0c60f5d36ab) +- [readme] add actions and codecov badges [`eaa9682`](https://github.com/inspect-js/has-symbols/commit/eaa9682f990f481d3acf7a1c7600bec36f7b3adc) +- [Dev Deps] update `eslint`, `tape` [`bc7a3ba`](https://github.com/inspect-js/has-symbols/commit/bc7a3ba46f27b7743f8a2579732d59d1b9ac791e) +- [Dev Deps] update `eslint`, `auto-changelog` [`0ace00a`](https://github.com/inspect-js/has-symbols/commit/0ace00af08a88cdd1e6ce0d60357d941c60c2d9f) +- [meta] use `prepublishOnly` script for npm 7+ [`093f72b`](https://github.com/inspect-js/has-symbols/commit/093f72bc2b0ed00c781f444922a5034257bf561d) +- [Tests] test on all 16 minors [`9b80d3d`](https://github.com/inspect-js/has-symbols/commit/9b80d3d9102529f04c20ec5b1fcc6e38426c6b03) + +## [v1.0.2](https://github.com/inspect-js/has-symbols/compare/v1.0.1...v1.0.2) - 2021-02-27 + +### Fixed + +- [Fix] use a universal way to get the original Symbol [`#11`](https://github.com/inspect-js/has-symbols/issues/11) + +### Commits + +- [Tests] migrate tests to Github Actions [`90ae798`](https://github.com/inspect-js/has-symbols/commit/90ae79820bdfe7bc703d67f5f3c5e205f98556d3) +- [meta] do not publish github action workflow files [`29e60a1`](https://github.com/inspect-js/has-symbols/commit/29e60a1b7c25c7f1acf7acff4a9320d0d10c49b4) +- [Tests] run `nyc` on all tests [`8476b91`](https://github.com/inspect-js/has-symbols/commit/8476b915650d360915abe2522505abf4b0e8f0ae) +- [readme] fix repo URLs, remove defunct badges [`126288e`](https://github.com/inspect-js/has-symbols/commit/126288ecc1797c0a40247a6b78bcb2e0bc5d7036) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `core-js`, `get-own-property-symbols` [`d84bdfa`](https://github.com/inspect-js/has-symbols/commit/d84bdfa48ac5188abbb4904b42614cd6c030940a) +- [Tests] fix linting errors [`0df3070`](https://github.com/inspect-js/has-symbols/commit/0df3070b981b6c9f2ee530c09189a7f5c6def839) +- [actions] add "Allow Edits" workflow [`1e6bc29`](https://github.com/inspect-js/has-symbols/commit/1e6bc29b188f32b9648657b07eda08504be5aa9c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`36cea2a`](https://github.com/inspect-js/has-symbols/commit/36cea2addd4e6ec435f35a2656b4e9ef82498e9b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1278338`](https://github.com/inspect-js/has-symbols/commit/127833801865fbc2cc8979beb9ca869c7bfe8222) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1493254`](https://github.com/inspect-js/has-symbols/commit/1493254eda13db5fb8fc5e4a3e8324b3d196029d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js` [`b090bf2`](https://github.com/inspect-js/has-symbols/commit/b090bf214d3679a30edc1e2d729d466ab5183e1d) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4addb7a`](https://github.com/inspect-js/has-symbols/commit/4addb7ab4dc73f927ae99928d68817554fc21dc0) +- [Dev Deps] update `auto-changelog`, `tape` [`81d0baf`](https://github.com/inspect-js/has-symbols/commit/81d0baf3816096a89a8558e8043895f7a7d10d8b) +- [Dev Deps] update `auto-changelog`; add `aud` [`1a4e561`](https://github.com/inspect-js/has-symbols/commit/1a4e5612c25d91c3a03d509721d02630bc4fe3da) +- [readme] remove unused testling URLs [`3000941`](https://github.com/inspect-js/has-symbols/commit/3000941f958046e923ed8152edb1ef4a599e6fcc) +- [Tests] only audit prod deps [`692e974`](https://github.com/inspect-js/has-symbols/commit/692e9743c912410e9440207631a643a34b4741a1) +- [Dev Deps] update `@ljharb/eslint-config` [`51c946c`](https://github.com/inspect-js/has-symbols/commit/51c946c7f6baa793ec5390bb5a45cdce16b4ba76) + +## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-16 + +### Commits + +- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b) +- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c) +- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91) +- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4) +- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193) +- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0) +- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0) + +## v1.0.0 - 2016-09-19 + +### Commits + +- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d) +- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a) +- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c) +- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb) +- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c) diff --git a/node_modules/has-symbols/LICENSE b/node_modules/has-symbols/LICENSE new file mode 100644 index 0000000..df31cbf --- /dev/null +++ b/node_modules/has-symbols/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-symbols/README.md b/node_modules/has-symbols/README.md new file mode 100644 index 0000000..33905f0 --- /dev/null +++ b/node_modules/has-symbols/README.md @@ -0,0 +1,46 @@ +# has-symbols [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has Symbol support. Supports spec, or shams. + +## Example + +```js +var hasSymbols = require('has-symbols'); + +hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. + +var hasSymbolsKinda = require('has-symbols/shams'); +hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-symbols +[2]: https://versionbadg.es/inspect-js/has-symbols.svg +[5]: https://david-dm.org/inspect-js/has-symbols.svg +[6]: https://david-dm.org/inspect-js/has-symbols +[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies +[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-symbols.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols +[codecov-image]: https://codecov.io/gh/inspect-js/has-symbols/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-symbols/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-symbols +[actions-url]: https://github.com/inspect-js/has-symbols/actions diff --git a/node_modules/has-symbols/index.js b/node_modules/has-symbols/index.js new file mode 100644 index 0000000..17044fa --- /dev/null +++ b/node_modules/has-symbols/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; diff --git a/node_modules/has-symbols/package.json b/node_modules/has-symbols/package.json new file mode 100644 index 0000000..fe7004a --- /dev/null +++ b/node_modules/has-symbols/package.json @@ -0,0 +1,101 @@ +{ + "name": "has-symbols", + "version": "1.0.3", + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:staging && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/has-symbols.git" + }, + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.2.3", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "greenkeeper": { + "ignore": [ + "core-js" + ] + } +} diff --git a/node_modules/has-symbols/shams.js b/node_modules/has-symbols/shams.js new file mode 100644 index 0000000..1285210 --- /dev/null +++ b/node_modules/has-symbols/shams.js @@ -0,0 +1,42 @@ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/node_modules/has-symbols/test/index.js b/node_modules/has-symbols/test/index.js new file mode 100644 index 0000000..352129c --- /dev/null +++ b/node_modules/has-symbols/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbols, 'function', 'is a function'); + t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbols are supported', { skip: !hasSymbols() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbols are not supported', { skip: hasSymbols() }, function (t) { + t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); + t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/core-js.js b/node_modules/has-symbols/test/shams/core-js.js new file mode 100644 index 0000000..df5365c --- /dev/null +++ b/node_modules/has-symbols/test/shams/core-js.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/node_modules/has-symbols/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000..9191b24 --- /dev/null +++ b/node_modules/has-symbols/test/shams/get-own-property-symbols.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/tests.js b/node_modules/has-symbols/test/tests.js new file mode 100644 index 0000000..89edd12 --- /dev/null +++ b/node_modules/has-symbols/test/tests.js @@ -0,0 +1,56 @@ +'use strict'; + +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + + if (typeof Symbol !== 'function') { return false; } + + t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); + + /* + t.equal( + Symbol.prototype.toString.call(Symbol('foo')), + Symbol.prototype.toString.call(Symbol('foo')), + 'two symbols with the same description stringify the same' + ); + */ + + /* + var foo = Symbol('foo'); + + t.notEqual( + String(foo), + String(Symbol('bar')), + 'two symbols with different descriptions do not stringify the same' + ); + */ + + t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); + // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); + + t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + t.notEqual(typeof sym, 'string', 'Symbol is not a string'); + t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + + var symVal = 42; + obj[sym] = symVal; + // eslint-disable-next-line no-restricted-syntax + for (sym in obj) { t.fail('symbol property key was found in for..in of object'); } + + t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); + t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { + configurable: true, + enumerable: true, + value: 42, + writable: true + }, 'property descriptor is correct'); +}; diff --git a/node_modules/has-tostringtag/.eslintrc b/node_modules/has-tostringtag/.eslintrc new file mode 100644 index 0000000..2d9a66a --- /dev/null +++ b/node_modules/has-tostringtag/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/node_modules/has-tostringtag/.github/FUNDING.yml b/node_modules/has-tostringtag/.github/FUNDING.yml new file mode 100644 index 0000000..7a450e7 --- /dev/null +++ b/node_modules/has-tostringtag/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-tostringtag +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-tostringtag/CHANGELOG.md b/node_modules/has-tostringtag/CHANGELOG.md new file mode 100644 index 0000000..39fb77c --- /dev/null +++ b/node_modules/has-tostringtag/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2021-08-05 + +### Commits + +- Tests [`6b6f573`](https://github.com/inspect-js/has-tostringtag/commit/6b6f5734dc2058badb300ff0783efdad95fe1a65) +- Initial commit [`2f8190e`](https://github.com/inspect-js/has-tostringtag/commit/2f8190e799fac32ba9b95a076c0255e01d7ce475) +- [meta] do not publish github action workflow files [`6e08cc4`](https://github.com/inspect-js/has-tostringtag/commit/6e08cc4e0fea7ec71ef66e70734b2af2c4a8b71b) +- readme [`94bed6c`](https://github.com/inspect-js/has-tostringtag/commit/94bed6c9560cbbfda034f8d6c260bb7b0db33c1a) +- npm init [`be67840`](https://github.com/inspect-js/has-tostringtag/commit/be67840ab92ee7adb98bcc65261975543f815fa5) +- Implementation [`c4914ec`](https://github.com/inspect-js/has-tostringtag/commit/c4914ecc51ddee692c85b471ae0a5d8123030fbf) +- [meta] use `auto-changelog` [`4aaf768`](https://github.com/inspect-js/has-tostringtag/commit/4aaf76895ae01d7b739f2b19f967ef2372506cd7) +- Only apps should have lockfiles [`bc4d99e`](https://github.com/inspect-js/has-tostringtag/commit/bc4d99e4bf494afbaa235c5f098df6e642edf724) +- [meta] add `safe-publish-latest` [`6523c05`](https://github.com/inspect-js/has-tostringtag/commit/6523c05c9b87140f3ae74c9daf91633dd9ff4e1f) diff --git a/node_modules/has-tostringtag/LICENSE b/node_modules/has-tostringtag/LICENSE new file mode 100644 index 0000000..7948bc0 --- /dev/null +++ b/node_modules/has-tostringtag/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-tostringtag/README.md b/node_modules/has-tostringtag/README.md new file mode 100644 index 0000000..67a5e92 --- /dev/null +++ b/node_modules/has-tostringtag/README.md @@ -0,0 +1,46 @@ +# has-tostringtag [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has `Symbol.toStringTag` support. Supports spec, or shams. + +## Example + +```js +var hasSymbolToStringTag = require('has-tostringtag'); + +hasSymbolToStringTag() === true; // if the environment has native Symbol.toStringTag support. Not polyfillable, not forgeable. + +var hasSymbolToStringTagKinda = require('has-tostringtag/shams'); +hasSymbolToStringTagKinda() === true; // if the environment has a Symbol.toStringTag sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-tostringtag +[2]: https://versionbadg.es/inspect-js/has-tostringtag.svg +[5]: https://david-dm.org/inspect-js/has-tostringtag.svg +[6]: https://david-dm.org/inspect-js/has-tostringtag +[7]: https://david-dm.org/inspect-js/has-tostringtag/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-tostringtag#info=devDependencies +[11]: https://nodei.co/npm/has-tostringtag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-tostringtag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-tostringtag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-tostringtag +[codecov-image]: https://codecov.io/gh/inspect-js/has-tostringtag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-tostringtag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-tostringtag +[actions-url]: https://github.com/inspect-js/has-tostringtag/actions diff --git a/node_modules/has-tostringtag/index.js b/node_modules/has-tostringtag/index.js new file mode 100644 index 0000000..d626b7a --- /dev/null +++ b/node_modules/has-tostringtag/index.js @@ -0,0 +1,7 @@ +'use strict'; + +var hasSymbols = require('has-symbols'); + +module.exports = function hasToStringTag() { + return hasSymbols() && typeof Symbol.toStringTag === 'symbol'; +}; diff --git a/node_modules/has-tostringtag/package.json b/node_modules/has-tostringtag/package.json new file mode 100644 index 0000000..9c74d64 --- /dev/null +++ b/node_modules/has-tostringtag/package.json @@ -0,0 +1,84 @@ +{ + "name": "has-tostringtag", + "version": "1.0.0", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Determine if the JS environment has `Symbol.toStringTag` support. Supports spec, or shams.", + "license": "MIT", + "main": "index.js", + "exports": { + ".": "./index.js", + "./shams": "./shams.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:staging && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-tostringtag.git" + }, + "bugs": { + "url": "https://github.com/inspect-js/has-tostringtag/issues" + }, + "homepage": "https://github.com/inspect-js/has-tostringtag#readme", + "keywords": [ + "javascript", + "ecmascript", + "symbol", + "symbols", + "tostringtag", + "Symbol.toStringTag" + ], + "dependencies": { + "has-symbols": "^1.0.2" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "core-js": "^2.6.12", + "eslint": "^7.32.0", + "get-own-property-symbols": "^0.9.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/has-tostringtag/shams.js b/node_modules/has-tostringtag/shams.js new file mode 100644 index 0000000..8b7e401 --- /dev/null +++ b/node_modules/has-tostringtag/shams.js @@ -0,0 +1,7 @@ +'use strict'; + +var hasSymbols = require('has-symbols/shams'); + +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; diff --git a/node_modules/has-tostringtag/test/index.js b/node_modules/has-tostringtag/test/index.js new file mode 100644 index 0000000..0679afd --- /dev/null +++ b/node_modules/has-tostringtag/test/index.js @@ -0,0 +1,21 @@ +'use strict'; + +var test = require('tape'); +var hasSymbolToStringTag = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbolToStringTag, 'function', 'is a function'); + t.equal(typeof hasSymbolToStringTag(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbol.toStringTag exists', { skip: !hasSymbolToStringTag() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbol.toStringTag does not exist', { skip: hasSymbolToStringTag() }, function (t) { + t.equal(typeof Symbol === 'undefined' ? 'undefined' : typeof Symbol.toStringTag, 'undefined', 'global Symbol.toStringTag is undefined'); + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/shams/core-js.js b/node_modules/has-tostringtag/test/shams/core-js.js new file mode 100644 index 0000000..692b86e --- /dev/null +++ b/node_modules/has-tostringtag/test/shams/core-js.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol') { + test('has native Symbol.toStringTag support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol.toStringTag, 'symbol'); + t.end(); + }); + return; +} + +var hasSymbolToStringTag = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbolToStringTag(), false, 'hasSymbolToStringTag is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasToStringTagAfter = hasSymbolToStringTag(); + t.equal(hasToStringTagAfter, true, 'hasSymbolToStringTag is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js b/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000..489fe83 --- /dev/null +++ b/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbolToStringTag = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbolToStringTag(), false, 'hasSymbolToStringTag is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasToStringTagAfter = hasSymbolToStringTag(); + t.equal(hasToStringTagAfter, true, 'hasSymbolToStringTag is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/tests.js b/node_modules/has-tostringtag/test/tests.js new file mode 100644 index 0000000..0dae885 --- /dev/null +++ b/node_modules/has-tostringtag/test/tests.js @@ -0,0 +1,14 @@ +'use strict'; + +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + t.ok(Symbol.toStringTag, 'Symbol.toStringTag exists'); + + if (typeof Symbol !== 'function' || !Symbol.toStringTag) { return false; } + + var obj = {}; + obj[Symbol.toStringTag] = 'test'; + + t.equal(Object.prototype.toString.call(obj), '[object test]'); +}; diff --git a/node_modules/has/LICENSE-MIT b/node_modules/has/LICENSE-MIT new file mode 100644 index 0000000..ae7014d --- /dev/null +++ b/node_modules/has/LICENSE-MIT @@ -0,0 +1,22 @@ +Copyright (c) 2013 Thiago de Arruda + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/has/README.md b/node_modules/has/README.md new file mode 100644 index 0000000..635e3a4 --- /dev/null +++ b/node_modules/has/README.md @@ -0,0 +1,18 @@ +# has + +> Object.prototype.hasOwnProperty.call shortcut + +## Installation + +```sh +npm install --save has +``` + +## Usage + +```js +var has = require('has'); + +has({}, 'hasOwnProperty'); // false +has(Object.prototype, 'hasOwnProperty'); // true +``` diff --git a/node_modules/has/package.json b/node_modules/has/package.json new file mode 100644 index 0000000..7c4592f --- /dev/null +++ b/node_modules/has/package.json @@ -0,0 +1,48 @@ +{ + "name": "has", + "description": "Object.prototype.hasOwnProperty.call shortcut", + "version": "1.0.3", + "homepage": "https://github.com/tarruda/has", + "author": { + "name": "Thiago de Arruda", + "email": "tpadilha84@gmail.com" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "repository": { + "type": "git", + "url": "git://github.com/tarruda/has.git" + }, + "bugs": { + "url": "https://github.com/tarruda/has/issues" + }, + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/tarruda/has/blob/master/LICENSE-MIT" + } + ], + "main": "./src", + "dependencies": { + "function-bind": "^1.1.1" + }, + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "eslint": "^4.19.1", + "tape": "^4.9.0" + }, + "engines": { + "node": ">= 0.4.0" + }, + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "tape test" + } +} diff --git a/node_modules/has/src/index.js b/node_modules/has/src/index.js new file mode 100644 index 0000000..dd92dd9 --- /dev/null +++ b/node_modules/has/src/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var bind = require('function-bind'); + +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); diff --git a/node_modules/has/test/index.js b/node_modules/has/test/index.js new file mode 100644 index 0000000..43d480b --- /dev/null +++ b/node_modules/has/test/index.js @@ -0,0 +1,10 @@ +'use strict'; + +var test = require('tape'); +var has = require('../'); + +test('has', function (t) { + t.equal(has({}, 'hasOwnProperty'), false, 'object literal does not have own property "hasOwnProperty"'); + t.equal(has(Object.prototype, 'hasOwnProperty'), true, 'Object.prototype has own property "hasOwnProperty"'); + t.end(); +}); diff --git a/node_modules/html-escaper/LICENSE.txt b/node_modules/html-escaper/LICENSE.txt new file mode 100644 index 0000000..dcfa0ae --- /dev/null +++ b/node_modules/html-escaper/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/html-escaper/README.md b/node_modules/html-escaper/README.md new file mode 100644 index 0000000..3dca341 --- /dev/null +++ b/node_modules/html-escaper/README.md @@ -0,0 +1,97 @@ +# html-escaper [![Build Status](https://travis-ci.org/WebReflection/html-escaper.svg?branch=master)](https://travis-ci.org/WebReflection/html-escaper) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/html-escaper/badge.svg?branch=master)](https://coveralls.io/github/WebReflection/html-escaper?branch=master) +A simple module to escape/unescape common problematic entities. + + +### How +This package is available in npm so `npm install html-escaper` is all you need to do, using eventually the global flag too. + +Once the module is present +```js +var html = require('html-escaper'); + +// two basic methods +html.escape('string'); +html.unescape('escaped string'); +``` + + +### Why +there is basically one rule only: do not **ever** replace one char after another if you are transforming a string into another. + +```js +// WARNING: THIS IS WRONG +// if you are that kind of dev that does this +function escape(s) { + return s.replace(/&/g, "&") + .replace(//g, ">") + .replace(/'/g, "'") + .replace(/"/g, """); +} + +// you might be the same dev that does this too +function unescape(s) { + return s.replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/'/g, "'") + .replace(/"/g, '"'); +} + +// guess what we have here ? +unescape('&lt;'); + +// now guess this XSS too ... +unescape('&lt;script&gt;alert("yo")&lt;/script&gt;'); + + +``` + +The last example will produce `` instead of the expected `<script>alert("yo")</script>`. + +Nothing like this could possibly happen if we grab all chars at once and either ways. +It's just a fortunate case that after swapping `&` with `&` no other replace will be affected, but it's not portable and universally a bad practice. + +Grab all chars at once, no excuses! + + + +**more details** +As somebody might think it's an `unescape` issue only, it's not. Being an anti-pattern with side effects works both ways. + +As example, changing the order of the replacement in escaping would produce the unexpected: +```js +function escape(s) { + return s.replace(//g, ">") + .replace(/'/g, "'") + .replace(/"/g, """) + .replace(/&/g, "&"); +} + +escape('<'); // &lt; instead of < +``` +If we do not want to code with the fear that the order wasn't perfect or that our order in either escaping or unescaping is different from the order another method or function used, if we understand the issue and we agree it's potentially a disaster prone approach, if we add the fact in this case creating 4 RegExp objects each time and invoking 4 times `.replace` trough the `String.prototype` is also potentially slower than creating one function only holding one object, or holding the function too, we should agree there is not absolutely any valid reason to keep proposing a char-by-char implementation. + +We have proofs this approach can fail already so ... why should we risk? Just avoid and grab all chars at once or simply use this tiny utility. + +### Backtick +Internt explorer < 9 has [some backtick issue](https://html5sec.org/#102) + +For compatibility sake with common server-side HTML entities encoders and decoders, and in order to have the most reliable I/O, this little utility will NOT fix this IE < 9 problem. + +It is also important to note that if we create valid HTML and we set attributes at runtime through this utility, backticks in strings cannot possibly affect attribute behaviors. + +```js +var img = new Image(); +img.src = html.escape( + 'x` `"` `' +); +// it won't cause problems even in IE < 9 +``` + +**However**, if you use `innerHTML` and you target IE < 9 then [this **might** be a problem](https://github.com/nette/nette/issues/1496). + +Accordingly, if you need more chars and/or backticks to be escaped and unescaped, feel free to use alternatives like [lodash](https://github.com/lodash/lodash) or [he](https://www.npmjs.com/package/he) + +Here a bit more of [my POV](https://github.com/WebReflection/html-escaper/commit/52d554fc6e8583b6ffdd357967cf71962fc07cf6#commitcomment-10625122) and why I haven't implemented same thing alternatives did. Good news: those are alternatives ;-) \ No newline at end of file diff --git a/node_modules/html-escaper/cjs/index.js b/node_modules/html-escaper/cjs/index.js new file mode 100644 index 0000000..164a34c --- /dev/null +++ b/node_modules/html-escaper/cjs/index.js @@ -0,0 +1,65 @@ +'use strict'; +/** + * Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +var replace = ''.replace; + +var ca = /[&<>'"]/g; +var es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g; + +var esca = { + '&': '&', + '<': '<', + '>': '>', + "'": ''', + '"': '"' +}; +var unes = { + '&': '&', + '&': '&', + '<': '<', + '<': '<', + '>': '>', + '>': '>', + ''': "'", + ''': "'", + '"': '"', + '"': '"' +}; + +function escape(es) { + return replace.call(es, ca, pe); +} +exports.escape = escape; + +function unescape(un) { + return replace.call(un, es, cape); +} +exports.unescape = unescape; + +function pe(m) { + return esca[m]; +} + +function cape(m) { + return unes[m]; +} diff --git a/node_modules/html-escaper/cjs/package.json b/node_modules/html-escaper/cjs/package.json new file mode 100644 index 0000000..0292b99 --- /dev/null +++ b/node_modules/html-escaper/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} \ No newline at end of file diff --git a/node_modules/html-escaper/esm/index.js b/node_modules/html-escaper/esm/index.js new file mode 100644 index 0000000..e05b93f --- /dev/null +++ b/node_modules/html-escaper/esm/index.js @@ -0,0 +1,62 @@ +/** + * Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +var replace = ''.replace; + +var ca = /[&<>'"]/g; +var es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g; + +var esca = { + '&': '&', + '<': '<', + '>': '>', + "'": ''', + '"': '"' +}; +var unes = { + '&': '&', + '&': '&', + '<': '<', + '<': '<', + '>': '>', + '>': '>', + ''': "'", + ''': "'", + '"': '"', + '"': '"' +}; + +export function escape(es) { + return replace.call(es, ca, pe); +}; + +export function unescape(un) { + return replace.call(un, es, cape); +}; + +function pe(m) { + return esca[m]; +} + +function cape(m) { + return unes[m]; +} diff --git a/node_modules/html-escaper/index.js b/node_modules/html-escaper/index.js new file mode 100644 index 0000000..6c3f2ab --- /dev/null +++ b/node_modules/html-escaper/index.js @@ -0,0 +1,70 @@ +var html = (function (exports) { + 'use strict'; + + /** + * Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + var replace = ''.replace; + + var ca = /[&<>'"]/g; + var es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g; + + var esca = { + '&': '&', + '<': '<', + '>': '>', + "'": ''', + '"': '"' + }; + var unes = { + '&': '&', + '&': '&', + '<': '<', + '<': '<', + '>': '>', + '>': '>', + ''': "'", + ''': "'", + '"': '"', + '"': '"' + }; + + function escape(es) { + return replace.call(es, ca, pe); + } + function unescape(un) { + return replace.call(un, es, cape); + } + function pe(m) { + return esca[m]; + } + + function cape(m) { + return unes[m]; + } + + exports.escape = escape; + exports.unescape = unescape; + + return exports; + +}({})); diff --git a/node_modules/html-escaper/min.js b/node_modules/html-escaper/min.js new file mode 100644 index 0000000..54d0c23 --- /dev/null +++ b/node_modules/html-escaper/min.js @@ -0,0 +1 @@ +var html=function(t){"use strict";var n="".replace,u=/[&<>'"]/g,r=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g,a={"&":"&","<":"<",">":">","'":"'",'"':"""},e={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'};function c(t){return a[t]}function o(t){return e[t]}return t.escape=function(t){return n.call(t,u,c)},t.unescape=function(t){return n.call(t,r,o)},t}({}); \ No newline at end of file diff --git a/node_modules/html-escaper/package.json b/node_modules/html-escaper/package.json new file mode 100644 index 0000000..81d06a9 --- /dev/null +++ b/node_modules/html-escaper/package.json @@ -0,0 +1,42 @@ +{ + "name": "html-escaper", + "version": "2.0.2", + "description": "fast and safe way to escape and unescape &<>'\" chars", + "main": "./cjs/index.js", + "unpkg": "min.js", + "scripts": { + "build": "npm run cjs && npm run rollup && npm run minify && npm test && npm run size", + "cjs": "ascjs esm cjs", + "coveralls": "cat ./coverage/lcov.info | coveralls", + "minify": "uglifyjs index.js --comments=/^!/ --compress --mangle -o min.js", + "rollup": "rollup --config rollup.config.js", + "size": "cat index.js | wc -c;cat min.js | wc -c;gzip -c min.js | wc -c", + "test": "istanbul cover ./test/index.js" + }, + "module": "./esm/index.js", + "repository": { + "type": "git", + "url": "https://github.com/WebReflection/html-escaper.git" + }, + "keywords": [ + "html", + "escape", + "encode", + "unescape", + "decode", + "entities" + ], + "author": "Andrea Giammarchi", + "license": "MIT", + "bugs": { + "url": "https://github.com/WebReflection/html-escaper/issues" + }, + "homepage": "https://github.com/WebReflection/html-escaper", + "devDependencies": { + "ascjs": "^3.1.2", + "coveralls": "^3.0.11", + "istanbul": "^0.4.5", + "rollup": "^2.1.0", + "uglify-js": "^3.8.0" + } +} diff --git a/node_modules/html-escaper/test/index.js b/node_modules/html-escaper/test/index.js new file mode 100644 index 0000000..0eb00de --- /dev/null +++ b/node_modules/html-escaper/test/index.js @@ -0,0 +1,23 @@ +delete Object.freeze; + +var html = require('../cjs'); + +console.assert( + html.escape('&<>\'"') === '&<>'"', + 'correct escape' +); + +console.assert( + html.escape('<>\'"&') === '<>'"&', + 'correct inverted escape' +); + +console.assert( + '&<>\'"' === html.unescape('&<>'"'), + 'correct unescape' +); + +console.assert( + '<>\'"&' === html.unescape('<>'"&'), + 'correct inverted unescape' +); diff --git a/node_modules/html-escaper/test/package.json b/node_modules/html-escaper/test/package.json new file mode 100644 index 0000000..0292b99 --- /dev/null +++ b/node_modules/html-escaper/test/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} \ No newline at end of file diff --git a/node_modules/human-signals/CHANGELOG.md b/node_modules/human-signals/CHANGELOG.md new file mode 100644 index 0000000..70d0392 --- /dev/null +++ b/node_modules/human-signals/CHANGELOG.md @@ -0,0 +1,11 @@ +# 2.1.0 + +## TypeScript types + +- Add [TypeScript definitions](src/main.d.ts) + +# 2.0.0 + +## Breaking changes + +- Minimal supported Node.js version is now `10.17.0` diff --git a/node_modules/human-signals/LICENSE b/node_modules/human-signals/LICENSE new file mode 100644 index 0000000..9af9492 --- /dev/null +++ b/node_modules/human-signals/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2019 ehmicky + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/human-signals/README.md b/node_modules/human-signals/README.md new file mode 100644 index 0000000..2af37c3 --- /dev/null +++ b/node_modules/human-signals/README.md @@ -0,0 +1,165 @@ +[![Codecov](https://img.shields.io/codecov/c/github/ehmicky/human-signals.svg?label=tested&logo=codecov)](https://codecov.io/gh/ehmicky/human-signals) +[![Travis](https://img.shields.io/badge/cross-platform-4cc61e.svg?logo=travis)](https://travis-ci.org/ehmicky/human-signals) +[![Node](https://img.shields.io/node/v/human-signals.svg?logo=node.js)](https://www.npmjs.com/package/human-signals) +[![Gitter](https://img.shields.io/gitter/room/ehmicky/human-signals.svg?logo=gitter)](https://gitter.im/ehmicky/human-signals) +[![Twitter](https://img.shields.io/badge/%E2%80%8B-twitter-4cc61e.svg?logo=twitter)](https://twitter.com/intent/follow?screen_name=ehmicky) +[![Medium](https://img.shields.io/badge/%E2%80%8B-medium-4cc61e.svg?logo=medium)](https://medium.com/@ehmicky) + +Human-friendly process signals. + +This is a map of known process signals with some information about each signal. + +Unlike +[`os.constants.signals`](https://nodejs.org/api/os.html#os_signal_constants) +this includes: + +- human-friendly [descriptions](#description) +- [default actions](#action), including whether they [can be prevented](#forced) +- whether the signal is [supported](#supported) by the current OS + +# Example + +```js +const { signalsByName, signalsByNumber } = require('human-signals') + +console.log(signalsByName.SIGINT) +// { +// name: 'SIGINT', +// number: 2, +// description: 'User interruption with CTRL-C', +// supported: true, +// action: 'terminate', +// forced: false, +// standard: 'ansi' +// } + +console.log(signalsByNumber[8]) +// { +// name: 'SIGFPE', +// number: 8, +// description: 'Floating point arithmetic error', +// supported: true, +// action: 'core', +// forced: false, +// standard: 'ansi' +// } +``` + +# Install + +```bash +npm install human-signals +``` + +# Usage + +## signalsByName + +_Type_: `object` + +Object whose keys are signal [names](#name) and values are +[signal objects](#signal). + +## signalsByNumber + +_Type_: `object` + +Object whose keys are signal [numbers](#number) and values are +[signal objects](#signal). + +## signal + +_Type_: `object` + +Signal object with the following properties. + +### name + +_Type_: `string` + +Standard name of the signal, for example `'SIGINT'`. + +### number + +_Type_: `number` + +Code number of the signal, for example `2`. While most `number` are +cross-platform, some are different between different OS. + +### description + +_Type_: `string` + +Human-friendly description for the signal, for example +`'User interruption with CTRL-C'`. + +### supported + +_Type_: `boolean` + +Whether the current OS can handle this signal in Node.js using +[`process.on(name, handler)`](https://nodejs.org/api/process.html#process_signal_events). + +The list of supported signals +[is OS-specific](https://github.com/ehmicky/cross-platform-node-guide/blob/master/docs/6_networking_ipc/signals.md#cross-platform-signals). + +### action + +_Type_: `string`\ +_Enum_: `'terminate'`, `'core'`, `'ignore'`, `'pause'`, `'unpause'` + +What is the default action for this signal when it is not handled. + +### forced + +_Type_: `boolean` + +Whether the signal's default action cannot be prevented. This is `true` for +`SIGTERM`, `SIGKILL` and `SIGSTOP`. + +### standard + +_Type_: `string`\ +_Enum_: `'ansi'`, `'posix'`, `'bsd'`, `'systemv'`, `'other'` + +Which standard defined that signal. + +# Support + +If you found a bug or would like a new feature, _don't hesitate_ to +[submit an issue on GitHub](../../issues). + +For other questions, feel free to +[chat with us on Gitter](https://gitter.im/ehmicky/human-signals). + +Everyone is welcome regardless of personal background. We enforce a +[Code of conduct](CODE_OF_CONDUCT.md) in order to promote a positive and +inclusive environment. + +# Contributing + +This project was made with ❤️. The simplest way to give back is by starring and +sharing it online. + +If the documentation is unclear or has a typo, please click on the page's `Edit` +button (pencil icon) and suggest a correction. + +If you would like to help us fix a bug or add a new feature, please check our +[guidelines](CONTRIBUTING.md). Pull requests are welcome! + +Thanks go to our wonderful contributors: + + + + + + + + + +

ehmicky

💻 🎨 🤔 📖

electrovir

💻
+ + + + + diff --git a/node_modules/human-signals/build/src/core.js b/node_modules/human-signals/build/src/core.js new file mode 100644 index 0000000..98e8fce --- /dev/null +++ b/node_modules/human-signals/build/src/core.js @@ -0,0 +1,273 @@ +"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SIGNALS=void 0; + +const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix"}, + +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi"}, + +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix"}, + +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi"}, + +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix"}, + +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi"}, + +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd"}, + +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd"}, + +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other"}, + +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi"}, + +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true}, + +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi"}, + +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix"}, + +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix"}, + +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi"}, + +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other"}, + +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix"}, + +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other"}, + +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true}, + +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true}, + +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix"}, + +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix"}, + +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other"}, + +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix"}, + +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd"}, + +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd"}, + +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd"}, + +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd"}, + +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other"}, + +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other"}, + +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other"}, + +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv"}, + +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other"}, + +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other"}];exports.SIGNALS=SIGNALS; +//# sourceMappingURL=core.js.map \ No newline at end of file diff --git a/node_modules/human-signals/build/src/core.js.map b/node_modules/human-signals/build/src/core.js.map new file mode 100644 index 0000000..cbfce26 --- /dev/null +++ b/node_modules/human-signals/build/src/core.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core.js"],"names":["SIGNALS","name","number","action","description","standard","forced"],"mappings":";;AAEO,KAAMA,CAAAA,OAAO,CAAG;AACrB;AACEC,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,iBAJf;AAKEC,QAAQ,CAAE,OALZ,CADqB;;AAQrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,+BAJf;AAKEC,QAAQ,CAAE,MALZ,CARqB;;AAerB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,gCAJf;AAKEC,QAAQ,CAAE,OALZ,CAfqB;;AAsBrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,6BAJf;AAKEC,QAAQ,CAAE,MALZ,CAtBqB;;AA6BrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,qBAJf;AAKEC,QAAQ,CAAE,OALZ,CA7BqB;;AAoCrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,SAJf;AAKEC,QAAQ,CAAE,MALZ,CApCqB;;AA2CrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,SAJf;AAKEC,QAAQ,CAAE,KALZ,CA3CqB;;AAkDrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW;AACT,mEALJ;AAMEC,QAAQ,CAAE,KANZ,CAlDqB;;AA0DrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,mDAJf;AAKEC,QAAQ,CAAE,OALZ,CA1DqB;;AAiErB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,iCAJf;AAKEC,QAAQ,CAAE,MALZ,CAjEqB;;AAwErB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,oBAJf;AAKEC,QAAQ,CAAE,OALZ;AAMEC,MAAM,CAAE,IANV,CAxEqB;;AAgFrB;AACEL,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,6BAJf;AAKEC,QAAQ,CAAE,OALZ,CAhFqB;;AAuFrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,oBAJf;AAKEC,QAAQ,CAAE,MALZ,CAvFqB;;AA8FrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,6BAJf;AAKEC,QAAQ,CAAE,OALZ,CA9FqB;;AAqGrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,uBAJf;AAKEC,QAAQ,CAAE,OALZ,CArGqB;;AA4GrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,kBAJf;AAKEC,QAAQ,CAAE,OALZ,CA5GqB;;AAmHrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,aAJf;AAKEC,QAAQ,CAAE,MALZ,CAnHqB;;AA0HrB;AACEJ,IAAI,CAAE,WADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,8BAJf;AAKEC,QAAQ,CAAE,OALZ,CA1HqB;;AAiIrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,8CAJf;AAKEC,QAAQ,CAAE,OALZ,CAjIqB;;AAwIrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,8CAJf;AAKEC,QAAQ,CAAE,OALZ,CAxIqB;;AA+IrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,SAHV;AAIEC,WAAW,CAAE,UAJf;AAKEC,QAAQ,CAAE,OALZ;AAMEC,MAAM,CAAE,IANV,CA/IqB;;AAuJrB;AACEL,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,OAHV;AAIEC,WAAW,CAAE,QAJf;AAKEC,QAAQ,CAAE,OALZ;AAMEC,MAAM,CAAE,IANV,CAvJqB;;AA+JrB;AACEL,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,OAHV;AAIEC,WAAW,CAAE,oCAJf;AAKEC,QAAQ,CAAE,OALZ,CA/JqB;;AAsKrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,OAHV;AAIEC,WAAW,CAAE,+CAJf;AAKEC,QAAQ,CAAE,OALZ,CAtKqB;;AA6KrB;AACEJ,IAAI,CAAE,UADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,mCAJf;AAKEC,QAAQ,CAAE,OALZ,CA7KqB;;AAoLrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,OAHV;AAIEC,WAAW,CAAE,oDAJf;AAKEC,QAAQ,CAAE,OALZ,CApLqB;;AA2LrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,kCAJf;AAKEC,QAAQ,CAAE,KALZ,CA3LqB;;AAkMrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,mBAJf;AAKEC,QAAQ,CAAE,KALZ,CAlMqB;;AAyMrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,cAJf;AAKEC,QAAQ,CAAE,KALZ,CAzMqB;;AAgNrB;AACEJ,IAAI,CAAE,WADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,kBAJf;AAKEC,QAAQ,CAAE,KALZ,CAhNqB;;AAuNrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,kBAJf;AAKEC,QAAQ,CAAE,KALZ,CAvNqB;;AA8NrB;AACEJ,IAAI,CAAE,UADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,8BAJf;AAKEC,QAAQ,CAAE,KALZ,CA9NqB;;AAqOrB;AACEJ,IAAI,CAAE,OADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,kBAJf;AAKEC,QAAQ,CAAE,OALZ,CArOqB;;AA4OrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,eAJf;AAKEC,QAAQ,CAAE,OALZ,CA5OqB;;AAmPrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,iCAJf;AAKEC,QAAQ,CAAE,OALZ,CAnPqB;;AA0PrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,6BAJf;AAKEC,QAAQ,CAAE,SALZ,CA1PqB;;AAiQrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,qBAJf;AAKEC,QAAQ,CAAE,OALZ,CAjQqB;;AAwQrB;AACEJ,IAAI,CAAE,WADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,qBAJf;AAKEC,QAAQ,CAAE,OALZ,CAxQqB,CAAhB,C","sourcesContent":["/* eslint-disable max-lines */\n// List of known process signals with information about them\nexport const SIGNALS = [\n {\n name: 'SIGHUP',\n number: 1,\n action: 'terminate',\n description: 'Terminal closed',\n standard: 'posix',\n },\n {\n name: 'SIGINT',\n number: 2,\n action: 'terminate',\n description: 'User interruption with CTRL-C',\n standard: 'ansi',\n },\n {\n name: 'SIGQUIT',\n number: 3,\n action: 'core',\n description: 'User interruption with CTRL-\\\\',\n standard: 'posix',\n },\n {\n name: 'SIGILL',\n number: 4,\n action: 'core',\n description: 'Invalid machine instruction',\n standard: 'ansi',\n },\n {\n name: 'SIGTRAP',\n number: 5,\n action: 'core',\n description: 'Debugger breakpoint',\n standard: 'posix',\n },\n {\n name: 'SIGABRT',\n number: 6,\n action: 'core',\n description: 'Aborted',\n standard: 'ansi',\n },\n {\n name: 'SIGIOT',\n number: 6,\n action: 'core',\n description: 'Aborted',\n standard: 'bsd',\n },\n {\n name: 'SIGBUS',\n number: 7,\n action: 'core',\n description:\n 'Bus error due to misaligned, non-existing address or paging error',\n standard: 'bsd',\n },\n {\n name: 'SIGEMT',\n number: 7,\n action: 'terminate',\n description: 'Command should be emulated but is not implemented',\n standard: 'other',\n },\n {\n name: 'SIGFPE',\n number: 8,\n action: 'core',\n description: 'Floating point arithmetic error',\n standard: 'ansi',\n },\n {\n name: 'SIGKILL',\n number: 9,\n action: 'terminate',\n description: 'Forced termination',\n standard: 'posix',\n forced: true,\n },\n {\n name: 'SIGUSR1',\n number: 10,\n action: 'terminate',\n description: 'Application-specific signal',\n standard: 'posix',\n },\n {\n name: 'SIGSEGV',\n number: 11,\n action: 'core',\n description: 'Segmentation fault',\n standard: 'ansi',\n },\n {\n name: 'SIGUSR2',\n number: 12,\n action: 'terminate',\n description: 'Application-specific signal',\n standard: 'posix',\n },\n {\n name: 'SIGPIPE',\n number: 13,\n action: 'terminate',\n description: 'Broken pipe or socket',\n standard: 'posix',\n },\n {\n name: 'SIGALRM',\n number: 14,\n action: 'terminate',\n description: 'Timeout or timer',\n standard: 'posix',\n },\n {\n name: 'SIGTERM',\n number: 15,\n action: 'terminate',\n description: 'Termination',\n standard: 'ansi',\n },\n {\n name: 'SIGSTKFLT',\n number: 16,\n action: 'terminate',\n description: 'Stack is empty or overflowed',\n standard: 'other',\n },\n {\n name: 'SIGCHLD',\n number: 17,\n action: 'ignore',\n description: 'Child process terminated, paused or unpaused',\n standard: 'posix',\n },\n {\n name: 'SIGCLD',\n number: 17,\n action: 'ignore',\n description: 'Child process terminated, paused or unpaused',\n standard: 'other',\n },\n {\n name: 'SIGCONT',\n number: 18,\n action: 'unpause',\n description: 'Unpaused',\n standard: 'posix',\n forced: true,\n },\n {\n name: 'SIGSTOP',\n number: 19,\n action: 'pause',\n description: 'Paused',\n standard: 'posix',\n forced: true,\n },\n {\n name: 'SIGTSTP',\n number: 20,\n action: 'pause',\n description: 'Paused using CTRL-Z or \"suspend\"',\n standard: 'posix',\n },\n {\n name: 'SIGTTIN',\n number: 21,\n action: 'pause',\n description: 'Background process cannot read terminal input',\n standard: 'posix',\n },\n {\n name: 'SIGBREAK',\n number: 21,\n action: 'terminate',\n description: 'User interruption with CTRL-BREAK',\n standard: 'other',\n },\n {\n name: 'SIGTTOU',\n number: 22,\n action: 'pause',\n description: 'Background process cannot write to terminal output',\n standard: 'posix',\n },\n {\n name: 'SIGURG',\n number: 23,\n action: 'ignore',\n description: 'Socket received out-of-band data',\n standard: 'bsd',\n },\n {\n name: 'SIGXCPU',\n number: 24,\n action: 'core',\n description: 'Process timed out',\n standard: 'bsd',\n },\n {\n name: 'SIGXFSZ',\n number: 25,\n action: 'core',\n description: 'File too big',\n standard: 'bsd',\n },\n {\n name: 'SIGVTALRM',\n number: 26,\n action: 'terminate',\n description: 'Timeout or timer',\n standard: 'bsd',\n },\n {\n name: 'SIGPROF',\n number: 27,\n action: 'terminate',\n description: 'Timeout or timer',\n standard: 'bsd',\n },\n {\n name: 'SIGWINCH',\n number: 28,\n action: 'ignore',\n description: 'Terminal window size changed',\n standard: 'bsd',\n },\n {\n name: 'SIGIO',\n number: 29,\n action: 'terminate',\n description: 'I/O is available',\n standard: 'other',\n },\n {\n name: 'SIGPOLL',\n number: 29,\n action: 'terminate',\n description: 'Watched event',\n standard: 'other',\n },\n {\n name: 'SIGINFO',\n number: 29,\n action: 'ignore',\n description: 'Request for process information',\n standard: 'other',\n },\n {\n name: 'SIGPWR',\n number: 30,\n action: 'terminate',\n description: 'Device running out of power',\n standard: 'systemv',\n },\n {\n name: 'SIGSYS',\n number: 31,\n action: 'core',\n description: 'Invalid system call',\n standard: 'other',\n },\n {\n name: 'SIGUNUSED',\n number: 31,\n action: 'terminate',\n description: 'Invalid system call',\n standard: 'other',\n },\n]\n/* eslint-enable max-lines */\n"],"file":"src/core.js"} \ No newline at end of file diff --git a/node_modules/human-signals/build/src/main.d.ts b/node_modules/human-signals/build/src/main.d.ts new file mode 100644 index 0000000..2dc5ea7 --- /dev/null +++ b/node_modules/human-signals/build/src/main.d.ts @@ -0,0 +1,52 @@ +/** + * Object whose keys are signal names and values are signal objects. + */ +export declare const signalsByName: { [signalName: string]: Signal } +/** + * Object whose keys are signal numbers and values are signal objects. + */ +export declare const signalsByNumber: { [signalNumber: string]: Signal } + +export declare type SignalAction = + | 'terminate' + | 'core' + | 'ignore' + | 'pause' + | 'unpause' +export declare type SignalStandard = + | 'ansi' + | 'posix' + | 'bsd' + | 'systemv' + | 'other' + +export declare type Signal = { + /** + * Standard name of the signal, for example 'SIGINT'. + */ + name: string + /** + * Code number of the signal, for example 2. While most number are cross-platform, some are different between different OS. + */ + number: number + /** + * Human-friendly description for the signal, for example 'User interruption with CTRL-C'. + */ + description: string + /** + * Whether the current OS can handle this signal in Node.js using process.on(name, handler). The list of supported signals is OS-specific. + */ + supported: boolean + /** + * What is the default action for this signal when it is not handled. + */ + action: SignalAction + /** + * Whether the signal's default action cannot be prevented. This is true for SIGTERM, SIGKILL and SIGSTOP. + */ + forced: boolean + /** + * Which standard defined that signal. + */ + standard: SignalStandard +} diff --git a/node_modules/human-signals/build/src/main.js b/node_modules/human-signals/build/src/main.js new file mode 100644 index 0000000..88f5fd2 --- /dev/null +++ b/node_modules/human-signals/build/src/main.js @@ -0,0 +1,71 @@ +"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.signalsByNumber=exports.signalsByName=void 0;var _os=require("os"); + +var _signals=require("./signals.js"); +var _realtime=require("./realtime.js"); + + + +const getSignalsByName=function(){ +const signals=(0,_signals.getSignals)(); +return signals.reduce(getSignalByName,{}); +}; + +const getSignalByName=function( +signalByNameMemo, +{name,number,description,supported,action,forced,standard}) +{ +return{ +...signalByNameMemo, +[name]:{name,number,description,supported,action,forced,standard}}; + +}; + +const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; + + + + +const getSignalsByNumber=function(){ +const signals=(0,_signals.getSignals)(); +const length=_realtime.SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals)); + +return Object.assign({},...signalsA); +}; + +const getSignalByNumber=function(number,signals){ +const signal=findSignalByNumber(number,signals); + +if(signal===undefined){ +return{}; +} + +const{name,description,supported,action,forced,standard}=signal; +return{ +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard}}; + + +}; + + + +const findSignalByNumber=function(number,signals){ +const signal=signals.find(({name})=>_os.constants.signals[name]===number); + +if(signal!==undefined){ +return signal; +} + +return signals.find(signalA=>signalA.number===number); +}; + +const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; +//# sourceMappingURL=main.js.map \ No newline at end of file diff --git a/node_modules/human-signals/build/src/main.js.map b/node_modules/human-signals/build/src/main.js.map new file mode 100644 index 0000000..3fdcede --- /dev/null +++ b/node_modules/human-signals/build/src/main.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/main.js"],"names":["getSignalsByName","signals","reduce","getSignalByName","signalByNameMemo","name","number","description","supported","action","forced","standard","signalsByName","getSignalsByNumber","length","SIGRTMAX","signalsA","Array","from","value","getSignalByNumber","Object","assign","signal","findSignalByNumber","undefined","find","constants","signalA","signalsByNumber"],"mappings":"2HAAA;;AAEA;AACA;;;;AAIA,KAAMA,CAAAA,gBAAgB,CAAG,UAAW;AAClC,KAAMC,CAAAA,OAAO,CAAG,yBAAhB;AACA,MAAOA,CAAAA,OAAO,CAACC,MAAR,CAAeC,eAAf,CAAgC,EAAhC,CAAP;AACD,CAHD;;AAKA,KAAMA,CAAAA,eAAe,CAAG;AACtBC,gBADsB;AAEtB,CAAEC,IAAF,CAAQC,MAAR,CAAgBC,WAAhB,CAA6BC,SAA7B,CAAwCC,MAAxC,CAAgDC,MAAhD,CAAwDC,QAAxD,CAFsB;AAGtB;AACA,MAAO;AACL,GAAGP,gBADE;AAEL,CAACC,IAAD,EAAQ,CAAEA,IAAF,CAAQC,MAAR,CAAgBC,WAAhB,CAA6BC,SAA7B,CAAwCC,MAAxC,CAAgDC,MAAhD,CAAwDC,QAAxD,CAFH,CAAP;;AAID,CARD;;AAUO,KAAMC,CAAAA,aAAa,CAAGZ,gBAAgB,EAAtC,C;;;;;AAKP,KAAMa,CAAAA,kBAAkB,CAAG,UAAW;AACpC,KAAMZ,CAAAA,OAAO,CAAG,yBAAhB;AACA,KAAMa,CAAAA,MAAM,CAAGC,mBAAW,CAA1B;AACA,KAAMC,CAAAA,QAAQ,CAAGC,KAAK,CAACC,IAAN,CAAW,CAAEJ,MAAF,CAAX,CAAuB,CAACK,KAAD,CAAQb,MAAR;AACtCc,iBAAiB,CAACd,MAAD,CAASL,OAAT,CADF,CAAjB;;AAGA,MAAOoB,CAAAA,MAAM,CAACC,MAAP,CAAc,EAAd,CAAkB,GAAGN,QAArB,CAAP;AACD,CAPD;;AASA,KAAMI,CAAAA,iBAAiB,CAAG,SAASd,MAAT,CAAiBL,OAAjB,CAA0B;AAClD,KAAMsB,CAAAA,MAAM,CAAGC,kBAAkB,CAAClB,MAAD,CAASL,OAAT,CAAjC;;AAEA,GAAIsB,MAAM,GAAKE,SAAf,CAA0B;AACxB,MAAO,EAAP;AACD;;AAED,KAAM,CAAEpB,IAAF,CAAQE,WAAR,CAAqBC,SAArB,CAAgCC,MAAhC,CAAwCC,MAAxC,CAAgDC,QAAhD,EAA6DY,MAAnE;AACA,MAAO;AACL,CAACjB,MAAD,EAAU;AACRD,IADQ;AAERC,MAFQ;AAGRC,WAHQ;AAIRC,SAJQ;AAKRC,MALQ;AAMRC,MANQ;AAORC,QAPQ,CADL,CAAP;;;AAWD,CAnBD;;;;AAuBA,KAAMa,CAAAA,kBAAkB,CAAG,SAASlB,MAAT,CAAiBL,OAAjB,CAA0B;AACnD,KAAMsB,CAAAA,MAAM,CAAGtB,OAAO,CAACyB,IAAR,CAAa,CAAC,CAAErB,IAAF,CAAD,GAAcsB,cAAU1B,OAAV,CAAkBI,IAAlB,IAA4BC,MAAvD,CAAf;;AAEA,GAAIiB,MAAM,GAAKE,SAAf,CAA0B;AACxB,MAAOF,CAAAA,MAAP;AACD;;AAED,MAAOtB,CAAAA,OAAO,CAACyB,IAAR,CAAaE,OAAO,EAAIA,OAAO,CAACtB,MAAR,GAAmBA,MAA3C,CAAP;AACD,CARD;;AAUO,KAAMuB,CAAAA,eAAe,CAAGhB,kBAAkB,EAA1C,C","sourcesContent":["import { constants } from 'os'\n\nimport { getSignals } from './signals.js'\nimport { SIGRTMAX } from './realtime.js'\n\n// Retrieve `signalsByName`, an object mapping signal name to signal properties.\n// We make sure the object is sorted by `number`.\nconst getSignalsByName = function() {\n const signals = getSignals()\n return signals.reduce(getSignalByName, {})\n}\n\nconst getSignalByName = function(\n signalByNameMemo,\n { name, number, description, supported, action, forced, standard },\n) {\n return {\n ...signalByNameMemo,\n [name]: { name, number, description, supported, action, forced, standard },\n }\n}\n\nexport const signalsByName = getSignalsByName()\n\n// Retrieve `signalsByNumber`, an object mapping signal number to signal\n// properties.\n// We make sure the object is sorted by `number`.\nconst getSignalsByNumber = function() {\n const signals = getSignals()\n const length = SIGRTMAX + 1\n const signalsA = Array.from({ length }, (value, number) =>\n getSignalByNumber(number, signals),\n )\n return Object.assign({}, ...signalsA)\n}\n\nconst getSignalByNumber = function(number, signals) {\n const signal = findSignalByNumber(number, signals)\n\n if (signal === undefined) {\n return {}\n }\n\n const { name, description, supported, action, forced, standard } = signal\n return {\n [number]: {\n name,\n number,\n description,\n supported,\n action,\n forced,\n standard,\n },\n }\n}\n\n// Several signals might end up sharing the same number because of OS-specific\n// numbers, in which case those prevail.\nconst findSignalByNumber = function(number, signals) {\n const signal = signals.find(({ name }) => constants.signals[name] === number)\n\n if (signal !== undefined) {\n return signal\n }\n\n return signals.find(signalA => signalA.number === number)\n}\n\nexport const signalsByNumber = getSignalsByNumber()\n"],"file":"src/main.js"} \ No newline at end of file diff --git a/node_modules/human-signals/build/src/realtime.js b/node_modules/human-signals/build/src/realtime.js new file mode 100644 index 0000000..f665516 --- /dev/null +++ b/node_modules/human-signals/build/src/realtime.js @@ -0,0 +1,19 @@ +"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SIGRTMAX=exports.getRealtimeSignals=void 0; +const getRealtimeSignals=function(){ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal); +};exports.getRealtimeSignals=getRealtimeSignals; + +const getRealtimeSignal=function(value,index){ +return{ +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix"}; + +}; + +const SIGRTMIN=34; +const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; +//# sourceMappingURL=realtime.js.map \ No newline at end of file diff --git a/node_modules/human-signals/build/src/realtime.js.map b/node_modules/human-signals/build/src/realtime.js.map new file mode 100644 index 0000000..808bbd1 --- /dev/null +++ b/node_modules/human-signals/build/src/realtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/realtime.js"],"names":["getRealtimeSignals","length","SIGRTMAX","SIGRTMIN","Array","from","getRealtimeSignal","value","index","name","number","action","description","standard"],"mappings":";AACO,KAAMA,CAAAA,kBAAkB,CAAG,UAAW;AAC3C,KAAMC,CAAAA,MAAM,CAAGC,QAAQ,CAAGC,QAAX,CAAsB,CAArC;AACA,MAAOC,CAAAA,KAAK,CAACC,IAAN,CAAW,CAAEJ,MAAF,CAAX,CAAuBK,iBAAvB,CAAP;AACD,CAHM,C;;AAKP,KAAMA,CAAAA,iBAAiB,CAAG,SAASC,KAAT,CAAgBC,KAAhB,CAAuB;AAC/C,MAAO;AACLC,IAAI,CAAG,QAAOD,KAAK,CAAG,CAAE,EADnB;AAELE,MAAM,CAAEP,QAAQ,CAAGK,KAFd;AAGLG,MAAM,CAAE,WAHH;AAILC,WAAW,CAAE,wCAJR;AAKLC,QAAQ,CAAE,OALL,CAAP;;AAOD,CARD;;AAUA,KAAMV,CAAAA,QAAQ,CAAG,EAAjB;AACO,KAAMD,CAAAA,QAAQ,CAAG,EAAjB,C","sourcesContent":["// List of realtime signals with information about them\nexport const getRealtimeSignals = function() {\n const length = SIGRTMAX - SIGRTMIN + 1\n return Array.from({ length }, getRealtimeSignal)\n}\n\nconst getRealtimeSignal = function(value, index) {\n return {\n name: `SIGRT${index + 1}`,\n number: SIGRTMIN + index,\n action: 'terminate',\n description: 'Application-specific signal (realtime)',\n standard: 'posix',\n }\n}\n\nconst SIGRTMIN = 34\nexport const SIGRTMAX = 64\n"],"file":"src/realtime.js"} \ No newline at end of file diff --git a/node_modules/human-signals/build/src/signals.js b/node_modules/human-signals/build/src/signals.js new file mode 100644 index 0000000..ab3b387 --- /dev/null +++ b/node_modules/human-signals/build/src/signals.js @@ -0,0 +1,35 @@ +"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getSignals=void 0;var _os=require("os"); + +var _core=require("./core.js"); +var _realtime=require("./realtime.js"); + + + +const getSignals=function(){ +const realtimeSignals=(0,_realtime.getRealtimeSignals)(); +const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals; +};exports.getSignals=getSignals; + + + + + + + +const normalizeSignal=function({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard}) +{ +const{ +signals:{[name]:constantSignal}}= +_os.constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return{name,number,description,supported,action,forced,standard}; +}; +//# sourceMappingURL=signals.js.map \ No newline at end of file diff --git a/node_modules/human-signals/build/src/signals.js.map b/node_modules/human-signals/build/src/signals.js.map new file mode 100644 index 0000000..2a6b919 --- /dev/null +++ b/node_modules/human-signals/build/src/signals.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/signals.js"],"names":["getSignals","realtimeSignals","signals","SIGNALS","map","normalizeSignal","name","number","defaultNumber","description","action","forced","standard","constantSignal","constants","supported","undefined"],"mappings":"gGAAA;;AAEA;AACA;;;;AAIO,KAAMA,CAAAA,UAAU,CAAG,UAAW;AACnC,KAAMC,CAAAA,eAAe,CAAG,kCAAxB;AACA,KAAMC,CAAAA,OAAO,CAAG,CAAC,GAAGC,aAAJ,CAAa,GAAGF,eAAhB,EAAiCG,GAAjC,CAAqCC,eAArC,CAAhB;AACA,MAAOH,CAAAA,OAAP;AACD,CAJM,C;;;;;;;;AAYP,KAAMG,CAAAA,eAAe,CAAG,SAAS;AAC/BC,IAD+B;AAE/BC,MAAM,CAAEC,aAFuB;AAG/BC,WAH+B;AAI/BC,MAJ+B;AAK/BC,MAAM,CAAG,KALsB;AAM/BC,QAN+B,CAAT;AAOrB;AACD,KAAM;AACJV,OAAO,CAAE,CAAE,CAACI,IAAD,EAAQO,cAAV,CADL;AAEFC,aAFJ;AAGA,KAAMC,CAAAA,SAAS,CAAGF,cAAc,GAAKG,SAArC;AACA,KAAMT,CAAAA,MAAM,CAAGQ,SAAS,CAAGF,cAAH,CAAoBL,aAA5C;AACA,MAAO,CAAEF,IAAF,CAAQC,MAAR,CAAgBE,WAAhB,CAA6BM,SAA7B,CAAwCL,MAAxC,CAAgDC,MAAhD,CAAwDC,QAAxD,CAAP;AACD,CAdD","sourcesContent":["import { constants } from 'os'\n\nimport { SIGNALS } from './core.js'\nimport { getRealtimeSignals } from './realtime.js'\n\n// Retrieve list of know signals (including realtime) with information about\n// them\nexport const getSignals = function() {\n const realtimeSignals = getRealtimeSignals()\n const signals = [...SIGNALS, ...realtimeSignals].map(normalizeSignal)\n return signals\n}\n\n// Normalize signal:\n// - `number`: signal numbers are OS-specific. This is taken into account by\n// `os.constants.signals`. However we provide a default `number` since some\n// signals are not defined for some OS.\n// - `forced`: set default to `false`\n// - `supported`: set value\nconst normalizeSignal = function({\n name,\n number: defaultNumber,\n description,\n action,\n forced = false,\n standard,\n}) {\n const {\n signals: { [name]: constantSignal },\n } = constants\n const supported = constantSignal !== undefined\n const number = supported ? constantSignal : defaultNumber\n return { name, number, description, supported, action, forced, standard }\n}\n"],"file":"src/signals.js"} \ No newline at end of file diff --git a/node_modules/human-signals/package.json b/node_modules/human-signals/package.json new file mode 100644 index 0000000..fd1d027 --- /dev/null +++ b/node_modules/human-signals/package.json @@ -0,0 +1,64 @@ +{ + "name": "human-signals", + "version": "2.1.0", + "main": "build/src/main.js", + "files": [ + "build/src", + "!~" + ], + "scripts": { + "test": "gulp test" + }, + "husky": { + "hooks": { + "pre-push": "gulp check --full" + } + }, + "description": "Human-friendly process signals", + "keywords": [ + "signal", + "signals", + "handlers", + "error-handling", + "errors", + "interrupts", + "sigterm", + "sigint", + "irq", + "process", + "exit", + "exit-code", + "status", + "operating-system", + "es6", + "javascript", + "linux", + "macos", + "windows", + "nodejs" + ], + "license": "Apache-2.0", + "homepage": "https://git.io/JeluP", + "repository": "ehmicky/human-signals", + "bugs": { + "url": "https://github.com/ehmicky/human-signals/issues" + }, + "author": "ehmicky (https://github.com/ehmicky)", + "directories": { + "lib": "src", + "test": "test" + }, + "types": "build/src/main.d.ts", + "dependencies": {}, + "devDependencies": { + "@ehmicky/dev-tasks": "^0.31.9", + "ajv": "^6.12.0", + "ava": "^3.5.0", + "gulp": "^4.0.2", + "husky": "^4.2.3", + "test-each": "^2.0.0" + }, + "engines": { + "node": ">=10.17.0" + } +} diff --git a/node_modules/ignore/LICENSE-MIT b/node_modules/ignore/LICENSE-MIT new file mode 100644 index 0000000..825533e --- /dev/null +++ b/node_modules/ignore/LICENSE-MIT @@ -0,0 +1,21 @@ +Copyright (c) 2013 Kael Zhang , contributors +http://kael.me/ + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/ignore/README.md b/node_modules/ignore/README.md new file mode 100644 index 0000000..50d8882 --- /dev/null +++ b/node_modules/ignore/README.md @@ -0,0 +1,412 @@ + + + + + + + + + + + + + +
LinuxOS XWindowsCoverageDownloads
+ + Build Status + + + Windows Build Status + + + Coverage Status + + + npm module downloads per month +
+ +# ignore + +`ignore` is a manager, filter and parser which implemented in pure JavaScript according to the [.gitignore spec 2.22.1](http://git-scm.com/docs/gitignore). + +`ignore` is used by eslint, gitbook and [many others](https://www.npmjs.com/browse/depended/ignore). + +Pay **ATTENTION** that [`minimatch`](https://www.npmjs.org/package/minimatch) (which used by `fstream-ignore`) does not follow the gitignore spec. + +To filter filenames according to a .gitignore file, I recommend this npm package, `ignore`. + +To parse an `.npmignore` file, you should use `minimatch`, because an `.npmignore` file is parsed by npm using `minimatch` and it does not work in the .gitignore way. + +### Tested on + +`ignore` is fully tested, and has more than **five hundreds** of unit tests. + +- Linux + Node: `0.8` - `7.x` +- Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. + +Actually, `ignore` does not rely on any versions of node specially. + +Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). + +## Table Of Main Contents + +- [Usage](#usage) +- [`Pathname` Conventions](#pathname-conventions) +- See Also: + - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. +- [Upgrade Guide](#upgrade-guide) + +## Install + +```sh +npm i ignore +``` + +## Usage + +```js +import ignore from 'ignore' +const ig = ignore().add(['.abc/*', '!.abc/d/']) +``` + +### Filter the given paths + +```js +const paths = [ + '.abc/a.js', // filtered out + '.abc/d/e.js' // included +] + +ig.filter(paths) // ['.abc/d/e.js'] +ig.ignores('.abc/a.js') // true +``` + +### As the filter function + +```js +paths.filter(ig.createFilter()); // ['.abc/d/e.js'] +``` + +### Win32 paths will be handled + +```js +ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) +// if the code above runs on windows, the result will be +// ['.abc\\d\\e.js'] +``` + +## Why another ignore? + +- `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. + +- `ignore` only contains utility methods to filter paths according to the specified ignore rules, so + - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. + - `ignore` don't cares about sub-modules of git projects. + +- Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: + - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. + - '`**/foo`' should match '`foo`' anywhere. + - Prevent re-including a file if a parent directory of that file is excluded. + - Handle trailing whitespaces: + - `'a '`(one space) should not match `'a '`(two spaces). + - `'a \ '` matches `'a '` + - All test cases are verified with the result of `git check-ignore`. + +# Methods + +## .add(pattern: string | Ignore): this +## .add(patterns: Array): this + +- **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance +- **patterns** `Array` Array of ignore patterns. + +Adds a rule or several rules to the current manager. + +Returns `this` + +Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. + +```js +ignore().add('#abc').ignores('#abc') // false +ignore().add('\\#abc').ignores('#abc') // true +``` + +`pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: + +```js +ignore() +.add(fs.readFileSync(filenameOfGitignore).toString()) +.filter(filenames) +``` + +`pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. + +## .addIgnoreFile(path) + +REMOVED in `3.x` for now. + +To upgrade `ignore@2.x` up to `3.x`, use + +```js +import fs from 'fs' + +if (fs.existsSync(filename)) { + ignore().add(fs.readFileSync(filename).toString()) +} +``` + +instead. + +## .filter(paths: Array<Pathname>): Array<Pathname> + +```ts +type Pathname = string +``` + +Filters the given array of pathnames, and returns the filtered array. + +- **paths** `Array.` The array of `pathname`s to be filtered. + +### `Pathname` Conventions: + +#### 1. `Pathname` should be a `path.relative()`d pathname + +`Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory, + +```js +// WRONG, an error will be thrown +ig.ignores('./abc') + +// WRONG, for it will never happen, and an error will be thrown +// If the gitignore rule locates at the root directory, +// `'/abc'` should be changed to `'abc'`. +// ``` +// path.relative('/', '/abc') -> 'abc' +// ``` +ig.ignores('/abc') + +// WRONG, that it is an absolute path on Windows, an error will be thrown +ig.ignores('C:\\abc') + +// Right +ig.ignores('abc') + +// Right +ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' +``` + +In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. + +Suppose the dir structure is: + +``` +/path/to/your/repo + |-- a + | |-- a.js + | + |-- .b + | + |-- .c + |-- .DS_store +``` + +Then the `paths` might be like this: + +```js +[ + 'a/a.js' + '.b', + '.c/.DS_store' +] +``` + +#### 2. filenames and dirnames + +`node-ignore` does NO `fs.stat` during path matching, so for the example below: + +```js +// First, we add a ignore pattern to ignore a directory +ig.add('config/') + +// `ig` does NOT know if 'config', in the real world, +// is a normal file, directory or something. + +ig.ignores('config') +// `ig` treats `config` as a file, so it returns `false` + +ig.ignores('config/') +// returns `true` +``` + +Specially for people who develop some library based on `node-ignore`, it is important to understand that. + +Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: + +```js +import glob from 'glob' + +glob('**', { + // Adds a / character to directory matches. + mark: true +}, (err, files) => { + if (err) { + return console.error(err) + } + + let filtered = ignore().add(patterns).filter(files) + console.log(filtered) +}) +``` + +## .ignores(pathname: Pathname): boolean + +> new in 3.2.0 + +Returns `Boolean` whether `pathname` should be ignored. + +```js +ig.ignores('.abc/a.js') // true +``` + +## .createFilter() + +Creates a filter function which could filter an array of paths with `Array.prototype.filter`. + +Returns `function(path)` the filter function. + +## .test(pathname: Pathname) since 5.0.0 + +Returns `TestResult` + +```ts +interface TestResult { + ignored: boolean + // true if the `pathname` is finally unignored by some negative pattern + unignored: boolean +} +``` + +- `{ignored: true, unignored: false}`: the `pathname` is ignored +- `{ignored: false, unignored: true}`: the `pathname` is unignored +- `{ignored: false, unignored: false}`: the `pathname` is never matched by any ignore rules. + +## static `ignore.isPathValid(pathname): boolean` since 5.0.0 + +Check whether the `pathname` is an valid `path.relative()`d path according to the [convention](#1-pathname-should-be-a-pathrelatived-pathname). + +This method is **NOT** used to check if an ignore pattern is valid. + +```js +ignore.isPathValid('./foo') // false +``` + +## ignore(options) + +### `options.ignorecase` since 4.0.0 + +Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (the default value), otherwise case sensitive. + +```js +const ig = ignore({ + ignorecase: false +}) + +ig.add('*.png') + +ig.ignores('*.PNG') // false +``` + +### `options.ignoreCase?: boolean` since 5.2.0 + +Which is alternative to `options.ignoreCase` + +### `options.allowRelativePaths?: boolean` since 5.2.0 + +This option brings backward compatibility with projects which based on `ignore@4.x`. If `options.allowRelativePaths` is `true`, `ignore` will not check whether the given path to be tested is [`path.relative()`d](#pathname-conventions). + +However, passing a relative path, such as `'./foo'` or `'../foo'`, to test if it is ignored or not is not a good practise, which might lead to unexpected behavior + +```js +ignore({ + allowRelativePaths: true +}).ignores('../foo/bar.js') // And it will not throw +``` + +**** + +# Upgrade Guide + +## Upgrade 4.x -> 5.x + +Since `5.0.0`, if an invalid `Pathname` passed into `ig.ignores()`, an error will be thrown, unless `options.allowRelative = true` is passed to the `Ignore` factory. + +While `ignore < 5.0.0` did not make sure what the return value was, as well as + +```ts +.ignores(pathname: Pathname): boolean + +.filter(pathnames: Array): Array + +.createFilter(): (pathname: Pathname) => boolean + +.test(pathname: Pathname): {ignored: boolean, unignored: boolean} +``` + +See the convention [here](#1-pathname-should-be-a-pathrelatived-pathname) for details. + +If there are invalid pathnames, the conversion and filtration should be done by users. + +```js +import {isPathValid} from 'ignore' // introduced in 5.0.0 + +const paths = [ + // invalid + ////////////////// + '', + false, + '../foo', + '.', + ////////////////// + + // valid + 'foo' +] +.filter(isValidPath) + +ig.filter(paths) +``` + +## Upgrade 3.x -> 4.x + +Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: + +```js +var ignore = require('ignore/legacy') +``` + +## Upgrade 2.x -> 3.x + +- All `options` of 2.x are unnecessary and removed, so just remove them. +- `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. +- `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. + +**** + +# Collaborators + +- [@whitecolor](https://github.com/whitecolor) *Alex* +- [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* +- [@azproduction](https://github.com/azproduction) *Mikhail Davydov* +- [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* +- [@JanMattner](https://github.com/JanMattner) *Jan Mattner* +- [@ntwb](https://github.com/ntwb) *Stephen Edgar* +- [@kasperisager](https://github.com/kasperisager) *Kasper Isager* +- [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* diff --git a/node_modules/ignore/index.d.ts b/node_modules/ignore/index.d.ts new file mode 100644 index 0000000..520eafa --- /dev/null +++ b/node_modules/ignore/index.d.ts @@ -0,0 +1,61 @@ +type Pathname = string + +interface TestResult { + ignored: boolean + unignored: boolean +} + +export interface Ignore { + /** + * Adds one or several rules to the current manager. + * @param {string[]} patterns + * @returns IgnoreBase + */ + add(patterns: string | Ignore | readonly (string | Ignore)[]): this + + /** + * Filters the given array of pathnames, and returns the filtered array. + * NOTICE that each path here should be a relative path to the root of your repository. + * @param paths the array of paths to be filtered. + * @returns The filtered array of paths + */ + filter(pathnames: readonly Pathname[]): Pathname[] + + /** + * Creates a filter function which could filter + * an array of paths with Array.prototype.filter. + */ + createFilter(): (pathname: Pathname) => boolean + + /** + * Returns Boolean whether pathname should be ignored. + * @param {string} pathname a path to check + * @returns boolean + */ + ignores(pathname: Pathname): boolean + + /** + * Returns whether pathname should be ignored or unignored + * @param {string} pathname a path to check + * @returns TestResult + */ + test(pathname: Pathname): TestResult +} + +interface Options { + ignorecase?: boolean + // For compatibility + ignoreCase?: boolean + allowRelativePaths?: boolean +} + +/** + * Creates new ignore manager. + */ +declare function ignore(options?: Options): Ignore + +declare namespace ignore { + export function isPathValid (pathname: string): boolean +} + +export default ignore diff --git a/node_modules/ignore/index.js b/node_modules/ignore/index.js new file mode 100644 index 0000000..a25577f --- /dev/null +++ b/node_modules/ignore/index.js @@ -0,0 +1,618 @@ +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const EMPTY = '' +const SPACE = ' ' +const ESCAPE = '\\' +const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/ +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ +const REGEX_SPLITALL_CRLF = /\r?\n/g +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ + +const SLASH = '/' + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +let TMP_KEY_IGNORE = 'node-ignore' +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol.for('node-ignore') +} +const KEY_IGNORE = TMP_KEY_IGNORE + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g + +const RETURN_FALSE = () => false + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +) + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes + return slashes.slice(0, length - length % 2) +} + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? SPACE + : EMPTY + ], + + // replace (\ ) with ' ' + [ + /\\\s/g, + () => SPACE + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ + + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], + + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], + + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], + + // normal intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + + // 'abc.*/' -> go + // 'abc.*' -> skip this rule, + // coz trailing single wildcard will be handed by [trailing wildcard] + /(^|[^\\]+)(\\\*)+(?=.+)/g, + + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1, p2) => { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + const unescaped = p2.replace(/\\\*/g, '[^\\/]*') + return p1 + unescaped + } + ], + + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], + + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], + + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. + + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], + + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' + + return `${prefix}(?=$|\\/$)` + } + ], +] + +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null) + +// @param {pattern} +const makeRegex = (pattern, ignoreCase) => { + let source = regexCache[pattern] + + if (!source) { + source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ) + regexCache[pattern] = source + } + + return ignoreCase + ? new RegExp(source, 'i') + : new RegExp(source) +} + +const isString = subject => typeof subject === 'string' + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) + +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin + this.pattern = pattern + this.negative = negative + this.regex = regex + } +} + +const createRule = (pattern, ignoreCase) => { + const origin = pattern + let negative = false + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') + + const regex = makeRegex(pattern, ignoreCase) + + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +} + +const throwError = (message, Ctor) => { + throw new Ctor(message) +} + +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d' + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +} + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + +checkPath.isNotRelative = isNotRelative +checkPath.convert = p => p + +class Ignore { + constructor ({ + ignorecase = true, + ignoreCase = ignorecase, + allowRelativePaths = false + } = {}) { + define(this, KEY_IGNORE, true) + + this._rules = [] + this._ignoreCase = ignoreCase + this._allowRelativePaths = allowRelativePaths + this._initCache() + } + + _initCache () { + this._ignoreCache = Object.create(null) + this._testCache = Object.create(null) + } + + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return + } + + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignoreCase) + this._added = true + this._rules.push(rule) + } + } + + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false + + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this) + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() + } + + return this + } + + // legacy + addPattern (pattern) { + return this.add(pattern) + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false + let unignored = false + + this._rules.forEach(rule => { + const {negative} = rule + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } + + const matched = rule.regex.test(path) + + if (matched) { + ignored = !negative + unignored = negative + } + }) + + return { + ignored, + unignored + } + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath) + + checkPath( + path, + originalPath, + this._allowRelativePaths + ? RETURN_FALSE + : throwError + ) + + return this._t(path, cache, checkUnignored, slices) + } + + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) + } + + slices.pop() + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} + +const factory = options => new Ignore(options) + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, RETURN_FALSE) + +factory.isPathValid = isPathValid + +// Fixes typescript +factory.default = factory + +module.exports = factory + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/') + + checkPath.convert = makePosix + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path) +} diff --git a/node_modules/ignore/legacy.js b/node_modules/ignore/legacy.js new file mode 100644 index 0000000..8518b7c --- /dev/null +++ b/node_modules/ignore/legacy.js @@ -0,0 +1,539 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +// A simple implementation of make-array +function makeArray(subject) { + return Array.isArray(subject) ? subject : [subject]; +} +var EMPTY = ''; +var SPACE = ' '; +var ESCAPE = '\\'; +var REGEX_TEST_BLANK_LINE = /^\s+$/; +var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/; +var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +var REGEX_SPLITALL_CRLF = /\r?\n/g; +// /foo, +// ./foo, +// ../foo, +// . +// .. +var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; +var SLASH = '/'; + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +var TMP_KEY_IGNORE = 'node-ignore'; +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol["for"]('node-ignore'); +} +var KEY_IGNORE = TMP_KEY_IGNORE; +var define = function define(object, key, value) { + return Object.defineProperty(object, key, { + value: value + }); +}; +var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; +var RETURN_FALSE = function RETURN_FALSE() { + return false; +}; + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +var sanitizeRange = function sanitizeRange(range) { + return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) { + return from.charCodeAt(0) <= to.charCodeAt(0) ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY; + }); +}; + +// See fixtures #59 +var cleanRangeBackSlash = function cleanRangeBackSlash(slashes) { + var length = slashes.length; + return slashes.slice(0, length - length % 2); +}; + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +var REPLACERS = [ +// > Trailing spaces are ignored unless they are quoted with backslash ("\") +[ +// (a\ ) -> (a ) +// (a ) -> (a) +// (a \ ) -> (a ) +/\\?\s+$/, function (match) { + return match.indexOf('\\') === 0 ? SPACE : EMPTY; +}], +// replace (\ ) with ' ' +[/\\\s/g, function () { + return SPACE; +}], +// Escape metacharacters +// which is written down by users but means special for regular expressions. + +// > There are 12 characters with special meanings: +// > - the backslash \, +// > - the caret ^, +// > - the dollar sign $, +// > - the period or dot ., +// > - the vertical bar or pipe symbol |, +// > - the question mark ?, +// > - the asterisk or star *, +// > - the plus sign +, +// > - the opening parenthesis (, +// > - the closing parenthesis ), +// > - and the opening square bracket [, +// > - the opening curly brace {, +// > These special characters are often called "metacharacters". +[/[\\$.|*+(){^]/g, function (match) { + return "\\".concat(match); +}], [ +// > a question mark (?) matches a single character +/(?!\\)\?/g, function () { + return '[^/]'; +}], +// leading slash +[ +// > A leading slash matches the beginning of the pathname. +// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". +// A leading slash matches the beginning of the pathname +/^\//, function () { + return '^'; +}], +// replace special metacharacter slash after the leading slash +[/\//g, function () { + return '\\/'; +}], [ +// > A leading "**" followed by a slash means match in all directories. +// > For example, "**/foo" matches file or directory "foo" anywhere, +// > the same as pattern "foo". +// > "**/foo/bar" matches file or directory "bar" anywhere that is directly +// > under directory "foo". +// Notice that the '*'s have been replaced as '\\*' +/^\^*\\\*\\\*\\\//, +// '**/foo' <-> 'foo' +function () { + return '^(?:.*\\/)?'; +}], +// starting +[ +// there will be no leading '/' +// (which has been replaced by section "leading slash") +// If starts with '**', adding a '^' to the regular expression also works +/^(?=[^^])/, function startingReplacer() { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^'; +}], +// two globstars +[ +// Use lookahead assertions so that we could match more than one `'/**'` +/\\\/\\\*\\\*(?=\\\/|$)/g, +// Zero, one or several directories +// should not use '*', or it will be replaced by the next replacer + +// Check if it is not the last `'/**'` +function (_, index, str) { + return index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+'; +}], +// normal intermediate wildcards +[ +// Never replace escaped '*' +// ignore rule '\*' will match the path '*' + +// 'abc.*/' -> go +// 'abc.*' -> skip this rule, +// coz trailing single wildcard will be handed by [trailing wildcard] +/(^|[^\\]+)(\\\*)+(?=.+)/g, +// '*.js' matches '.js' +// '*.js' doesn't match 'abc' +function (_, p1, p2) { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + var unescaped = p2.replace(/\\\*/g, '[^\\/]*'); + return p1 + unescaped; +}], [ +// unescape, revert step 3 except for back slash +// For example, if a user escape a '\\*', +// after step 3, the result will be '\\\\\\*' +/\\\\\\(?=[$.|*+(){^])/g, function () { + return ESCAPE; +}], [ +// '\\\\' -> '\\' +/\\\\/g, function () { + return ESCAPE; +}], [ +// > The range notation, e.g. [a-zA-Z], +// > can be used to match one of the characters in a range. + +// `\` is escaped by step 3 +/(\\)?\[([^\]/]*?)(\\*)($|\])/g, function (match, leadEscape, range, endEscape, close) { + return leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? "\\[".concat(range).concat(cleanRangeBackSlash(endEscape)).concat(close) : close === ']' ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? "[".concat(sanitizeRange(range)).concat(endEscape, "]") // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' : '[]'; +}], +// ending +[ +// 'js' will not match 'js.' +// 'ab' will not match 'abc' +/(?:[^*])$/, +// WTF! +// https://git-scm.com/docs/gitignore +// changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) +// which re-fixes #24, #38 + +// > If there is a separator at the end of the pattern then the pattern +// > will only match directories, otherwise the pattern can match both +// > files and directories. + +// 'js*' will not match 'a.js' +// 'js/' will not match 'a.js' +// 'js' will match 'a.js' and 'a.js/' +function (match) { + return /\/$/.test(match) + // foo/ will not match 'foo' + ? "".concat(match, "$") // foo matches 'foo' and 'foo/' + : "".concat(match, "(?=$|\\/$)"); +}], +// trailing wildcard +[/(\^|\\\/)?\\\*$/, function (_, p1) { + var prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? "".concat(p1, "[^/]+") // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + return "".concat(prefix, "(?=$|\\/$)"); +}]]; + +// A simple cache, because an ignore rule only has only one certain meaning +var regexCache = Object.create(null); + +// @param {pattern} +var makeRegex = function makeRegex(pattern, ignoreCase) { + var source = regexCache[pattern]; + if (!source) { + source = REPLACERS.reduce(function (prev, current) { + return prev.replace(current[0], current[1].bind(pattern)); + }, pattern); + regexCache[pattern] = source; + } + return ignoreCase ? new RegExp(source, 'i') : new RegExp(source); +}; +var isString = function isString(subject) { + return typeof subject === 'string'; +}; + +// > A blank line matches no files, so it can serve as a separator for readability. +var checkPattern = function checkPattern(pattern) { + return pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; +}; +var splitPattern = function splitPattern(pattern) { + return pattern.split(REGEX_SPLITALL_CRLF); +}; +var IgnoreRule = /*#__PURE__*/_createClass(function IgnoreRule(origin, pattern, negative, regex) { + _classCallCheck(this, IgnoreRule); + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex; +}); +var createRule = function createRule(pattern, ignoreCase) { + var origin = pattern; + var negative = false; + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + var regex = makeRegex(pattern, ignoreCase); + return new IgnoreRule(origin, pattern, negative, regex); +}; +var throwError = function throwError(message, Ctor) { + throw new Ctor(message); +}; +var checkPath = function checkPath(path, originalPath, doThrow) { + if (!isString(path)) { + return doThrow("path must be a string, but got `".concat(originalPath, "`"), TypeError); + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow("path must not be empty", TypeError); + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + var r = '`path.relative()`d'; + return doThrow("path should be a ".concat(r, " string, but got \"").concat(originalPath, "\""), RangeError); + } + return true; +}; +var isNotRelative = function isNotRelative(path) { + return REGEX_TEST_INVALID_PATH.test(path); +}; +checkPath.isNotRelative = isNotRelative; +checkPath.convert = function (p) { + return p; +}; +var Ignore = /*#__PURE__*/function () { + function Ignore() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$ignorecase = _ref.ignorecase, + ignorecase = _ref$ignorecase === void 0 ? true : _ref$ignorecase, + _ref$ignoreCase = _ref.ignoreCase, + ignoreCase = _ref$ignoreCase === void 0 ? ignorecase : _ref$ignoreCase, + _ref$allowRelativePat = _ref.allowRelativePaths, + allowRelativePaths = _ref$allowRelativePat === void 0 ? false : _ref$allowRelativePat; + _classCallCheck(this, Ignore); + define(this, KEY_IGNORE, true); + this._rules = []; + this._ignoreCase = ignoreCase; + this._allowRelativePaths = allowRelativePaths; + this._initCache(); + } + _createClass(Ignore, [{ + key: "_initCache", + value: function _initCache() { + this._ignoreCache = Object.create(null); + this._testCache = Object.create(null); + } + }, { + key: "_addPattern", + value: function _addPattern(pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + if (checkPattern(pattern)) { + var rule = createRule(pattern, this._ignoreCase); + this._added = true; + this._rules.push(rule); + } + } + + // @param {Array | string | Ignore} pattern + }, { + key: "add", + value: function add(pattern) { + this._added = false; + makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache(); + } + return this; + } + + // legacy + }, { + key: "addPattern", + value: function addPattern(pattern) { + return this.add(pattern); + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + }, { + key: "_testOne", + value: function _testOne(path, checkUnignored) { + var ignored = false; + var unignored = false; + this._rules.forEach(function (rule) { + var negative = rule.negative; + if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) { + return; + } + var matched = rule.regex.test(path); + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + return { + ignored: ignored, + unignored: unignored + }; + } + + // @returns {TestResult} + }, { + key: "_test", + value: function _test(originalPath, cache, checkUnignored, slices) { + var path = originalPath + // Supports nullable path + && checkPath.convert(originalPath); + checkPath(path, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError); + return this._t(path, cache, checkUnignored, slices); + } + }, { + key: "_t", + value: function _t(path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path]; + } + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH); + } + slices.pop(); + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored); + } + var parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices); + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent : this._testOne(path, checkUnignored); + } + }, { + key: "ignores", + value: function ignores(path) { + return this._test(path, this._ignoreCache, false).ignored; + } + }, { + key: "createFilter", + value: function createFilter() { + var _this = this; + return function (path) { + return !_this.ignores(path); + }; + } + }, { + key: "filter", + value: function filter(paths) { + return makeArray(paths).filter(this.createFilter()); + } + + // @returns {TestResult} + }, { + key: "test", + value: function test(path) { + return this._test(path, this._testCache, true); + } + }]); + return Ignore; +}(); +var factory = function factory(options) { + return new Ignore(options); +}; +var isPathValid = function isPathValid(path) { + return checkPath(path && checkPath.convert(path), path, RETURN_FALSE); +}; +factory.isPathValid = isPathValid; + +// Fixes typescript +factory["default"] = factory; +module.exports = factory; + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( +// Detect `process` so that it can run in browsers. +typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) { + /* eslint no-control-regex: "off" */ + var makePosix = function makePosix(str) { + return /^\\\\\?\\/.test(str) || /[\0-\x1F"<>\|]+/.test(str) ? str : str.replace(/\\/g, '/'); + }; + checkPath.convert = makePosix; + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + var REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = function (path) { + return REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path); + }; +} diff --git a/node_modules/ignore/package.json b/node_modules/ignore/package.json new file mode 100644 index 0000000..fe5498d --- /dev/null +++ b/node_modules/ignore/package.json @@ -0,0 +1,73 @@ +{ + "name": "ignore", + "version": "5.2.4", + "description": "Ignore is a manager and filter for .gitignore rules, the one used by eslint, gitbook and many others.", + "files": [ + "legacy.js", + "index.js", + "index.d.ts", + "LICENSE-MIT" + ], + "scripts": { + "prepublishOnly": "npm run build", + "build": "babel -o legacy.js index.js", + "test:lint": "eslint .", + "test:tsc": "tsc ./test/ts/simple.ts --lib ES6", + "test:ts": "node ./test/ts/simple.js", + "tap": "tap --reporter classic", + "test:git": "npm run tap test/git-check-ignore.js", + "test:ignore": "npm run tap test/ignore.js", + "test:others": "npm run tap test/others.js", + "test:cases": "npm run tap test/*.js -- --coverage", + "test:no-coverage": "npm run tap test/*.js -- --no-check-coverage", + "test:only": "npm run test:lint && npm run test:tsc && npm run test:ts && npm run test:cases", + "test": "npm run test:only", + "test:win32": "IGNORE_TEST_WIN32=1 npm run test", + "report": "tap --coverage-report=html", + "posttest": "npm run report && codecov" + }, + "repository": { + "type": "git", + "url": "git@github.com:kaelzhang/node-ignore.git" + }, + "keywords": [ + "ignore", + ".gitignore", + "gitignore", + "npmignore", + "rules", + "manager", + "filter", + "regexp", + "regex", + "fnmatch", + "glob", + "asterisks", + "regular-expression" + ], + "author": "kael", + "license": "MIT", + "bugs": { + "url": "https://github.com/kaelzhang/node-ignore/issues" + }, + "devDependencies": { + "@babel/cli": "^7.19.3", + "@babel/core": "^7.20.5", + "@babel/preset-env": "^7.20.2", + "codecov": "^3.8.2", + "debug": "^4.3.4", + "eslint": "^8.30.0", + "eslint-config-ostai": "^3.0.0", + "eslint-plugin-import": "^2.26.0", + "mkdirp": "^1.0.4", + "pre-suf": "^1.1.1", + "rimraf": "^3.0.2", + "spawn-sync": "^2.0.0", + "tap": "^16.3.2", + "tmp": "0.2.1", + "typescript": "^4.9.4" + }, + "engines": { + "node": ">= 4" + } +} diff --git a/node_modules/import-fresh/index.d.ts b/node_modules/import-fresh/index.d.ts new file mode 100644 index 0000000..36d7e20 --- /dev/null +++ b/node_modules/import-fresh/index.d.ts @@ -0,0 +1,30 @@ +/** +Import a module while bypassing the cache. + +@example +``` +// foo.js +let i = 0; +module.exports = () => ++i; + +// index.js +import importFresh = require('import-fresh'); + +require('./foo')(); +//=> 1 + +require('./foo')(); +//=> 2 + +importFresh('./foo')(); +//=> 1 + +importFresh('./foo')(); +//=> 1 + +const foo = importFresh('./foo'); +``` +*/ +declare function importFresh(moduleId: string): T; + +export = importFresh; diff --git a/node_modules/import-fresh/index.js b/node_modules/import-fresh/index.js new file mode 100644 index 0000000..0a4c5d5 --- /dev/null +++ b/node_modules/import-fresh/index.js @@ -0,0 +1,33 @@ +'use strict'; +const path = require('path'); +const resolveFrom = require('resolve-from'); +const parentModule = require('parent-module'); + +module.exports = moduleId => { + if (typeof moduleId !== 'string') { + throw new TypeError('Expected a string'); + } + + const parentPath = parentModule(__filename); + + const cwd = parentPath ? path.dirname(parentPath) : __dirname; + const filePath = resolveFrom(cwd, moduleId); + + const oldModule = require.cache[filePath]; + // Delete itself from module parent + if (oldModule && oldModule.parent) { + let i = oldModule.parent.children.length; + + while (i--) { + if (oldModule.parent.children[i].id === filePath) { + oldModule.parent.children.splice(i, 1); + } + } + } + + delete require.cache[filePath]; // Delete module from cache + + const parent = require.cache[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step + + return parent === undefined ? require(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require +}; diff --git a/node_modules/import-fresh/license b/node_modules/import-fresh/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/import-fresh/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/import-fresh/package.json b/node_modules/import-fresh/package.json new file mode 100644 index 0000000..0c09362 --- /dev/null +++ b/node_modules/import-fresh/package.json @@ -0,0 +1,43 @@ +{ + "name": "import-fresh", + "version": "3.3.0", + "description": "Import a module while bypassing the cache", + "license": "MIT", + "repository": "sindresorhus/import-fresh", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd", + "heapdump": "node heapdump.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "require", + "cache", + "uncache", + "uncached", + "module", + "fresh", + "bypass" + ], + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "devDependencies": { + "ava": "^1.0.1", + "heapdump": "^0.3.12", + "tsd": "^0.7.3", + "xo": "^0.23.0" + } +} diff --git a/node_modules/import-fresh/readme.md b/node_modules/import-fresh/readme.md new file mode 100644 index 0000000..bd14c79 --- /dev/null +++ b/node_modules/import-fresh/readme.md @@ -0,0 +1,48 @@ +# import-fresh + +> Import a module while bypassing the [cache](https://nodejs.org/api/modules.html#modules_caching) + +Useful for testing purposes when you need to freshly import a module. + +## Install + +``` +$ npm install import-fresh +``` + +## Usage + +```js +// foo.js +let i = 0; +module.exports = () => ++i; +``` + +```js +const importFresh = require('import-fresh'); + +require('./foo')(); +//=> 1 + +require('./foo')(); +//=> 2 + +importFresh('./foo')(); +//=> 1 + +importFresh('./foo')(); +//=> 1 +``` + +## import-fresh for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of import-fresh and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-import-fresh?utm_source=npm-import-fresh&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Related + +- [clear-module](https://github.com/sindresorhus/clear-module) - Clear a module from the import cache +- [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path +- [import-cwd](https://github.com/sindresorhus/import-cwd) - Import a module from the current working directory +- [import-lazy](https://github.com/sindresorhus/import-lazy) - Import modules lazily diff --git a/node_modules/import-local/fixtures/cli.js b/node_modules/import-local/fixtures/cli.js new file mode 100755 index 0000000..46b939f --- /dev/null +++ b/node_modules/import-local/fixtures/cli.js @@ -0,0 +1,7 @@ +#!/usr/bin/env node +'use strict'; +const importLocal = require('..'); + +if (importLocal(__filename)) { + console.log('local'); +} diff --git a/node_modules/import-local/index.js b/node_modules/import-local/index.js new file mode 100644 index 0000000..28c9c60 --- /dev/null +++ b/node_modules/import-local/index.js @@ -0,0 +1,24 @@ +'use strict'; +const path = require('path'); +const {fileURLToPath} = require('url'); +const resolveCwd = require('resolve-cwd'); +const pkgDir = require('pkg-dir'); + +module.exports = filename => { + const normalizedFilename = filename.startsWith('file://') ? fileURLToPath(filename) : filename; + const globalDir = pkgDir.sync(path.dirname(normalizedFilename)); + const relativePath = path.relative(globalDir, normalizedFilename); + const pkg = require(path.join(globalDir, 'package.json')); + const localFile = resolveCwd.silent(path.join(pkg.name, relativePath)); + const localNodeModules = path.join(process.cwd(), 'node_modules'); + + const filenameInLocalNodeModules = !path.relative(localNodeModules, normalizedFilename).startsWith('..') && + // On Windows, if `localNodeModules` and `normalizedFilename` are on different partitions, `path.relative()` returns the value of `normalizedFilename`, resulting in `filenameInLocalNodeModules` incorrectly becoming `true`. + path.parse(localNodeModules).root === path.parse(normalizedFilename).root; + + // Use `path.relative()` to detect local package installation, + // because __filename's case is inconsistent on Windows + // Can use `===` when targeting Node.js 8 + // See https://github.com/nodejs/node/issues/6624 + return !filenameInLocalNodeModules && localFile && path.relative(localFile, normalizedFilename) !== '' && require(localFile); +}; diff --git a/node_modules/import-local/license b/node_modules/import-local/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/import-local/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/import-local/package.json b/node_modules/import-local/package.json new file mode 100644 index 0000000..0de45f0 --- /dev/null +++ b/node_modules/import-local/package.json @@ -0,0 +1,52 @@ +{ + "name": "import-local", + "version": "3.1.0", + "description": "Let a globally installed package use a locally installed version of itself if available", + "license": "MIT", + "repository": "sindresorhus/import-local", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "fixtures/cli.js" + ], + "keywords": [ + "import", + "local", + "require", + "resolve", + "global", + "version", + "prefer", + "cli" + ], + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "devDependencies": { + "ava": "2.1.0", + "cpy": "^7.0.1", + "del": "^4.1.1", + "execa": "^2.0.1", + "xo": "^0.24.0" + }, + "xo": { + "ignores": [ + "fixtures" + ] + } +} diff --git a/node_modules/import-local/readme.md b/node_modules/import-local/readme.md new file mode 100644 index 0000000..cc5244f --- /dev/null +++ b/node_modules/import-local/readme.md @@ -0,0 +1,37 @@ +# import-local + +> Let a globally installed package use a locally installed version of itself if available + +Useful for CLI tools that want to defer to the user's locally installed version when available, but still work if it's not installed locally. For example, [AVA](https://avajs.dev) and [XO](https://github.com/xojs/xo) uses this method. + +## Install + +```sh +npm install import-local +``` + +## Usage + +```js +import importLocal from 'import-local'; + +if (importLocal(import.meta.url)) { + console.log('Using local version of this package'); +} else { + // Code for both global and local version here… +} +``` + +You can also pass in `__filename` when used in a CommonJS context. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/imurmurhash/README.md b/node_modules/imurmurhash/README.md new file mode 100644 index 0000000..f35b20a --- /dev/null +++ b/node_modules/imurmurhash/README.md @@ -0,0 +1,122 @@ +iMurmurHash.js +============== + +An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). + +This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. + +Installation +------------ + +To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. + +```html + + +``` + +--- + +To use iMurmurHash in Node.js, install the module using NPM: + +```bash +npm install imurmurhash +``` + +Then simply include it in your scripts: + +```javascript +MurmurHash3 = require('imurmurhash'); +``` + +Quick Example +------------- + +```javascript +// Create the initial hash +var hashState = MurmurHash3('string'); + +// Incrementally add text +hashState.hash('more strings'); +hashState.hash('even more strings'); + +// All calls can be chained if desired +hashState.hash('and').hash('some').hash('more'); + +// Get a result +hashState.result(); +// returns 0xe4ccfe6b +``` + +Functions +--------- + +### MurmurHash3 ([string], [seed]) +Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: + +```javascript +// Use the cached object, calling the function again will return the same +// object (but reset, so the current state would be lost) +hashState = MurmurHash3(); +... + +// Create a new object that can be safely used however you wish. Calling the +// function again will simply return a new state object, and no state loss +// will occur, at the cost of creating more objects. +hashState = new MurmurHash3(); +``` + +Both methods can be mixed however you like if you have different use cases. + +--- + +### MurmurHash3.prototype.hash (string) +Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. + +--- + +### MurmurHash3.prototype.result () +Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. + +```javascript +// Do the whole string at once +MurmurHash3('this is a test string').result(); +// 0x70529328 + +// Do part of the string, get a result, then the other part +var m = MurmurHash3('this is a'); +m.result(); +// 0xbfc4f834 +m.hash(' test string').result(); +// 0x70529328 (same as above) +``` + +--- + +### MurmurHash3.prototype.reset ([seed]) +Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. + +--- + +License (MIT) +------------- +Copyright (c) 2013 Gary Court, Jens Taylor + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/imurmurhash/imurmurhash.js b/node_modules/imurmurhash/imurmurhash.js new file mode 100644 index 0000000..e63146a --- /dev/null +++ b/node_modules/imurmurhash/imurmurhash.js @@ -0,0 +1,138 @@ +/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ +(function(){ + var cache; + + // Call this function without `new` to use the cached object (good for + // single-threaded environments), or with `new` to create a new object. + // + // @param {string} key A UTF-16 or ASCII string + // @param {number} seed An optional positive integer + // @return {object} A MurmurHash3 object for incremental hashing + function MurmurHash3(key, seed) { + var m = this instanceof MurmurHash3 ? this : cache; + m.reset(seed) + if (typeof key === 'string' && key.length > 0) { + m.hash(key); + } + + if (m !== this) { + return m; + } + }; + + // Incrementally add a string to this hash + // + // @param {string} key A UTF-16 or ASCII string + // @return {object} this + MurmurHash3.prototype.hash = function(key) { + var h1, k1, i, top, len; + + len = key.length; + this.len += len; + + k1 = this.k1; + i = 0; + switch (this.rem) { + case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; + case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; + case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; + case 3: + k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; + k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; + } + + this.rem = (len + this.rem) & 3; // & 3 is same as % 4 + len -= this.rem; + if (len > 0) { + h1 = this.h1; + while (1) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; + + if (i >= len) { + break; + } + + k1 = ((key.charCodeAt(i++) & 0xffff)) ^ + ((key.charCodeAt(i++) & 0xffff) << 8) ^ + ((key.charCodeAt(i++) & 0xffff) << 16); + top = key.charCodeAt(i++); + k1 ^= ((top & 0xff) << 24) ^ + ((top & 0xff00) >> 8); + } + + k1 = 0; + switch (this.rem) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xffff); + } + + this.h1 = h1; + } + + this.k1 = k1; + return this; + }; + + // Get the result of this hash + // + // @return {number} The 32-bit hash + MurmurHash3.prototype.result = function() { + var k1, h1; + + k1 = this.k1; + h1 = this.h1; + + if (k1 > 0) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= this.len; + + h1 ^= h1 >>> 16; + h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + }; + + // Reset the hash object for reuse + // + // @param {number} seed An optional positive integer + MurmurHash3.prototype.reset = function(seed) { + this.h1 = typeof seed === 'number' ? seed : 0; + this.rem = this.k1 = this.len = 0; + return this; + }; + + // A cached object to use. This can be safely used if you're in a single- + // threaded environment, otherwise you need to create new hashes to use. + cache = new MurmurHash3(); + + if (typeof(module) != 'undefined') { + module.exports = MurmurHash3; + } else { + this.MurmurHash3 = MurmurHash3; + } +}()); diff --git a/node_modules/imurmurhash/imurmurhash.min.js b/node_modules/imurmurhash/imurmurhash.min.js new file mode 100644 index 0000000..dc0ee88 --- /dev/null +++ b/node_modules/imurmurhash/imurmurhash.min.js @@ -0,0 +1,12 @@ +/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ +!function(){function t(h,r){var s=this instanceof t?this:e;return s.reset(r),"string"==typeof h&&h.length>0&&s.hash(h),s!==this?s:void 0}var e;t.prototype.hash=function(t){var e,h,r,s,i;switch(i=t.length,this.len+=i,h=this.k1,r=0,this.rem){case 0:h^=i>r?65535&t.charCodeAt(r++):0;case 1:h^=i>r?(65535&t.charCodeAt(r++))<<8:0;case 2:h^=i>r?(65535&t.charCodeAt(r++))<<16:0;case 3:h^=i>r?(255&t.charCodeAt(r))<<24:0,h^=i>r?(65280&t.charCodeAt(r++))>>8:0}if(this.rem=3&i+this.rem,i-=this.rem,i>0){for(e=this.h1;;){if(h=4294967295&11601*h+3432906752*(65535&h),h=h<<15|h>>>17,h=4294967295&13715*h+461832192*(65535&h),e^=h,e=e<<13|e>>>19,e=4294967295&5*e+3864292196,r>=i)break;h=65535&t.charCodeAt(r++)^(65535&t.charCodeAt(r++))<<8^(65535&t.charCodeAt(r++))<<16,s=t.charCodeAt(r++),h^=(255&s)<<24^(65280&s)>>8}switch(h=0,this.rem){case 3:h^=(65535&t.charCodeAt(r+2))<<16;case 2:h^=(65535&t.charCodeAt(r+1))<<8;case 1:h^=65535&t.charCodeAt(r)}this.h1=e}return this.k1=h,this},t.prototype.result=function(){var t,e;return t=this.k1,e=this.h1,t>0&&(t=4294967295&11601*t+3432906752*(65535&t),t=t<<15|t>>>17,t=4294967295&13715*t+461832192*(65535&t),e^=t),e^=this.len,e^=e>>>16,e=4294967295&51819*e+2246770688*(65535&e),e^=e>>>13,e=4294967295&44597*e+3266445312*(65535&e),e^=e>>>16,e>>>0},t.prototype.reset=function(t){return this.h1="number"==typeof t?t:0,this.rem=this.k1=this.len=0,this},e=new t,"undefined"!=typeof module?module.exports=t:this.MurmurHash3=t}(); \ No newline at end of file diff --git a/node_modules/imurmurhash/package.json b/node_modules/imurmurhash/package.json new file mode 100644 index 0000000..8a93edb --- /dev/null +++ b/node_modules/imurmurhash/package.json @@ -0,0 +1,40 @@ +{ + "name": "imurmurhash", + "version": "0.1.4", + "description": "An incremental implementation of MurmurHash3", + "homepage": "https://github.com/jensyt/imurmurhash-js", + "main": "imurmurhash.js", + "files": [ + "imurmurhash.js", + "imurmurhash.min.js", + "package.json", + "README.md" + ], + "repository": { + "type": "git", + "url": "https://github.com/jensyt/imurmurhash-js" + }, + "bugs": { + "url": "https://github.com/jensyt/imurmurhash-js/issues" + }, + "keywords": [ + "murmur", + "murmurhash", + "murmurhash3", + "hash", + "incremental" + ], + "author": { + "name": "Jens Taylor", + "email": "jensyt@gmail.com", + "url": "https://github.com/homebrewing" + }, + "license": "MIT", + "dependencies": { + }, + "devDependencies": { + }, + "engines": { + "node": ">=0.8.19" + } +} diff --git a/node_modules/inflight/LICENSE b/node_modules/inflight/LICENSE new file mode 100644 index 0000000..05eeeb8 --- /dev/null +++ b/node_modules/inflight/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/inflight/README.md b/node_modules/inflight/README.md new file mode 100644 index 0000000..6dc8929 --- /dev/null +++ b/node_modules/inflight/README.md @@ -0,0 +1,37 @@ +# inflight + +Add callbacks to requests in flight to avoid async duplication + +## USAGE + +```javascript +var inflight = require('inflight') + +// some request that does some stuff +function req(key, callback) { + // key is any random string. like a url or filename or whatever. + // + // will return either a falsey value, indicating that the + // request for this key is already in flight, or a new callback + // which when called will call all callbacks passed to inflightk + // with the same key + callback = inflight(key, callback) + + // If we got a falsey value back, then there's already a req going + if (!callback) return + + // this is where you'd fetch the url or whatever + // callback is also once()-ified, so it can safely be assigned + // to multiple events etc. First call wins. + setTimeout(function() { + callback(null, key) + }, 100) +} + +// only assigns a single setTimeout +// when it dings, all cbs get called +req('foo', cb1) +req('foo', cb2) +req('foo', cb3) +req('foo', cb4) +``` diff --git a/node_modules/inflight/inflight.js b/node_modules/inflight/inflight.js new file mode 100644 index 0000000..48202b3 --- /dev/null +++ b/node_modules/inflight/inflight.js @@ -0,0 +1,54 @@ +var wrappy = require('wrappy') +var reqs = Object.create(null) +var once = require('once') + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} diff --git a/node_modules/inflight/package.json b/node_modules/inflight/package.json new file mode 100644 index 0000000..6084d35 --- /dev/null +++ b/node_modules/inflight/package.json @@ -0,0 +1,29 @@ +{ + "name": "inflight", + "version": "1.0.6", + "description": "Add callbacks to requests in flight to avoid async duplication", + "main": "inflight.js", + "files": [ + "inflight.js" + ], + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.1.2" + }, + "scripts": { + "test": "tap test.js --100" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/inflight.git" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "bugs": { + "url": "https://github.com/isaacs/inflight/issues" + }, + "homepage": "https://github.com/isaacs/inflight", + "license": "ISC" +} diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..37b4366 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.4", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "tap" + }, + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/node_modules/internal-slot/.editorconfig b/node_modules/internal-slot/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/internal-slot/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/internal-slot/.eslintignore b/node_modules/internal-slot/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/internal-slot/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/internal-slot/.eslintrc b/node_modules/internal-slot/.eslintrc new file mode 100644 index 0000000..c42d8f2 --- /dev/null +++ b/node_modules/internal-slot/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-params": [2, 3], + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + "no-magic-numbers": 0, + }, +} diff --git a/node_modules/internal-slot/.github/FUNDING.yml b/node_modules/internal-slot/.github/FUNDING.yml new file mode 100644 index 0000000..8dc96e2 --- /dev/null +++ b/node_modules/internal-slot/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/internal-slot +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/internal-slot/.nycrc b/node_modules/internal-slot/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/internal-slot/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/internal-slot/CHANGELOG.md b/node_modules/internal-slot/CHANGELOG.md new file mode 100644 index 0000000..0c5b3e1 --- /dev/null +++ b/node_modules/internal-slot/CHANGELOG.md @@ -0,0 +1,87 @@ +### Changelog + +All notable changes to this project will be documented in this file. Dates are displayed in UTC. + +Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). + +#### [v1.0.5](https://github.com/ljharb/internal-slot/compare/v1.0.4...v1.0.5) + +> 9 February 2023 + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`e427703`](https://github.com/ljharb/internal-slot/commit/e427703bfc669c590a863ec77ecd3789d7b7c458) +- [Deps] update `get-intrinsic` [`aa652f0`](https://github.com/ljharb/internal-slot/commit/aa652f05c5c15b4ed1a118be60f0565e47bd7208) +- [Fix] improve assertion message [`8df86e3`](https://github.com/ljharb/internal-slot/commit/8df86e3ea21786b5eb7654f22202665c8b63accf) + +#### [v1.0.4](https://github.com/ljharb/internal-slot/compare/v1.0.3...v1.0.4) + +> 13 December 2022 + +- [actions] reuse common workflows [`82a1aee`](https://github.com/ljharb/internal-slot/commit/82a1aee603bce8627930597edb3a04b4970ed151) +- [meta] use `npmignore` to autogenerate an npmignore file [`56f7e71`](https://github.com/ljharb/internal-slot/commit/56f7e7182dd934dd6c1b80497a110670d02a91b9) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`e25ff67`](https://github.com/ljharb/internal-slot/commit/e25ff67d568f77c1b66168957d82b080779e1c0a) +- [actions] update rebase action to use reusable workflow [`227e81e`](https://github.com/ljharb/internal-slot/commit/227e81eaef7230a265103ef1ef0618d2920c3f30) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `foreach`, `object-inspect`, `tape` [`fc9f319`](https://github.com/ljharb/internal-slot/commit/fc9f319d136ddf2e79910390d1e7ad279d41cc01) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `object-inspect`, `safe-publish-latest`, `tape` [`0a72a0f`](https://github.com/ljharb/internal-slot/commit/0a72a0f389511b41645f441da19257a266cb37f7) +- [actions] update codecov uploader [`e2b993f`](https://github.com/ljharb/internal-slot/commit/e2b993f143278a30424ebd5526019e59828989d0) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`8f0ab80`](https://github.com/ljharb/internal-slot/commit/8f0ab808afdd458001c35c828962dc714d824754) +- [actions] update checkout action [`8da4b91`](https://github.com/ljharb/internal-slot/commit/8da4b91c3454671da2e53a831ca0928147965a09) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@safe-publish-latest`, `tape` [`7ab37aa`](https://github.com/ljharb/internal-slot/commit/7ab37aabf01ded2605fa583a9866b62172f82e30) +- [readme] add github actions/codecov badges [`71234be`](https://github.com/ljharb/internal-slot/commit/71234bef4ef99e2f17d72ae3a1b7c0522519b7d7) +- [Fix] `assert`: throw on a nonexistent slot even when an object already has other slots [`12580bd`](https://github.com/ljharb/internal-slot/commit/12580bd26fe9f8603566e9e076092b5e1fb7340b) +- [Tests] use `for-each` instead of `foreach` [`7229df0`](https://github.com/ljharb/internal-slot/commit/7229df01666ccb022dde82686d84b97b7bcfc53a) +- [meta] use `prepublishOnly` script for npm 7+ [`8728872`](https://github.com/ljharb/internal-slot/commit/8728872cfbd735d3ae87e885c081a08d5b26edf0) +- [Deps] update `get-intrinsic` [`1b7088f`](https://github.com/ljharb/internal-slot/commit/1b7088fa970c33757816b08357814bdbf6d722b6) +- [Deps] update `get-intrinsic` [`063621e`](https://github.com/ljharb/internal-slot/commit/063621ec99d1b9262d3898c0ecad0e1e98be5f75) + +#### [v1.0.3](https://github.com/ljharb/internal-slot/compare/v1.0.2...v1.0.3) + +> 26 January 2021 + +- [Tests] use shared travis-ci configs [`0ef2263`](https://github.com/ljharb/internal-slot/commit/0ef22634fa2269d9df0d784aca3c5748e8eabd3b) +- [Tests] migrate tests to Github Actions [`6253915`](https://github.com/ljharb/internal-slot/commit/6253915d28721df2eda5630849bc6b57647e3ee2) +- [meta] do not publish github action workflow files [`ef94e55`](https://github.com/ljharb/internal-slot/commit/ef94e555727ed6a649ef64010904fe89a468d459) +- [Tests] run `nyc` on all tests; use `tape` runner [`917d6ca`](https://github.com/ljharb/internal-slot/commit/917d6ca630cdcd6b4da9a2c300c6a3abb6e724fe) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`8dcb6fe`](https://github.com/ljharb/internal-slot/commit/8dcb6fe01d6a45e1af17a9dace95ca47c99b4328) +- [actions] add "Allow Edits" workflow [`7aa3e86`](https://github.com/ljharb/internal-slot/commit/7aa3e86edb0149fd882717481885760aeb28474e) +- [Refactor] use `get-intrinsic` instead of `es-abstract`; update `side-channel` [`11ad17d`](https://github.com/ljharb/internal-slot/commit/11ad17d4255adcbc55fd4eca0bf6733bac59f1bf) +- [readme] remove travis badge [`5b75452`](https://github.com/ljharb/internal-slot/commit/5b754523aa07e8f67d0135df75059a18047292bb) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`d531688`](https://github.com/ljharb/internal-slot/commit/d5316880956b4dd83e6b6c9ab48fdd8171a4a268) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`c76fa91`](https://github.com/ljharb/internal-slot/commit/c76fa91a7e623a738e22332bee4e985aea41122e) +- [Dev Deps] update `eslint`, `tape` [`e733ccd`](https://github.com/ljharb/internal-slot/commit/e733ccd68e81c72ef2e02726e001895053de7887) +- [Dev Deps] update `auto-changelog`; add `aud` [`df20bf5`](https://github.com/ljharb/internal-slot/commit/df20bf5d3943a533c20799d8cc1449997e85d53b) +- [meta] fix autochangelog [`e89e6f1`](https://github.com/ljharb/internal-slot/commit/e89e6f1ff9f10f386e6400b586db78ad9c0f1309) +- [Tests] only audit prod deps [`71317b9`](https://github.com/ljharb/internal-slot/commit/71317b95ec6bbd9877807da0c0316ee9f5f30fab) +- [Deps] update `es-abstract` [`c17ccf4`](https://github.com/ljharb/internal-slot/commit/c17ccf45f4cb0d3b7a1536e9cd3a7ff9a7dafd21) +- [Dev Deps] update `tape` [`d81ae03`](https://github.com/ljharb/internal-slot/commit/d81ae030a0e8f58cee00f752601ce60405a93d78) +- [Deps] update `es-abstract` [`b56303b`](https://github.com/ljharb/internal-slot/commit/b56303b4c3af7a510f9f51860895a46fd2e14752) +- [Deps] update `es-abstract` [`9996d1c`](https://github.com/ljharb/internal-slot/commit/9996d1cf3507750c7a6845a2fb0d0f849ea898a1) + +#### [v1.0.2](https://github.com/ljharb/internal-slot/compare/v1.0.1...v1.0.2) + +> 20 December 2019 + +- [Deps] update `es-abstract`, `side-channel` [`5c9df03`](https://github.com/ljharb/internal-slot/commit/5c9df03a25518f5c482cff4e1447a26fa071df9a) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`7820f98`](https://github.com/ljharb/internal-slot/commit/7820f984e523a64ddf3068c4e5631abf61eb1ea4) + +#### [v1.0.1](https://github.com/ljharb/internal-slot/compare/v1.0.0...v1.0.1) + +> 1 December 2019 + +- [Refactor] use `side-channel` package [`d38639f`](https://github.com/ljharb/internal-slot/commit/d38639f0a3cdb5090711179d0e78df857ecbd5d3) +- [actions] add automatic rebasing / merge commit blocking [`74267e6`](https://github.com/ljharb/internal-slot/commit/74267e6e591e18ba39186cb99139d3fd7a757c9f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `object-inspect`, `safe-publish-latest` [`b042eef`](https://github.com/ljharb/internal-slot/commit/b042eefc067b830bbd370833f7f21754e802b0b2) +- [Deps] update `es-abstract` [`98cf4e8`](https://github.com/ljharb/internal-slot/commit/98cf4e86c1bfe99eda7b11a8ea70394368f33e4f) + +#### v1.0.0 + +> 20 October 2019 + +- Tests [`b50fa41`](https://github.com/ljharb/internal-slot/commit/b50fa41b6f47aba39ac4cb733658580974a0b00a) +- implementation [`c5a59f3`](https://github.com/ljharb/internal-slot/commit/c5a59f3753677f81aa12a0226d3b1187846d06dd) +- Initial commit [`15ebe4d`](https://github.com/ljharb/internal-slot/commit/15ebe4dc6d46885f67969d64c9c3e705780963f8) +- readme [`382a3f5`](https://github.com/ljharb/internal-slot/commit/382a3f53d8975e6488373a0fc2abcdc7c4c44247) +- npm init [`d5e7c97`](https://github.com/ljharb/internal-slot/commit/d5e7c977ef694e89c245fd11165f63c06a7a5040) +- [meta] add FUNDING.yml [`685b608`](https://github.com/ljharb/internal-slot/commit/685b6087613f6735f4411a558500d92f8a3ec3f2) +- [meta] add `auto-changelog`, `safe-publish-latest` [`f8fdf1c`](https://github.com/ljharb/internal-slot/commit/f8fdf1c3f0c592f71746da6d7f8bea18f8946dda) +- [Tests] add `npm run lint` [`baaaa09`](https://github.com/ljharb/internal-slot/commit/baaaa09ab6e5bc5fcc0e7c76e10c55aa18f4ca7e) +- Only apps should have lockfiles [`dfa7efa`](https://github.com/ljharb/internal-slot/commit/dfa7efa3d5cd23261cb75c2adab6ee3c06790fee) diff --git a/node_modules/internal-slot/LICENSE b/node_modules/internal-slot/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/node_modules/internal-slot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/internal-slot/README.md b/node_modules/internal-slot/README.md new file mode 100644 index 0000000..73d9852 --- /dev/null +++ b/node_modules/internal-slot/README.md @@ -0,0 +1,58 @@ +# internal-slot [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Truly private storage, akin to the JS spec’s concept of internal slots. + +Uses a WeakMap when available; a Map when not; and a regular object in even older engines. Performance and garbage collection behavior will reflect the environment’s capabilities accordingly. + +## Example + +```js +var SLOT = require('internal-slot'); +var assert = require('assert'); + +var o = {}; + +assert.throws(function () { SLOT.assert(o, 'foo'); }); + +assert.equal(SLOT.has(o, 'foo'), false); +assert.equal(SLOT.get(o, 'foo'), undefined); + +SLOT.set(o, 'foo', 42); + +assert.equal(SLOT.has(o, 'foo'), true); +assert.equal(SLOT.get(o, 'foo'), 42); + +assert.doesNotThrow(function () { SLOT.assert(o, 'foo'); }); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/internal-slot +[npm-version-svg]: https://versionbadg.es/ljharb/internal-slot.svg +[deps-svg]: https://david-dm.org/ljharb/internal-slot.svg +[deps-url]: https://david-dm.org/ljharb/internal-slot +[dev-deps-svg]: https://david-dm.org/ljharb/internal-slot/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/internal-slot#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/internal-slot.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/internal-slot.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/internal-slot.svg +[downloads-url]: https://npm-stat.com/charts.html?package=internal-slot +[codecov-image]: https://codecov.io/gh/ljharb/internal-slot/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/internal-slot/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/internal-slot +[actions-url]: https://github.com/ljharb/internal-slot/actions diff --git a/node_modules/internal-slot/index.js b/node_modules/internal-slot/index.js new file mode 100644 index 0000000..ab3496d --- /dev/null +++ b/node_modules/internal-slot/index.js @@ -0,0 +1,62 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var has = require('has'); +var channel = require('side-channel')(); + +var $TypeError = GetIntrinsic('%TypeError%'); + +var SLOT = { + assert: function (O, slot) { + if (!O || (typeof O !== 'object' && typeof O !== 'function')) { + throw new $TypeError('`O` is not an object'); + } + if (typeof slot !== 'string') { + throw new $TypeError('`slot` must be a string'); + } + channel.assert(O); + if (!SLOT.has(O, slot)) { + throw new $TypeError('`' + slot + '` is not present on `O`'); + } + }, + get: function (O, slot) { + if (!O || (typeof O !== 'object' && typeof O !== 'function')) { + throw new $TypeError('`O` is not an object'); + } + if (typeof slot !== 'string') { + throw new $TypeError('`slot` must be a string'); + } + var slots = channel.get(O); + return slots && slots['$' + slot]; + }, + has: function (O, slot) { + if (!O || (typeof O !== 'object' && typeof O !== 'function')) { + throw new $TypeError('`O` is not an object'); + } + if (typeof slot !== 'string') { + throw new $TypeError('`slot` must be a string'); + } + var slots = channel.get(O); + return !!slots && has(slots, '$' + slot); + }, + set: function (O, slot, V) { + if (!O || (typeof O !== 'object' && typeof O !== 'function')) { + throw new $TypeError('`O` is not an object'); + } + if (typeof slot !== 'string') { + throw new $TypeError('`slot` must be a string'); + } + var slots = channel.get(O); + if (!slots) { + slots = {}; + channel.set(O, slots); + } + slots['$' + slot] = V; + } +}; + +if (Object.freeze) { + Object.freeze(SLOT); +} + +module.exports = SLOT; diff --git a/node_modules/internal-slot/package.json b/node_modules/internal-slot/package.json new file mode 100644 index 0000000..9351a55 --- /dev/null +++ b/node_modules/internal-slot/package.json @@ -0,0 +1,71 @@ +{ + "name": "internal-slot", + "version": "1.0.5", + "description": "ES spec-like internal slots", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "pretest": "npm run lint", + "lint": "eslint .", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/internal-slot.git" + }, + "keywords": [ + "internal", + "slot", + "internal slot", + "ecmascript", + "es", + "spec", + "private", + "data", + "private data", + "weakmap" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/internal-slot/issues" + }, + "homepage": "https://github.com/ljharb/internal-slot#readme", + "engines": { + "node": ">= 0.4" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.1", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.3" + }, + "dependencies": { + "get-intrinsic": "^1.2.0", + "has": "^1.0.3", + "side-channel": "^1.0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/internal-slot/test/index.js b/node_modules/internal-slot/test/index.js new file mode 100644 index 0000000..d1db994 --- /dev/null +++ b/node_modules/internal-slot/test/index.js @@ -0,0 +1,121 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var forEach = require('for-each'); + +var SLOT = require('../'); + +test('assert', function (t) { + forEach([null, undefined, true, false, 'foo', '', 42, 0], function (primitive) { + t['throws']( + function () { SLOT.assert(primitive, ''); }, + TypeError, + inspect(primitive) + ' is not an Object' + ); + }); + + forEach([null, undefined, true, false, 42, 0, {}, [], function () {}, /a/g], function (nonString) { + t['throws']( + function () { SLOT.assert({}, nonString); }, + TypeError, + inspect(nonString) + ' is not a String' + ); + }); + + t['throws']( + function () { SLOT.assert({}, 'whatever'); }, + TypeError, + 'nonexistent slot throws' + ); + + var o = {}; + SLOT.set(o, 'x'); + t.doesNotThrow(function () { SLOT.assert(o, 'x'); }, 'existent slot noops'); + t['throws'](function () { SLOT.assert(o, 'y'); }, 'thing with a slot throws on a nonexistent slot'); + + t.end(); +}); + +test('has', function (t) { + forEach([null, undefined, true, false, 'foo', '', 42, 0], function (primitive) { + t['throws']( + function () { SLOT.has(primitive, ''); }, + TypeError, + inspect(primitive) + ' is not an Object' + ); + }); + + forEach([null, undefined, true, false, 42, 0, {}, [], function () {}, /a/g], function (nonString) { + t['throws']( + function () { SLOT.has({}, nonString); }, + TypeError, + inspect(nonString) + ' is not a String' + ); + }); + + var o = {}; + + t.equal(SLOT.has(o, 'nonexistent'), false, 'nonexistent slot yields false'); + + SLOT.set(o, 'foo'); + t.equal(SLOT.has(o, 'foo'), true, 'existent slot yields true'); + + t.end(); +}); + +test('get', function (t) { + forEach([null, undefined, true, false, 'foo', '', 42, 0], function (primitive) { + t['throws']( + function () { SLOT.get(primitive, ''); }, + TypeError, + inspect(primitive) + ' is not an Object' + ); + }); + + forEach([null, undefined, true, false, 42, 0, {}, [], function () {}, /a/g], function (nonString) { + t['throws']( + function () { SLOT.get({}, nonString); }, + TypeError, + inspect(nonString) + ' is not a String' + ); + }); + + var o = {}; + t.equal(SLOT.get(o, 'nonexistent'), undefined, 'nonexistent slot is undefined'); + + var v = {}; + SLOT.set(o, 'f', v); + t.equal(SLOT.get(o, 'f'), v, '"get" retrieves value set by "set"'); + + t.end(); +}); + +test('set', function (t) { + forEach([null, undefined, true, false, 'foo', '', 42, 0], function (primitive) { + t['throws']( + function () { SLOT.set(primitive, ''); }, + TypeError, + inspect(primitive) + ' is not an Object' + ); + }); + + forEach([null, undefined, true, false, 42, 0, {}, [], function () {}, /a/g], function (nonString) { + t['throws']( + function () { SLOT.set({}, nonString); }, + TypeError, + inspect(nonString) + ' is not a String' + ); + }); + + var o = function () {}; + t.equal(SLOT.get(o, 'f'), undefined, 'slot not set'); + + SLOT.set(o, 'f', 42); + t.equal(SLOT.get(o, 'f'), 42, 'slot was set'); + + SLOT.set(o, 'f', Infinity); + t.equal(SLOT.get(o, 'f'), Infinity, 'slot was set again'); + + t.end(); +}); diff --git a/node_modules/is-array-buffer/.eslintrc b/node_modules/is-array-buffer/.eslintrc new file mode 100644 index 0000000..46f3b12 --- /dev/null +++ b/node_modules/is-array-buffer/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/is-array-buffer/.github/FUNDING.yml b/node_modules/is-array-buffer/.github/FUNDING.yml new file mode 100644 index 0000000..61d7d6c --- /dev/null +++ b/node_modules/is-array-buffer/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-array-buffer +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-array-buffer/.nycrc b/node_modules/is-array-buffer/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-array-buffer/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-array-buffer/CHANGELOG.md b/node_modules/is-array-buffer/CHANGELOG.md new file mode 100644 index 0000000..0c84af7 --- /dev/null +++ b/node_modules/is-array-buffer/CHANGELOG.md @@ -0,0 +1,58 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v3.0.2](https://github.com/fengyuanchen/is-array-buffer/compare/v3.0.1...v3.0.2) - 2023-03-01 + +### Commits + +- [Fix] `node` 0.8: an object arg to a TA only throws a RangeError when it is an ArrayBuffer of an incompatible byte length [`d5108f6`](https://github.com/fengyuanchen/is-array-buffer/commit/d5108f6d06245e616b6c563995f214a38732243c) +- [Dev Deps] update `object-inspect`, `tape` [`400f456`](https://github.com/fengyuanchen/is-array-buffer/commit/400f4563ccbe27c7fbb485665352c76210bba9cb) +- [Deps] update `get-intrinsic` [`133732e`](https://github.com/fengyuanchen/is-array-buffer/commit/133732ec88f8dded1c705b758badc2240077a6d8) + +## [v3.0.1](https://github.com/fengyuanchen/is-array-buffer/compare/v3.0.0...v3.0.1) - 2023-01-05 + +### Commits + +- [Fix] in node 0.8, TAs do not coerce Uint8Arrays to an ArrayBuffer properly [`e488763`](https://github.com/fengyuanchen/is-array-buffer/commit/e48876346f446825dad619e55dcc830ed93f2853) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`8eebfa2`](https://github.com/fengyuanchen/is-array-buffer/commit/8eebfa21881f3a9fa5094f8c486f00e496658ea9) + +## [v3.0.0](https://github.com/fengyuanchen/is-array-buffer/compare/v2.0.0...v3.0.0) - 2023-01-04 + +### Commits + +- [Breaking] replace package implementation [`b65f929`](https://github.com/fengyuanchen/is-array-buffer/commit/b65f929d856d2a42f043be0f5a0fc2e067370ed1) +- Initial implementation, tests, readme [`06afa73`](https://github.com/fengyuanchen/is-array-buffer/commit/06afa73e775960802ea9257cc6b4cdf768c72d3f) +- Initial commit [`051813f`](https://github.com/fengyuanchen/is-array-buffer/commit/051813f15e3cbf515e2447306761dd9c42819150) +- npm init [`946d3de`](https://github.com/fengyuanchen/is-array-buffer/commit/946d3de82b15471fb2c00a4a2a5a52eb0515eb04) +- [meta] use `npmignore` to autogenerate an npmignore file [`ca4c446`](https://github.com/fengyuanchen/is-array-buffer/commit/ca4c446f37daf5ab8cc590f2194574c2706561ed) +- Only apps should have lockfiles [`be7d8eb`](https://github.com/fengyuanchen/is-array-buffer/commit/be7d8eb09dc5033c04df85d7ba9a8714f4e54357) +- docs: fix badge link [`9ea7fb6`](https://github.com/fengyuanchen/is-array-buffer/commit/9ea7fb638e79f8938161b3b7370cb965d8e93a8b) + + + +## 2.0.0 (Feb 12, 2021) + +- Refactor in TypeScript. +- Drop the `dist` directory. +- Drop the UMD bundled file. +- Add a declaration file for TypeScript. + +## 1.0.1 (Apr 1, 2018) + +- Improve code style. + +## 1.0.0 (Jul 25, 2017) + +- Supports UMD, CommonJS and ES Module. + +## 0.1.0 (Nov 28, 2015) + +- Check if ArrayBuffer is defined first. + +## 0.0.1 (Nov 11, 2015) + +- Initial release. diff --git a/node_modules/is-array-buffer/LICENSE b/node_modules/is-array-buffer/LICENSE new file mode 100644 index 0000000..a9b309c --- /dev/null +++ b/node_modules/is-array-buffer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2015 Chen Gengyuan, Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/is-array-buffer/README.md b/node_modules/is-array-buffer/README.md new file mode 100644 index 0000000..7b0292f --- /dev/null +++ b/node_modules/is-array-buffer/README.md @@ -0,0 +1,56 @@ +# is-array-buffer [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Is this value a JS ArrayBuffer? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag. + +## Example + +```js +var assert = require('assert'); +var isArrayBuffer = require('is-array-buffer'); + +assert(!isArrayBuffer(function () {})); +assert(!isArrayBuffer(null)); +assert(!isArrayBuffer(function* () { yield 42; return Infinity; }); +assert(!isArrayBuffer(Symbol('foo'))); +assert(!isArrayBuffer(1n)); +assert(!isArrayBuffer(Object(1n))); + +assert(!isArrayBuffer(new Set())); +assert(!isArrayBuffer(new WeakSet())); +assert(!isArrayBuffer(new Map())); +assert(!isArrayBuffer(new WeakMap())); +assert(!isArrayBuffer(new WeakRef({}))); +assert(!isArrayBuffer(new FinalizationRegistry(() => {}))); +assert(!isArrayBuffer(new SharedArrayBuffer())); + +assert(isArrayBuffer(new ArrayBuffer())); + +class MyArrayBuffer extends ArrayBuffer {} +assert(isArrayBuffer(new MyArrayBuffer())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/is-array-buffer +[npm-version-svg]: https://versionbadg.es/inspect-js/is-array-buffer.svg +[deps-svg]: https://david-dm.org/inspect-js/is-array-buffer.svg +[deps-url]: https://david-dm.org/inspect-js/is-array-buffer +[dev-deps-svg]: https://david-dm.org/inspect-js/is-array-buffer/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/is-array-buffer#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/is-array-buffer.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-array-buffer.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-array-buffer.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-array-buffer +[codecov-image]: https://codecov.io/gh/inspect-js/is-array-buffer/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-array-buffer/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-array-buffer +[actions-url]: https://github.com/inspect-js/is-array-buffer/actions diff --git a/node_modules/is-array-buffer/index.js b/node_modules/is-array-buffer/index.js new file mode 100644 index 0000000..7674285 --- /dev/null +++ b/node_modules/is-array-buffer/index.js @@ -0,0 +1,43 @@ +'use strict'; + +var callBind = require('call-bind'); +var callBound = require('call-bind/callBound'); +var GetIntrinsic = require('get-intrinsic'); +var isTypedArray = require('is-typed-array'); + +var $ArrayBuffer = GetIntrinsic('ArrayBuffer', true); +var $Float32Array = GetIntrinsic('Float32Array', true); +var $byteLength = callBound('ArrayBuffer.prototype.byteLength', true); + +// in node 0.10, ArrayBuffers have no prototype methods, but have an own slot-checking `slice` method +var abSlice = $ArrayBuffer && !$byteLength && new $ArrayBuffer().slice; +var $abSlice = abSlice && callBind(abSlice); + +module.exports = $byteLength || $abSlice + ? function isArrayBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + try { + if ($byteLength) { + $byteLength(obj); + } else { + $abSlice(obj, 0); + } + return true; + } catch (e) { + return false; + } + } + : $Float32Array + // in node 0.8, ArrayBuffers have no prototype or own methods + ? function IsArrayBuffer(obj) { + try { + return (new $Float32Array(obj)).buffer === obj && !isTypedArray(obj); + } catch (e) { + return typeof obj === 'object' && e.name === 'RangeError'; + } + } + : function isArrayBuffer(obj) { // eslint-disable-line no-unused-vars + return false; + }; diff --git a/node_modules/is-array-buffer/package.json b/node_modules/is-array-buffer/package.json new file mode 100644 index 0000000..6b1f125 --- /dev/null +++ b/node_modules/is-array-buffer/package.json @@ -0,0 +1,78 @@ +{ + "name": "is-array-buffer", + "version": "3.0.2", + "description": "Is this value a JS ArrayBuffer?", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only --", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/is-array-buffer.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "is", + "arraybuffer", + "array", + "buffer" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/is-array-buffer/issues" + }, + "homepage": "https://github.com/inspect-js/is-array-buffer#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.1", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "available-typed-arrays": "^1.0.5", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.3" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true, + "startingVersion": "2.0.1" + }, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.0", + "is-typed-array": "^1.1.10" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/is-array-buffer/test/index.js b/node_modules/is-array-buffer/test/index.js new file mode 100644 index 0000000..7ddf9d7 --- /dev/null +++ b/node_modules/is-array-buffer/test/index.js @@ -0,0 +1,43 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var forEach = require('for-each'); +var v = require('es-value-fixtures'); +var availableTypedArrays = require('available-typed-arrays')(); + +var isArrayBuffer = require('..'); + +test('isArrayBuffer', function (t) { + t.equal(typeof isArrayBuffer, 'function', 'is a function'); + + var nonABs = v.primitives.concat( + v.objects, + typeof SharedArrayBuffer === 'function' ? new SharedArrayBuffer() : [] + ); + forEach(nonABs, function (nonAB) { + t.equal(isArrayBuffer(nonAB), false, inspect(nonAB) + ' is not an ArrayBuffer'); + }); + + t.test('actual ArrayBuffer instances', { skip: typeof ArrayBuffer === 'undefined' }, function (st) { + var ab = new ArrayBuffer(); + st.equal(isArrayBuffer(ab), true, inspect(ab) + ' is an ArrayBuffer'); + + var ab42 = new ArrayBuffer(42); + st.equal(isArrayBuffer(ab42), true, inspect(ab42) + ' is an ArrayBuffer'); + + st.end(); + }); + + t.test('Typed Arrays', { skip: availableTypedArrays.length === 0 }, function (st) { + forEach(availableTypedArrays, function (TypedArray) { + var ta = new global[TypedArray](0); + st.equal(isArrayBuffer(ta.buffer), true, inspect(ta.buffer) + ', the TA\'s buffer, is an ArrayBuffer'); + st.equal(isArrayBuffer(ta), false, inspect(ta) + ' is not an ArrayBuffer'); + }); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/is-arrayish/.editorconfig b/node_modules/is-arrayish/.editorconfig new file mode 100644 index 0000000..4c017f8 --- /dev/null +++ b/node_modules/is-arrayish/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +indent_style = tab +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.coffee] +indent_style = space + +[{package.json,*.yml}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/node_modules/is-arrayish/.istanbul.yml b/node_modules/is-arrayish/.istanbul.yml new file mode 100644 index 0000000..19fbec3 --- /dev/null +++ b/node_modules/is-arrayish/.istanbul.yml @@ -0,0 +1,4 @@ +instrumentation: + excludes: + - test.js + - test/**/* diff --git a/node_modules/is-arrayish/.npmignore b/node_modules/is-arrayish/.npmignore new file mode 100644 index 0000000..8d5eacb --- /dev/null +++ b/node_modules/is-arrayish/.npmignore @@ -0,0 +1,5 @@ +/coverage/ +/test.js +/test/ +*.sw[a-p] +/node_modules/ diff --git a/node_modules/is-arrayish/.travis.yml b/node_modules/is-arrayish/.travis.yml new file mode 100644 index 0000000..5a04243 --- /dev/null +++ b/node_modules/is-arrayish/.travis.yml @@ -0,0 +1,17 @@ +language: node_js + +script: + - node_modules/.bin/istanbul cover node_modules/.bin/_mocha -- --compilers coffee:coffee-script/register + - cat coverage/lcov.info | node_modules/.bin/coveralls +node_js: + - "0.10" + - "0.11" + - "0.12" + - "iojs" +os: + - linux + - osx + +notifications: + slack: + secure: oOt8QGzdrPDsTMcyahtIq5Q+0U1iwfgJgFCxBLsomQ0bpIMn+y5m4viJydA2UinHPGc944HS3LMZS9iKQyv+DjTgbhUyNXqeVjtxCwRe37f5rKQlXVvdfmjHk2kln4H8DcK3r5Qd/+2hd9BeMsp2GImTrkRSud1CZQlhhe5IgZOboSoWpGVMMy1iazWT06tAtiB2LRVhmsdUaFZDWAhGZ+UAvCPf+mnBOAylIj+U0GDrofhfTi25RK0gddG2f/p2M1HCu49O6wECGWkt2hVei233DkNJyLLLJVcvmhf+aXkV5TjMyaoxh/HdcV4DrA7KvYuWmWWKsINa9hlwAsdd/FYmJ6PjRkKWas2JoQ1C+qOzDxyQvn3CaUZFKD99pdsq0rBBZujqXQKZZ/hWb/CE74BI6fKmqQkiEPaD/7uADj04FEg6HVBZaMCyauOaK5b3VC97twbALZ1qVxYV6mU+zSEvnUbpnjjvRO0fSl9ZHA+rzkW73kX3GmHY0wAozEZbSy7QLuZlQ2QtHmBLr+APaGMdL1sFF9qFfzqKy0WDbSE0WS6hpAEJpTsjYmeBrnI8UmK3m++iEgyQPvZoH9LhUT+ek7XIfHZMe04BmC6wuO24/RfpmR6bQK9VMarFCYlBiWxg/z30vkP0KTpUi3o/cqFm7/Noxc0i2LVqM3E0Sy4= diff --git a/node_modules/is-arrayish/LICENSE b/node_modules/is-arrayish/LICENSE new file mode 100644 index 0000000..0a5f461 --- /dev/null +++ b/node_modules/is-arrayish/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 JD Ballard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-arrayish/README.md b/node_modules/is-arrayish/README.md new file mode 100644 index 0000000..7d36072 --- /dev/null +++ b/node_modules/is-arrayish/README.md @@ -0,0 +1,16 @@ +# node-is-arrayish [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-is-arrayish.svg?style=flat-square)](https://travis-ci.org/Qix-/node-is-arrayish) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-is-arrayish.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-is-arrayish) +> Determines if an object can be used like an Array + +## Example +```javascript +var isArrayish = require('is-arrayish'); + +isArrayish([]); // true +isArrayish({__proto__: []}); // true +isArrayish({}); // false +isArrayish({length:10}); // false +``` + +## License +Licensed under the [MIT License](http://opensource.org/licenses/MIT). +You can find a copy of it in [LICENSE](LICENSE). diff --git a/node_modules/is-arrayish/index.js b/node_modules/is-arrayish/index.js new file mode 100644 index 0000000..5b97186 --- /dev/null +++ b/node_modules/is-arrayish/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function isArrayish(obj) { + if (!obj) { + return false; + } + + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); +}; diff --git a/node_modules/is-arrayish/package.json b/node_modules/is-arrayish/package.json new file mode 100644 index 0000000..8b2d1c3 --- /dev/null +++ b/node_modules/is-arrayish/package.json @@ -0,0 +1,34 @@ +{ + "name": "is-arrayish", + "description": "Determines if an object can be used as an array", + "version": "0.2.1", + "author": "Qix (http://github.com/qix-)", + "keywords": [ + "is", + "array", + "duck", + "type", + "arrayish", + "similar", + "proto", + "prototype", + "type" + ], + "license": "MIT", + "scripts": { + "pretest": "xo", + "test": "mocha --compilers coffee:coffee-script/register" + }, + "repository": { + "type": "git", + "url": "https://github.com/qix-/node-is-arrayish.git" + }, + "devDependencies": { + "coffee-script": "^1.9.3", + "coveralls": "^2.11.2", + "istanbul": "^0.3.17", + "mocha": "^2.2.5", + "should": "^7.0.1", + "xo": "^0.6.1" + } +} diff --git a/node_modules/is-bigint/.eslintignore b/node_modules/is-bigint/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-bigint/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-bigint/.eslintrc b/node_modules/is-bigint/.eslintrc new file mode 100644 index 0000000..1283fcf --- /dev/null +++ b/node_modules/is-bigint/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["BigInt"] }], + "operator-linebreak": [2, "before"], + }, +} diff --git a/node_modules/is-bigint/.github/FUNDING.yml b/node_modules/is-bigint/.github/FUNDING.yml new file mode 100644 index 0000000..59d03ba --- /dev/null +++ b/node_modules/is-bigint/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-bigint +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-bigint/.nycrc b/node_modules/is-bigint/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-bigint/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-bigint/CHANGELOG.md b/node_modules/is-bigint/CHANGELOG.md new file mode 100644 index 0000000..c1b0271 --- /dev/null +++ b/node_modules/is-bigint/CHANGELOG.md @@ -0,0 +1,71 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/inspect-js/is-bigint/compare/v1.0.3...v1.0.4) - 2021-08-11 + +### Commits + +- [eslint] remove unnecessary eslintrc file [`7220aa5`](https://github.com/inspect-js/is-bigint/commit/7220aa515c51649b48ba57bb77f92d85e27557d8) +- [readme] add github actions/codecov badges [`053a071`](https://github.com/inspect-js/is-bigint/commit/053a07123511eef5a91fd7889ae2d8323fbcf7d7) +- [Deps] add `has-bigints` as a runtime dependency [`0fc3c9d`](https://github.com/inspect-js/is-bigint/commit/0fc3c9d5165f62500ea9c27943cb302df65432f7) +- [Dev Deps] update `tape` [`145f11d`](https://github.com/inspect-js/is-bigint/commit/145f11d1d285d92b3144f48178fe0fb3b2f828d9) + +## [v1.0.3](https://github.com/inspect-js/is-bigint/compare/v1.0.2...v1.0.3) - 2021-08-06 + +### Commits + +- [Tests] use `has-tostringtag` for easier checking of Symbol.toStringTag [`3b44080`](https://github.com/inspect-js/is-bigint/commit/3b440801b69689d907b33184134f00d7e8a35f9f) +- [Dev Deps] update `auto-changelog`, `eslint`, `object-inspect`, `tape` [`e4d4a6c`](https://github.com/inspect-js/is-bigint/commit/e4d4a6c2ab743b52eda906abd1ed4b0608952533) +- [Fix] use `has-bigints` for more robust BigInt detection [`7bb9d7a`](https://github.com/inspect-js/is-bigint/commit/7bb9d7ab42214c12ce25e9f0cfe2af769388c3bb) + +## [v1.0.2](https://github.com/inspect-js/is-bigint/compare/v1.0.1...v1.0.2) - 2021-05-04 + +### Commits + +- [meta] do not publish github action workflow files [`276d677`](https://github.com/inspect-js/is-bigint/commit/276d677d1eac61e990a2f2b523c7cdef70784865) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`cea7fb6`](https://github.com/inspect-js/is-bigint/commit/cea7fb6e882ad7e2f550de2bd9317a4409bcd735) +- [readme] fix repo URLs; remove travis badge [`c8e7c36`](https://github.com/inspect-js/is-bigint/commit/c8e7c3651f3303fddafa61cf29cfbb79ea2d5d4b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbols`, `object-inspect`, `tape` [`32f3d90`](https://github.com/inspect-js/is-bigint/commit/32f3d909363045fe5d40dde9e4db354344ab4d50) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `tape` [`c2f20f5`](https://github.com/inspect-js/is-bigint/commit/c2f20f577d84e68b4e3224abb51024fbc4b9b2ba) +- [meta] remove unneeded token; update checkout action [`94e46e9`](https://github.com/inspect-js/is-bigint/commit/94e46e92a1a85ec022c8febf8d5d3c2369b46e97) +- [meta] use `prepublishOnly` script for npm 7+ [`3e663ec`](https://github.com/inspect-js/is-bigint/commit/3e663ecb09bfdc5dbaaa37aaef4adf28b5e49035) + +## [v1.0.1](https://github.com/inspect-js/is-bigint/compare/v1.0.0...v1.0.1) - 2020-11-30 + +### Commits + +- [Tests] use shared travis-ci configs [`28f1211`](https://github.com/inspect-js/is-bigint/commit/28f1211132ad2a6495d816140680fa16c12eb6f3) +- [Tests] migrate tests to Github Actions [`0998c64`](https://github.com/inspect-js/is-bigint/commit/0998c6443d603028f8b988bcdd52d23dbf513031) +- [meta] add `auto-changelog` [`2352de6`](https://github.com/inspect-js/is-bigint/commit/2352de6df8385b256d75ce50c360947243a599f6) +- [Tests] run `nyc` on all tests [`9c16a9a`](https://github.com/inspect-js/is-bigint/commit/9c16a9a5ddaf7c2c578542ab8f00dd4e72eff541) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `object-inspect`, `tape` [`4cd0edd`](https://github.com/inspect-js/is-bigint/commit/4cd0edd1917f789501291315c9eac5f895fd719e) +- [actions] add automatic rebasing / merge commit blocking [`f0f4b91`](https://github.com/inspect-js/is-bigint/commit/f0f4b91dba029dbca5b3cd27ef91c4fb8e3ec51a) +- [actions] add "Allow Edits" workflow [`7f4f46e`](https://github.com/inspect-js/is-bigint/commit/7f4f46ec07679c00e22287ec55b39ff1e4f809cf) +- [meta] create FUNDING.yml [`2d0cb9a`](https://github.com/inspect-js/is-bigint/commit/2d0cb9ae8ddf635f2c472ce49f95f717f2c432bf) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`0ee110e`](https://github.com/inspect-js/is-bigint/commit/0ee110effdcaa96d90f21a0ec6e625941f77c45a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `has-symbols`, `object-inspect`, `tape` [`5bb7f3a`](https://github.com/inspect-js/is-bigint/commit/5bb7f3a8de6ec5ee2aa573c22e41884f3d2d1cc3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`d3d67d0`](https://github.com/inspect-js/is-bigint/commit/d3d67d05f8a3f4cb07085811629f56ef872949c3) +- [Dev Deps] update `auto-changelog`, `tape` [`54e270f`](https://github.com/inspect-js/is-bigint/commit/54e270fa29856dba90f86785fa61bffc79a2825d) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`d82bfe7`](https://github.com/inspect-js/is-bigint/commit/d82bfe75c63aeda40f7e473c57f26cea8790ba3a) +- [Dev Deps] update `auto-changelog`; add `aud` [`9c34bd1`](https://github.com/inspect-js/is-bigint/commit/9c34bd1873f08d77c82d8e54ad90c5a1a035e7ea) +- [Tests] add missing `posttest` script [`0690bd9`](https://github.com/inspect-js/is-bigint/commit/0690bd9868d4d8b43424b4224cdbb8659a1c6423) +- [meta] add `funding` field [`7ca36d0`](https://github.com/inspect-js/is-bigint/commit/7ca36d06ebcf6b01a592ecd6758bd2b39c0fb0db) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`5ffa8da`](https://github.com/inspect-js/is-bigint/commit/5ffa8dad9f634891cf739ee118f1b43142b0f01d) +- [Dev Deps] update `eslint` [`8512c2f`](https://github.com/inspect-js/is-bigint/commit/8512c2f29a9267fe8fe19209bcf77df94f127172) +- [Tests] only audit prod deps [`f2147dc`](https://github.com/inspect-js/is-bigint/commit/f2147dc54e72594985e8f6db3932a4f0819dc4db) +- [readme] fix header [`d6eff75`](https://github.com/inspect-js/is-bigint/commit/d6eff75d00471f465768deb92867e878c27733b3) + +## v1.0.0 - 2018-09-20 + +### Commits + +- [Tests] add tests [`847f12a`](https://github.com/inspect-js/is-bigint/commit/847f12af125fcefb75ed3517550feedf7dd73e88) +- Initial commit [`b53f3c6`](https://github.com/inspect-js/is-bigint/commit/b53f3c6754e7fd7a9982ff5b1466c4dc9799dad9) +- readme [`66c15fe`](https://github.com/inspect-js/is-bigint/commit/66c15fe1a0d965b8c78bf3a3bfc289dcfec53ee1) +- Implementation [`c2c0974`](https://github.com/inspect-js/is-bigint/commit/c2c0974397825a2a56e1ea8af0546171309d4805) +- package.json [`98b174c`](https://github.com/inspect-js/is-bigint/commit/98b174c24b070053f0548e58f9b87bc9dbdf922a) +- Only apps should have lockfiles [`a77c74b`](https://github.com/inspect-js/is-bigint/commit/a77c74bd8ca5f058f1e6165ae7b33bb84adef98c) diff --git a/node_modules/is-bigint/LICENSE b/node_modules/is-bigint/LICENSE new file mode 100644 index 0000000..9dd868f --- /dev/null +++ b/node_modules/is-bigint/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/is-bigint/README.md b/node_modules/is-bigint/README.md new file mode 100644 index 0000000..d64549f --- /dev/null +++ b/node_modules/is-bigint/README.md @@ -0,0 +1,44 @@ +# is-bigint [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this an ES BigInt value? + +## Example + +```js +var isBigInt = require('is-bigint'); +assert(!isBigInt(function () {})); +assert(!isBigInt(null)); +assert(!isBigInt(function* () { yield 42; return Infinity; }); +assert(!isBigInt(Symbol('foo'))); + +assert(isBigInt(1n)); +assert(isBigInt(Object(1n))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-bigint +[2]: https://versionbadg.es/inspect-js/is-bigint.svg +[5]: https://david-dm.org/inspect-js/is-bigint.svg +[6]: https://david-dm.org/inspect-js/is-bigint +[7]: https://david-dm.org/inspect-js/is-bigint/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-bigint#info=devDependencies +[11]: https://nodei.co/npm/is-bigint.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-bigint.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-bigint.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-bigint +[codecov-image]: https://codecov.io/gh/inspect-js/is-bigint/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-bigint/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-bigint +[actions-url]: https://github.com/inspect-js/is-bigint/actions diff --git a/node_modules/is-bigint/index.js b/node_modules/is-bigint/index.js new file mode 100644 index 0000000..8da47d7 --- /dev/null +++ b/node_modules/is-bigint/index.js @@ -0,0 +1,38 @@ +'use strict'; + +var hasBigInts = require('has-bigints')(); + +if (hasBigInts) { + var bigIntValueOf = BigInt.prototype.valueOf; + var tryBigInt = function tryBigIntObject(value) { + try { + bigIntValueOf.call(value); + return true; + } catch (e) { + } + return false; + }; + + module.exports = function isBigInt(value) { + if ( + value === null + || typeof value === 'undefined' + || typeof value === 'boolean' + || typeof value === 'string' + || typeof value === 'number' + || typeof value === 'symbol' + || typeof value === 'function' + ) { + return false; + } + if (typeof value === 'bigint') { + return true; + } + + return tryBigInt(value); + }; +} else { + module.exports = function isBigInt(value) { + return false && value; + }; +} diff --git a/node_modules/is-bigint/package.json b/node_modules/is-bigint/package.json new file mode 100644 index 0000000..850dbd8 --- /dev/null +++ b/node_modules/is-bigint/package.json @@ -0,0 +1,58 @@ +{ + "name": "is-bigint", + "version": "1.0.4", + "description": "Is this value an ES BigInt?", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/is-bigint.git" + }, + "keywords": [ + "bigint", + "es", + "integer", + "is" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/is-bigint/issues" + }, + "homepage": "https://github.com/inspect-js/is-bigint#readme", + "dependencies": { + "has-bigints": "^1.0.1" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^7.32.0", + "has-symbols": "^1.0.2", + "nyc": "^10.3.2", + "object-inspect": "^1.11.0", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/is-bigint/test/index.js b/node_modules/is-bigint/test/index.js new file mode 100644 index 0000000..21537d6 --- /dev/null +++ b/node_modules/is-bigint/test/index.js @@ -0,0 +1,81 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var hasBigInts = require('has-bigints')(); +var hasSymbols = require('has-symbols')(); +var hasToStringTag = require('has-tostringtag/shams')(); + +var isBigInt = require('../'); + +var debug = function (v, m) { return inspect(v) + ' ' + m; }; + +var forEach = function (arr, func) { + var i; + for (i = 0; i < arr.length; ++i) { + func(arr[i], i, arr); + } +}; + +test('non-BigInt values', function (t) { + var nonBigInts = [ + true, + false, + Object(true), + Object(false), + null, + undefined, + {}, + [], + /a/g, + 'string', + 42, + new Date(), + function () {}, + NaN + ]; + if (hasSymbols) { + nonBigInts.push(Symbol.iterator, Symbol('foo')); + } + t.plan(nonBigInts.length); + forEach(nonBigInts, function (nonBigInt) { + t.equal(false, isBigInt(nonBigInt), debug(nonBigInt, 'is not a BigInt')); + }); + t.end(); +}); + +test('faked BigInt values', function (t) { + t.test('real BigInt valueOf', { skip: !hasBigInts }, function (st) { + var fakeBigInt = { valueOf: function () { return BigInt(42); } }; + st.equal(false, isBigInt(fakeBigInt), 'object with valueOf returning a BigInt is not a BigInt'); + st.end(); + }); + + t.test('faked @@toStringTag', { skip: !hasBigInts || !hasToStringTag }, function (st) { + var fakeBigInt = { valueOf: function () { return BigInt(42); } }; + fakeBigInt[Symbol.toStringTag] = 'BigInt'; + st.equal(false, isBigInt(fakeBigInt), 'object with fake BigInt @@toStringTag and valueOf returning a BigInt is not a BigInt'); + + var notSoFakeBigInt = { valueOf: function () { return 42; } }; + notSoFakeBigInt[Symbol.toStringTag] = 'BigInt'; + st.equal(false, isBigInt(notSoFakeBigInt), 'object with fake BigInt @@toStringTag and valueOf not returning a BigInt is not a BigInt'); + st.end(); + }); + + var fakeBigIntString = { toString: function () { return '42n'; } }; + t.equal(false, isBigInt(fakeBigIntString), 'object with toString returning 42n is not a BigInt'); + + t.end(); +}); + +test('BigInt support', { skip: !hasBigInts }, function (t) { + forEach([ + Function('return 42n')(), // eslint-disable-line no-new-func + BigInt(42), + Object(BigInt(42)) + ], function (bigInt) { + t.equal(true, isBigInt(bigInt), debug(bigInt, 'is a BigInt')); + }); + + t.end(); +}); diff --git a/node_modules/is-boolean-object/.editorconfig b/node_modules/is-boolean-object/.editorconfig new file mode 100644 index 0000000..8d93cc1 --- /dev/null +++ b/node_modules/is-boolean-object/.editorconfig @@ -0,0 +1,22 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[.github/workflows/*.yml] +indent_style = off +indent_size = off +max_line_length = off + +[{CHANGELOG.md,*.json}] +max_line_length = off diff --git a/node_modules/is-boolean-object/.eslintignore b/node_modules/is-boolean-object/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-boolean-object/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-boolean-object/.eslintrc b/node_modules/is-boolean-object/.eslintrc new file mode 100644 index 0000000..a072916 --- /dev/null +++ b/node_modules/is-boolean-object/.eslintrc @@ -0,0 +1,22 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-nested-callbacks": [2, 3] + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "prefer-regex-literals": 0, + }, + }, + { + "files": "test-corejs.js", + "extends": "@ljharb/eslint-config/tests", + }, + ], +} diff --git a/node_modules/is-boolean-object/.github/FUNDING.yml b/node_modules/is-boolean-object/.github/FUNDING.yml new file mode 100644 index 0000000..fd04996 --- /dev/null +++ b/node_modules/is-boolean-object/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-boolean-object +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-boolean-object/.nycrc b/node_modules/is-boolean-object/.nycrc new file mode 100644 index 0000000..a69aa2d --- /dev/null +++ b/node_modules/is-boolean-object/.nycrc @@ -0,0 +1,10 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test", + "test-corejs.js" + ] +} diff --git a/node_modules/is-boolean-object/CHANGELOG.md b/node_modules/is-boolean-object/CHANGELOG.md new file mode 100644 index 0000000..f789bdb --- /dev/null +++ b/node_modules/is-boolean-object/CHANGELOG.md @@ -0,0 +1,107 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.2](https://github.com/inspect-js/is-boolean-object/compare/v1.1.1...v1.1.2) - 2021-08-05 + +### Commits + +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`6d319ea`](https://github.com/inspect-js/is-boolean-object/commit/6d319eac0ba237f7ba440a1fc4b32d007b1b0cf3) +- [Dev Deps] update `auto-changelog`, `core-js`, `eslint`, `tape` [`4f85bef`](https://github.com/inspect-js/is-boolean-object/commit/4f85bef244f8fdd9ab99db0afe0b8fa00c853709) + +## [v1.1.1](https://github.com/inspect-js/is-boolean-object/compare/v1.1.0...v1.1.1) - 2021-05-07 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`7201c41`](https://github.com/inspect-js/is-boolean-object/commit/7201c41fc1fd9d64b51716b80fc63d95064a4a59) +- [Tests] run tests with core-js as well [`9590e61`](https://github.com/inspect-js/is-boolean-object/commit/9590e6135505e2e3f69c6d8785a539fca1b1e594) +- [meta] do not publish github action workflow files [`341472b`](https://github.com/inspect-js/is-boolean-object/commit/341472bbe9855030c7eda9340ee4284244f0a4ad) +- [readme] update repo URLs; remove travis badge [`9fdbbc6`](https://github.com/inspect-js/is-boolean-object/commit/9fdbbc64b2a70ee93fcfd95fc6c94c7ec2bbedd4) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1cd35c9`](https://github.com/inspect-js/is-boolean-object/commit/1cd35c9b9b0b4af203f20bda0d7fd60798e57f99) +- [readme] add actions and codecov badges [`03769fe`](https://github.com/inspect-js/is-boolean-object/commit/03769feb1466f03b1345882ca0e4f8cacbbce9ce) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`db6598c`](https://github.com/inspect-js/is-boolean-object/commit/db6598c4cabcd0ffd2ba9b4525b53907f8b2ff1f) +- [Fix] do not use `Object.prototype.toString` when `Symbol.toStringTag` is shammed [`e0b8a9f`](https://github.com/inspect-js/is-boolean-object/commit/e0b8a9f0fc1290a0a29c75967d56bc1c17eb8d2d) +- [readme] remove defunct testling badge [`986a621`](https://github.com/inspect-js/is-boolean-object/commit/986a6217da7385f7063e1d4e4bf5be2892d00c20) +- [meta] use `prepublishOnly` script for npm 7+ [`7bb3b29`](https://github.com/inspect-js/is-boolean-object/commit/7bb3b2902008ca07af4185ca98bc41b3222d579f) +- [Deps] update `call-bind` [`3af6a71`](https://github.com/inspect-js/is-boolean-object/commit/3af6a71e1004c79567630ac9944b9f2cc184ac77) +- [meta] do not publish corejs test file [`d911f03`](https://github.com/inspect-js/is-boolean-object/commit/d911f0368b6922645d15b9e28f3ed92e1badcef4) +- [actions] update workflows [`9bb3d90`](https://github.com/inspect-js/is-boolean-object/commit/9bb3d9015f377280324b162a3062d21936707216) + +## [v1.1.0](https://github.com/inspect-js/is-boolean-object/compare/v1.0.1...v1.1.0) - 2020-12-05 + +### Commits + +- [Tests] migrate tests to Github Actions [`6cdb652`](https://github.com/inspect-js/is-boolean-object/commit/6cdb652add3c6e44c2f7fe07c5ca4c0d14ddc2c1) +- [Tests] run `nyc` on all tests [`9a33076`](https://github.com/inspect-js/is-boolean-object/commit/9a33076d14869bf5120a6ca3903bcb9a008cf2e5) +- [Tests] add .editorconfig [`bb401c0`](https://github.com/inspect-js/is-boolean-object/commit/bb401c084416b010d64e0c5a74465b37addab31f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`5cb2405`](https://github.com/inspect-js/is-boolean-object/commit/5cb24052ca84d840e929f05cd1fe6c03b85ec032) +- [Robustness] use `call-bind` to avoid a dependency on `.call` [`76d87ae`](https://github.com/inspect-js/is-boolean-object/commit/76d87ae74235a9995d39bcf5783c04c744c34520) +- [actions] add "Allow Edits" workflow [`337206a`](https://github.com/inspect-js/is-boolean-object/commit/337206af74bd7c340bc938ab6dc0535c08490b3d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`11f0481`](https://github.com/inspect-js/is-boolean-object/commit/11f0481efca28a241a35d384e2a302b1bcdc9a37) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`b9602c8`](https://github.com/inspect-js/is-boolean-object/commit/b9602c8ca11be138722187c1fb0a5b25a57a4edc) +- [Dev Deps] update `auto-changelog`, `tape`; add `aud` [`999e9e2`](https://github.com/inspect-js/is-boolean-object/commit/999e9e224d4eec8b20fc9c3431e9ba42caad79c9) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`bbb6728`](https://github.com/inspect-js/is-boolean-object/commit/bbb6728b9410f9d3e2d266523a477127e5e4c16f) + +## [v1.0.1](https://github.com/inspect-js/is-boolean-object/compare/v1.0.0...v1.0.1) - 2019-12-18 + +### Commits + +- [Tests] use shared travis-ci configs [`a1778b8`](https://github.com/inspect-js/is-boolean-object/commit/a1778b81ab4fe4479176de854e4e233cc441f183) +- Update `eslint`; use my personal shared `eslint` config. [`2c42c50`](https://github.com/inspect-js/is-boolean-object/commit/2c42c50a0654044b6c7e2a4ab18227e8c275464b) +- [Tests] remove `jscs` [`3807025`](https://github.com/inspect-js/is-boolean-object/commit/380702504fabc47fe22f61c4847379023d31a657) +- [Tests] up to `node` `v8.4`, `v7.10`, `v6.11`, `v5.12`, `v4.8`; improve matrix; newer npm breaks in older node; improve scripts. [`a02b986`](https://github.com/inspect-js/is-boolean-object/commit/a02b98682b285de09e2c5a895627771d6a7f552c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is`, `jscs`, `nsp`, `semver`, `tape` [`d9030a9`](https://github.com/inspect-js/is-boolean-object/commit/d9030a99b8e274c76ae5f23f31d9d085a7e25272) +- Update `eslint`, `nsp` [`a1b6388`](https://github.com/inspect-js/is-boolean-object/commit/a1b6388fabd0de51a02c567953826344ef05890c) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9`; use `nvm install-latest-npm` [`17a0fd3`](https://github.com/inspect-js/is-boolean-object/commit/17a0fd391e32635ec3434baca0d062f8abeeb592) +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`0b1818f`](https://github.com/inspect-js/is-boolean-object/commit/0b1818fdcaebc6133e515dfe3b5a8930b38999b5) +- [meta] remove unused Makefile and associated utilities [`33dc0ae`](https://github.com/inspect-js/is-boolean-object/commit/33dc0ae35a03e91f81b1bb3db5ba763dacadbfa2) +- Update `covert`, `jscs`, `eslint`, `semver` [`7e513c1`](https://github.com/inspect-js/is-boolean-object/commit/7e513c12998a651c14f62b3ecfb7215a5cc5ee8f) +- [Tests] up to `node` `v11.4`, `v10.14`, `v8.14`, `v6.15` [`992b849`](https://github.com/inspect-js/is-boolean-object/commit/992b84933760e0fe6ba2cee74ad7fff507f28128) +- [meta] add `auto-changelog` [`63d71b8`](https://github.com/inspect-js/is-boolean-object/commit/63d71b8beb9aeb77cab3d2db2cf643f1b8b1a55c) +- Update `tape`, `eslint`, `semver` [`76aea69`](https://github.com/inspect-js/is-boolean-object/commit/76aea699fb315ac460799182d707c388b4a4e017) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`a6cbec0`](https://github.com/inspect-js/is-boolean-object/commit/a6cbec09940b6f2c7cf366526a94c0c4756508f5) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `replace`, `semver`, `tape`; add `safe-publish-latest` [`7cf6bb0`](https://github.com/inspect-js/is-boolean-object/commit/7cf6bb05ba7bac504df680dd9ca625fba6dccb5a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` [`57d713c`](https://github.com/inspect-js/is-boolean-object/commit/57d713cca2ccbbbf1da1142ee5e8236d12551f76) +- [actions] add automatic rebasing / merge commit blocking [`f7a2bdb`](https://github.com/inspect-js/is-boolean-object/commit/f7a2bdb905e07d75c65593359f81bfeda9fe9826) +- [meta] create FUNDING.yml [`9765e73`](https://github.com/inspect-js/is-boolean-object/commit/9765e738cccdd5ff6c89b21324119a2bf4064fbd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is`, `replace`, `semver`, `tape` [`5c16b56`](https://github.com/inspect-js/is-boolean-object/commit/5c16b56a5a2d36c6a70c1bd396b3a6c931f655db) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`5717aad`](https://github.com/inspect-js/is-boolean-object/commit/5717aadd8b0e8c76ccb194d1845ad8cc120f29c6) +- [Dev Deps] update `is`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`80b924d`](https://github.com/inspect-js/is-boolean-object/commit/80b924dd270188e1e928f4141078bee14d810e9b) +- [Dev Deps] update `jscs` [`2e5479e`](https://github.com/inspect-js/is-boolean-object/commit/2e5479e56b6d33288582cfe8c254ca081e79500c) +- Test up to `io.js` `v2.2` [`93379a4`](https://github.com/inspect-js/is-boolean-object/commit/93379a4b48ba719113006ab08bbe6679c8a27293) +- [Tests] remove `nsp`; use `npm audit`; allow to fail for now [`36ae30a`](https://github.com/inspect-js/is-boolean-object/commit/36ae30acffe4a892ea0882a793b8a90f09d08fdf) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`ef76976`](https://github.com/inspect-js/is-boolean-object/commit/ef76976db22f2867fca2ee377fdbc9da81f0d142) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`a1182bd`](https://github.com/inspect-js/is-boolean-object/commit/a1182bd99e5d31e113107241f0d697e71b27bf7b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`4f79b47`](https://github.com/inspect-js/is-boolean-object/commit/4f79b474f0643fd2c9dbc863949a61cf01255b6f) +- [Tests] up to `node` `v10.3` [`5e96464`](https://github.com/inspect-js/is-boolean-object/commit/5e96464fc08eacc45f5f58fe7800ddbc45e40cea) +- [Dev Deps] update `eslint`, `nsp`, `semver`, `tape` [`e1eb3fa`](https://github.com/inspect-js/is-boolean-object/commit/e1eb3fad8bad65140db3bd2381bb3bea6a9c6242) +- Only apps should have lockfiles. [`c7f301f`](https://github.com/inspect-js/is-boolean-object/commit/c7f301ff368f9e04f7f64a2ce9b6ae1aec803e69) +- [meta] add `funding` field [`fad0366`](https://github.com/inspect-js/is-boolean-object/commit/fad03662becea5db7cef29d816d173ad771be86a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`80d39d9`](https://github.com/inspect-js/is-boolean-object/commit/80d39d90205d3bb564acb80b0625e90c267347fd) +- [Tests] use `eclint` instead of `editorconfig-tools` [`980e91b`](https://github.com/inspect-js/is-boolean-object/commit/980e91b186a728f77366ba16b7bebc813b9cc3b0) +- [Dev Deps] Update `tape`, `eslint` [`9960830`](https://github.com/inspect-js/is-boolean-object/commit/9960830876a3672686c569fde3d43bb7983955f1) +- Test up to `io.js` `v3.0` [`a3c3cd0`](https://github.com/inspect-js/is-boolean-object/commit/a3c3cd087d7fcefbf4f3525c05f4cee3b6e5b0ef) +- [Dev Deps] update `tape` [`217fbd6`](https://github.com/inspect-js/is-boolean-object/commit/217fbd6bb2989f9304ad95cd49697da7fe03b8d5) +- [Tests] only audit prod deps [`89284ee`](https://github.com/inspect-js/is-boolean-object/commit/89284ee17dce1d044df0ca9e006072f25742bbaf) +- [Performance] only use toStringTag code path when the value has that property [`2863bc5`](https://github.com/inspect-js/is-boolean-object/commit/2863bc5b72680f05ace8e66fddcf48966b942d55) +- [Dev Deps] update `replace` [`53e72a5`](https://github.com/inspect-js/is-boolean-object/commit/53e72a5ceca5b3a82e6407829f9227df9df6d329) +- [Enhancement] slight optimization for `null` [`a90a3c4`](https://github.com/inspect-js/is-boolean-object/commit/a90a3c4464d0300e23384d96fb4281b55b7fd723) +- [Dev Deps] update `tape` [`9377bd5`](https://github.com/inspect-js/is-boolean-object/commit/9377bd5110e99d8ec550f24ef3f6ead62a8f1f50) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`3085530`](https://github.com/inspect-js/is-boolean-object/commit/30855304841854f79e406372f524efe4bc7d8c04) +- Test on `io.js` `v2.4` [`8af335c`](https://github.com/inspect-js/is-boolean-object/commit/8af335ca82a0eeba4a0a593775e4caf744834ec4) +- Test on `io.js` `v2.3` [`1eb3424`](https://github.com/inspect-js/is-boolean-object/commit/1eb3424bef528551f5c99a754281a51d92e40ab1) + +## v1.0.0 - 2015-04-28 + +### Commits + +- Dotfiles [`6b9b998`](https://github.com/inspect-js/is-boolean-object/commit/6b9b998bb238a32d4829c9f9bf274e5ca15023ee) +- `make release` [`d5e50b3`](https://github.com/inspect-js/is-boolean-object/commit/d5e50b33a3cd8d8abe7de8ae36e2944c24ce76ba) +- package.json [`117676a`](https://github.com/inspect-js/is-boolean-object/commit/117676a48609e636d4257c1b35c695ff20939211) +- Read me [`ef327a7`](https://github.com/inspect-js/is-boolean-object/commit/ef327a74c7f73e64cfa3c20a9620ef7accf8b762) +- Initial commit [`2346886`](https://github.com/inspect-js/is-boolean-object/commit/2346886252b9637c1af6851a3fc2cbc98bc986aa) +- Tests [`67211f8`](https://github.com/inspect-js/is-boolean-object/commit/67211f8bff1a49e5df219935765b83573c097353) +- Implementation [`2d88bd6`](https://github.com/inspect-js/is-boolean-object/commit/2d88bd6e1ef0f07f5a639775eb89f3b78e12eb65) diff --git a/node_modules/is-boolean-object/LICENSE b/node_modules/is-boolean-object/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/node_modules/is-boolean-object/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/is-boolean-object/README.md b/node_modules/is-boolean-object/README.md new file mode 100644 index 0000000..a77f3e9 --- /dev/null +++ b/node_modules/is-boolean-object/README.md @@ -0,0 +1,57 @@ +# is-boolean-object [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this value a JS Boolean? This module works cross-realm/iframe, and despite ES6 @@toStringTag. + +## Example + +```js +var isBoolean = require('is-boolean-object'); +var assert = require('assert'); + +assert.notOk(isBoolean(undefined)); +assert.notOk(isBoolean(null)); +assert.notOk(isBoolean('foo')); +assert.notOk(isBoolean(function () {})); +assert.notOk(isBoolean([])); +assert.notOk(isBoolean({})); +assert.notOk(isBoolean(/a/g)); +assert.notOk(isBoolean(new RegExp('a', 'g'))); +assert.notOk(isBoolean(new Date())); +assert.notOk(isBoolean(42)); +assert.notOk(isBoolean(NaN)); +assert.notOk(isBoolean(Infinity)); + +assert.ok(isBoolean(new Boolean(42))); +assert.ok(isBoolean(false)); +assert.ok(isBoolean(Object(false))); +assert.ok(isBoolean(true)); +assert.ok(isBoolean(Object(true))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-boolean-object +[2]: https://versionbadg.es/inspect-js/is-boolean-object.svg +[5]: https://david-dm.org/inspect-js/is-boolean-object.svg +[6]: https://david-dm.org/inspect-js/is-boolean-object +[7]: https://david-dm.org/inspect-js/is-boolean-object/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-boolean-object#info=devDependencies +[11]: https://nodei.co/npm/is-boolean-object.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-boolean-object.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-boolean-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-boolean-object +[codecov-image]: https://codecov.io/gh/inspect-js/is-boolean-object/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-boolean-object/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-boolean-object +[actions-url]: https://github.com/inspect-js/is-boolean-object/actions diff --git a/node_modules/is-boolean-object/index.js b/node_modules/is-boolean-object/index.js new file mode 100644 index 0000000..e1011f6 --- /dev/null +++ b/node_modules/is-boolean-object/index.js @@ -0,0 +1,26 @@ +'use strict'; + +var callBound = require('call-bind/callBound'); +var $boolToStr = callBound('Boolean.prototype.toString'); +var $toString = callBound('Object.prototype.toString'); + +var tryBooleanObject = function booleanBrandCheck(value) { + try { + $boolToStr(value); + return true; + } catch (e) { + return false; + } +}; +var boolClass = '[object Boolean]'; +var hasToStringTag = require('has-tostringtag/shams')(); + +module.exports = function isBoolean(value) { + if (typeof value === 'boolean') { + return true; + } + if (value === null || typeof value !== 'object') { + return false; + } + return hasToStringTag && Symbol.toStringTag in value ? tryBooleanObject(value) : $toString(value) === boolClass; +}; diff --git a/node_modules/is-boolean-object/package.json b/node_modules/is-boolean-object/package.json new file mode 100644 index 0000000..06196f6 --- /dev/null +++ b/node_modules/is-boolean-object/package.json @@ -0,0 +1,87 @@ +{ + "name": "is-boolean-object", + "version": "1.1.2", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "Is this value a JS Boolean? This module works cross-realm/iframe, and despite ES6 @@toStringTag.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only && npm run test:harmony && npm run test:corejs", + "tests-only": "nyc tape 'test/**/*.js'", + "test:harmony": "node --harmony --es-staging test", + "test:corejs": "nyc tape test-corejs.js", + "posttest": "aud --production", + "prelint": "npm run eccheck", + "lint": "eslint --ext=js,mjs .", + "eccheck": "eclint check $(git ls-files)", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-boolean-object.git" + }, + "keywords": [ + "Boolean", + "ES6", + "toStringTag", + "@@toStringTag", + "Boolean object", + "true", + "false", + "is-boolean" + ], + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "core-js": "^3.16.0", + "eclint": "^2.8.1", + "eslint": "^7.32.0", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.0" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/is-boolean-object/test/index.js b/node_modules/is-boolean-object/test/index.js new file mode 100644 index 0000000..cd4c44f --- /dev/null +++ b/node_modules/is-boolean-object/test/index.js @@ -0,0 +1,48 @@ +'use strict'; + +var test = require('tape'); +var isBoolean = require('../'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('not Booleans', function (t) { + t.test('primitives', function (st) { + st.notOk(isBoolean(), 'undefined is not Boolean'); + st.notOk(isBoolean(null), 'null is not Boolean'); + st.notOk(isBoolean(0), '0 is not Boolean'); + st.notOk(isBoolean(NaN), 'NaN is not Boolean'); + st.notOk(isBoolean(Infinity), 'Infinity is not Boolean'); + st.notOk(isBoolean('foo'), 'string is not Boolean'); + st.end(); + }); + + t.test('objects', function (st) { + st.notOk(isBoolean(Object(42)), 'number object is not Boolean'); + st.notOk(isBoolean([]), 'array is not Boolean'); + st.notOk(isBoolean({}), 'object is not Boolean'); + st.notOk(isBoolean(function () {}), 'function is not Boolean'); + st.notOk(isBoolean(/a/g), 'regex literal is not Boolean'); + st.notOk(isBoolean(new RegExp('a', 'g')), 'regex object is not Boolean'); + st.notOk(isBoolean(new Date()), 'new Date() is not Boolean'); + st.end(); + }); + + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + var fakeBoolean = { + toString: function () { return 'true'; }, + valueOf: function () { return true; } + }; + fakeBoolean[Symbol.toStringTag] = 'Boolean'; + t.notOk(isBoolean(fakeBoolean), 'fake Boolean with @@toStringTag "Boolean" is not Boolean'); + t.end(); +}); + +test('Booleans', function (t) { + t.ok(isBoolean(true), 'true is Boolean'); + t.ok(isBoolean(false), 'false is Boolean'); + t.ok(isBoolean(Object(true)), 'Object(true) is Boolean'); + t.ok(isBoolean(Object(false)), 'Object(false) is Boolean'); + t.end(); +}); diff --git a/node_modules/is-callable/.editorconfig b/node_modules/is-callable/.editorconfig new file mode 100644 index 0000000..f5f5679 --- /dev/null +++ b/node_modules/is-callable/.editorconfig @@ -0,0 +1,31 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 +max_line_length = off + +[README.md] +indent_style = off +indent_size = off +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[coverage*/**/*] +indent_style = off +indent_size = off +max_line_length = off diff --git a/node_modules/is-callable/.eslintrc b/node_modules/is-callable/.eslintrc new file mode 100644 index 0000000..ce033bf --- /dev/null +++ b/node_modules/is-callable/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-statements-per-line": [2, { "max": 2 }], + }, +} diff --git a/node_modules/is-callable/.github/FUNDING.yml b/node_modules/is-callable/.github/FUNDING.yml new file mode 100644 index 0000000..0fdebd0 --- /dev/null +++ b/node_modules/is-callable/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-callable +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-callable/.nycrc b/node_modules/is-callable/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-callable/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-callable/CHANGELOG.md b/node_modules/is-callable/CHANGELOG.md new file mode 100644 index 0000000..32788cd --- /dev/null +++ b/node_modules/is-callable/CHANGELOG.md @@ -0,0 +1,158 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.7](https://github.com/inspect-js/is-callable/compare/v1.2.6...v1.2.7) - 2022-09-23 + +### Commits + +- [Fix] recognize `document.all` in IE 6-10 [`06c1db2`](https://github.com/inspect-js/is-callable/commit/06c1db2b9b2e0f28428e1293eb572f8f93871ec7) +- [Tests] improve logic for FF 20-35 [`0f7d9b9`](https://github.com/inspect-js/is-callable/commit/0f7d9b9c7fe149ca87e71f0a125ade251a6a578c) +- [Fix] handle `document.all` in FF 27 (and +, probably) [`696c661`](https://github.com/inspect-js/is-callable/commit/696c661b8c0810c2d05ab172f1607f4e77ddf81e) +- [Tests] fix proxy tests in FF 42-63 [`985df0d`](https://github.com/inspect-js/is-callable/commit/985df0dd36f8cfe6f1993657b7c0f4cfc19dae30) +- [readme] update tested browsers [`389e919`](https://github.com/inspect-js/is-callable/commit/389e919493b1cb2010126b0411e5291bf76169bd) +- [Fix] detect `document.all` in Opera 12.16 [`b9f1022`](https://github.com/inspect-js/is-callable/commit/b9f1022b3d7e466b7f09080bd64c253caf644325) +- [Fix] HTML elements: properly report as callable in Opera 12.16 [`17391fe`](https://github.com/inspect-js/is-callable/commit/17391fe02b895777c4337be28dca3b364b743b34) +- [Tests] fix inverted logic in FF3 test [`056ebd4`](https://github.com/inspect-js/is-callable/commit/056ebd48790f46ca18ff5b12f51b44c08ccc3595) + +## [v1.2.6](https://github.com/inspect-js/is-callable/compare/v1.2.5...v1.2.6) - 2022-09-14 + +### Commits + +- [Fix] work for `document.all` in Firefox 3 and IE 6-8 [`015132a`](https://github.com/inspect-js/is-callable/commit/015132aaef886ec777b5b3593ef4ce461dd0c7d4) +- [Test] skip function toString check for nullish values [`8698116`](https://github.com/inspect-js/is-callable/commit/8698116f95eb59df8b48ec8e4585fc1cdd8cae9f) +- [readme] add "supported engines" section [`0442207`](https://github.com/inspect-js/is-callable/commit/0442207a89a1554d41ba36daf21862ef7ccbd500) +- [Tests] skip one of the fixture objects in FF 3.6 [`a501141`](https://github.com/inspect-js/is-callable/commit/a5011410bc6edb276c6ec8b47ce5c5d83c4bee15) +- [Tests] allow `class` constructor tests to fail in FF v45 - v54, which has undetectable classes [`b12e4a4`](https://github.com/inspect-js/is-callable/commit/b12e4a4d8c438678bd7710f9f896680150766b51) +- [Fix] Safari 4: regexes should not be considered callable [`4b732ff`](https://github.com/inspect-js/is-callable/commit/4b732ffa34346db3f0193ea4e46b7d4e637e6c82) +- [Fix] properly recognize `document.all` in Safari 4 [`3193735`](https://github.com/inspect-js/is-callable/commit/319373525dc4603346661641840cd9a3e0613136) + +## [v1.2.5](https://github.com/inspect-js/is-callable/compare/v1.2.4...v1.2.5) - 2022-09-11 + +### Commits + +- [actions] reuse common workflows [`5bb4b32`](https://github.com/inspect-js/is-callable/commit/5bb4b32dc93987328ab4f396601f751c4a7abd62) +- [meta] better `eccheck` command [`b9bd597`](https://github.com/inspect-js/is-callable/commit/b9bd597322b6e3a24c74c09881ca73e1d9f9f485) +- [meta] use `npmignore` to autogenerate an npmignore file [`3192d38`](https://github.com/inspect-js/is-callable/commit/3192d38527c7fc461d05d5aa93d47628e658bc45) +- [Fix] for HTML constructors, always use `tryFunctionObject` even in pre-toStringTag browsers [`3076ea2`](https://github.com/inspect-js/is-callable/commit/3076ea21d1f6ecc1cb711dcf1da08f257892c72b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `available-typed-arrays`, `object-inspect`, `safe-publish-latest`, `tape` [`8986746`](https://github.com/inspect-js/is-callable/commit/89867464c42adc5cd375ee074a4574b0295442cb) +- [meta] add `auto-changelog` [`7dda9d0`](https://github.com/inspect-js/is-callable/commit/7dda9d04e670a69ae566c8fa596da4ff4371e615) +- [Fix] properly report `document.all` [`da90b2b`](https://github.com/inspect-js/is-callable/commit/da90b2b68dc4f33702c2e01ad07b4f89bcb60984) +- [actions] update codecov uploader [`c8f847c`](https://github.com/inspect-js/is-callable/commit/c8f847c90e04e54ff73c7cfae86e96e94990e324) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`899ae00`](https://github.com/inspect-js/is-callable/commit/899ae00b6abd10d81fc8bc7f02b345fd885d5f56) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-value-fixtures`, `object-inspect`, `tape` [`344e913`](https://github.com/inspect-js/is-callable/commit/344e913b149609bf741aa7345fa32dc0b90d8893) +- [meta] remove greenkeeper config [`737dce5`](https://github.com/inspect-js/is-callable/commit/737dce5590b1abb16183a63cb9d7d26920b3b394) +- [meta] npmignore coverage output [`680a883`](https://github.com/inspect-js/is-callable/commit/680a8839071bf36a419fe66e1ced7a3303c27b28) + + +1.2.4 / 2021-08-05 +================= + * [Fix] use `has-tostringtag` approach to behave correctly in the presence of symbol shams + * [readme] fix repo URLs + * [readme] add actions and codecov badges + * [readme] remove defunct badges + * [meta] ignore eclint checking coverage output + * [meta] use `prepublishOnly` script for npm 7+ + * [actions] use `node/install` instead of `node/run`; use `codecov` action + * [actions] remove unused workflow file + * [Tests] run `nyc` on all tests; use `tape` runner + * [Tests] use `available-typed-arrays`, `for-each`, `has-symbols`, `object-inspect` + * [Dev Deps] update `available-typed-arrays`, `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` + +1.2.3 / 2021-01-31 +================= + * [Fix] `document.all` is callable (do not use `document.all`!) + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` + * [Tests] migrate tests to Github Actions + * [actions] add "Allow Edits" workflow + * [actions] switch Automatic Rebase workflow to `pull_request_target` event + +1.2.2 / 2020-09-21 +================= + * [Fix] include actual fix from 579179e + * [Dev Deps] update `eslint` + +1.2.1 / 2020-09-09 +================= + * [Fix] phantomjs‘ Reflect.apply does not throw properly on a bad array-like + * [Dev Deps] update `eslint`, `@ljharb/eslint-config` + * [meta] fix eclint error + +1.2.0 / 2020-06-02 +================= + * [New] use `Reflect.apply`‑based callability detection + * [readme] add install instructions (#55) + * [meta] only run `aud` on prod deps + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `make-arrow-function`, `make-generator-function`; add `aud`, `safe-publish-latest`, `make-async-function` + * [Tests] add tests for function proxies (#53, #25) + +1.1.5 / 2019-12-18 +================= + * [meta] remove unused Makefile and associated utilities + * [meta] add `funding` field; add FUNDING.yml + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `semver`, `tape`, `covert`, `rimraf` + * [Tests] use shared travis configs + * [Tests] use `eccheck` over `editorconfig-tools` + * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops + * [Tests] remove `jscs` + * [actions] add automatic rebasing / merge commit blocking + +1.1.4 / 2018-07-02 +================= + * [Fix] improve `class` and arrow function detection (#30, #31) + * [Tests] on all latest node minors; improve matrix + * [Dev Deps] update all dev deps + +1.1.3 / 2016-02-27 +================= + * [Fix] ensure “class “ doesn’t screw up “class” detection + * [Tests] up to `node` `v5.7`, `v4.3` + * [Dev Deps] update to `eslint` v2, `@ljharb/eslint-config`, `jscs` + +1.1.2 / 2016-01-15 +================= + * [Fix] Make sure comments don’t screw up “class” detection (#4) + * [Tests] up to `node` `v5.3` + * [Tests] Add `parallelshell`, run both `--es-staging` and stock tests at once + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Refactor] convert `isNonES6ClassFn` into `isES6ClassFn` + +1.1.1 / 2015-11-30 +================= + * [Fix] do not throw when a non-function has a function in its [[Prototype]] (#2) + * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `jscs`, `nsp`, `semver` + * [Tests] up to `node` `v5.1` + * [Tests] no longer allow node 0.8 to fail. + * [Tests] fix npm upgrades in older nodes + +1.1.0 / 2015-10-02 +================= + * [Fix] Some browsers report TypedArray constructors as `typeof object` + * [New] return false for "class" constructors, when possible. + * [Tests] up to `io.js` `v3.3`, `node` `v4.1` + * [Dev Deps] update `eslint`, `editorconfig-tools`, `nsp`, `tape`, `semver`, `jscs`, `covert`, `make-arrow-function` + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + +1.0.4 / 2015-01-30 +================= + * If @@toStringTag is not present, use the old-school Object#toString test. + +1.0.3 / 2015-01-29 +================= + * Add tests to ensure arrow functions are callable. + * Refactor to aid optimization of non-try/catch code. + +1.0.2 / 2015-01-29 +================= + * Fix broken package.json + +1.0.1 / 2015-01-29 +================= + * Add early exit for typeof not "function" + +1.0.0 / 2015-01-29 +================= + * Initial release. diff --git a/node_modules/is-callable/LICENSE b/node_modules/is-callable/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/node_modules/is-callable/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/is-callable/README.md b/node_modules/is-callable/README.md new file mode 100644 index 0000000..4f2b6d6 --- /dev/null +++ b/node_modules/is-callable/README.md @@ -0,0 +1,83 @@ +# is-callable [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag. + +## Supported engines +Automatically tested in every minor version of node. + +Manually tested in: + - Safari: v4 - v15 (4, 5, 5.1, 6.0.5, 6.2, 7.1, 8, 9.1.3, 10.1.2, 11.1.2, 12.1, 13.1.2, 14.1.2, 15.3, 15.6.1) + - Note: Safari 9 has `class`, but `Function.prototype.toString` hides that progeny and makes them look like functions, so `class` constructors will be reported by this package as callable, when they are not in fact callable. + - Chrome: v15 - v81, v83 - v106(every integer version) + - Note: This includes Edge v80+ and Opera v15+, which matches Chrome + - Firefox: v3, v3.6, v4 - v105 (every integer version) + - Note: v45 - v54 has `class`, but `Function.prototype.toString` hides that progeny and makes them look like functions, so `class` constructors will be reported by this package as callable, when they are not in fact callable. + - Note: in v42 - v63, `Function.prototype.toString` throws on HTML element constructors, or a Proxy to a function + - Note: in v20 - v35, HTML element constructors are not callable, despite having typeof `function`. + - Note: in v19, `document.all` is not callable. + - IE: v6 - v11(every integer version + - Opera: v11.1, v11.5, v11.6, v12.1, v12.14, v12.15, v12.16, v15+ v15+ matches Chrome + +## Example + +```js +var isCallable = require('is-callable'); +var assert = require('assert'); + +assert.notOk(isCallable(undefined)); +assert.notOk(isCallable(null)); +assert.notOk(isCallable(false)); +assert.notOk(isCallable(true)); +assert.notOk(isCallable([])); +assert.notOk(isCallable({})); +assert.notOk(isCallable(/a/g)); +assert.notOk(isCallable(new RegExp('a', 'g'))); +assert.notOk(isCallable(new Date())); +assert.notOk(isCallable(42)); +assert.notOk(isCallable(NaN)); +assert.notOk(isCallable(Infinity)); +assert.notOk(isCallable(new Number(42))); +assert.notOk(isCallable('foo')); +assert.notOk(isCallable(Object('foo'))); + +assert.ok(isCallable(function () {})); +assert.ok(isCallable(function* () {})); +assert.ok(isCallable(x => x * x)); +``` + +## Install + +Install with + +``` +npm install is-callable +``` + +## Tests + +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-callable +[2]: https://versionbadg.es/inspect-js/is-callable.svg +[5]: https://david-dm.org/inspect-js/is-callable.svg +[6]: https://david-dm.org/inspect-js/is-callable +[7]: https://david-dm.org/inspect-js/is-callable/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-callable#info=devDependencies +[11]: https://nodei.co/npm/is-callable.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-callable.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-callable.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-callable +[codecov-image]: https://codecov.io/gh/inspect-js/is-callable/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-callable/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-callable +[actions-url]: https://github.com/inspect-js/is-callable/actions diff --git a/node_modules/is-callable/index.js b/node_modules/is-callable/index.js new file mode 100644 index 0000000..f2a89f8 --- /dev/null +++ b/node_modules/is-callable/index.js @@ -0,0 +1,101 @@ +'use strict'; + +var fnToStr = Function.prototype.toString; +var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; +var badArrayLike; +var isCallableMarker; +if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { + try { + badArrayLike = Object.defineProperty({}, 'length', { + get: function () { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + // eslint-disable-next-line no-throw-literal + reflectApply(function () { throw 42; }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply = null; + } + } +} else { + reflectApply = null; +} + +var constructorRegex = /^\s*class\b/; +var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } +}; + +var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var objectClass = '[object Object]'; +var fnClass = '[object Function]'; +var genClass = '[object GeneratorFunction]'; +var ddaClass = '[object HTMLAllCollection]'; // IE 11 +var ddaClass2 = '[object HTML document.all class]'; +var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 +var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` + +var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing + +var isDDA = function isDocumentDotAll() { return false; }; +if (typeof document === 'object') { + // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly + var all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + /* globals document: false */ + // in IE 6-8, typeof document.all is "object" and it's truthy + if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { + try { + var str = toStr.call(value); + return ( + str === ddaClass + || str === ddaClass2 + || str === ddaClass3 // opera 12.16 + || str === objectClass // IE 6-8 + ) && value('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + return false; + }; + } +} + +module.exports = reflectApply + ? function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + try { + reflectApply(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { return false; } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } + : function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } + return tryFunctionObject(value); + }; diff --git a/node_modules/is-callable/package.json b/node_modules/is-callable/package.json new file mode 100644 index 0000000..aa3e8df --- /dev/null +++ b/node_modules/is-callable/package.json @@ -0,0 +1,106 @@ +{ + "name": "is-callable", + "version": "1.2.7", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only --", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs ." + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-callable.git" + }, + "keywords": [ + "Function", + "function", + "callable", + "generator", + "generator function", + "arrow", + "arrow function", + "ES6", + "toStringTag", + "@@toStringTag" + ], + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "available-typed-arrays": "^1.0.5", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "has-tostringtag": "^1.0.0", + "make-arrow-function": "^1.2.0", + "make-async-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.2", + "rimraf": "^2.7.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true, + "startingVersion": "v1.2.5" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/is-callable/test/index.js b/node_modules/is-callable/test/index.js new file mode 100644 index 0000000..bfe5db5 --- /dev/null +++ b/node_modules/is-callable/test/index.js @@ -0,0 +1,244 @@ +'use strict'; + +/* eslint no-magic-numbers: 1 */ + +var test = require('tape'); +var isCallable = require('../'); +var hasToStringTag = require('has-tostringtag/shams')(); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var typedArrayNames = require('available-typed-arrays')(); +var generators = require('make-generator-function')(); +var arrows = require('make-arrow-function').list(); +var asyncs = require('make-async-function').list(); +var weirdlyCommentedArrowFn; +try { + /* eslint-disable no-new-func */ + weirdlyCommentedArrowFn = Function('return cl/*/**/=>/**/ass - 1;')(); + /* eslint-enable no-new-func */ +} catch (e) { /**/ } + +var isIE68 = !(0 in [undefined]); +var isFirefox = typeof window !== 'undefined' && ('netscape' in window) && (/ rv:/).test(navigator.userAgent); +var fnToStringCoerces; +try { + Function.prototype.toString.call(v.uncoercibleFnObject); + fnToStringCoerces = true; +} catch (e) { + fnToStringCoerces = false; +} + +var noop = function () {}; +var classFake = function classFake() { }; // eslint-disable-line func-name-matching +var returnClass = function () { return ' class '; }; +var return3 = function () { return 3; }; +/* for coverage */ +noop(); +classFake(); +returnClass(); +return3(); +/* end for coverage */ + +var proxy; +if (typeof Proxy === 'function') { + try { + proxy = new Proxy(function () {}, {}); + // for coverage + proxy(); + String(proxy); + } catch (_) { + // Older engines throw a `TypeError` when `Function.prototype.toString` is called on a Proxy object. + proxy = null; + } +} + +var invokeFunction = function invokeFunctionString(str) { + var result; + try { + /* eslint-disable no-new-func */ + var fn = Function(str); + /* eslint-enable no-new-func */ + result = fn(); + } catch (e) {} + return result; +}; + +var classConstructor = invokeFunction('"use strict"; return class Foo {}'); +var hasDetectableClasses = classConstructor && Function.prototype.toString.call(classConstructor) === 'class Foo {}'; + +var commentedClass = invokeFunction('"use strict"; return class/*kkk*/\n//blah\n Bar\n//blah\n {}'); +var commentedClassOneLine = invokeFunction('"use strict"; return class/**/A{}'); +var classAnonymous = invokeFunction('"use strict"; return class{}'); +var classAnonymousCommentedOneLine = invokeFunction('"use strict"; return class/*/*/{}'); + +test('not callables', function (t) { + t.notOk(isCallable(), 'implicit undefined is not callable'); + + forEach(v.nonFunctions.concat([ + Object(42), + Object('foo'), + NaN, + [], + /a/g, + new RegExp('a', 'g'), + new Date() + ]), function (nonFunction) { + if (fnToStringCoerces && nonFunction === v.coercibleFnObject) { + t.comment('FF 3.6 has a Function toString that coerces its receiver, so this test is skipped'); + return; + } + if (nonFunction != null) { // eslint-disable-line eqeqeq + if (isFirefox) { + // Firefox 3 throws some kind of *object* here instead of a proper error + t['throws']( + function () { Function.prototype.toString.call(nonFunction); }, + inspect(nonFunction) + ' can not be used with Function toString' + ); + } else { + t['throws']( + function () { Function.prototype.toString.call(nonFunction); }, + TypeError, + inspect(nonFunction) + ' can not be used with Function toString' + ); + } + } + t.equal(isCallable(nonFunction), false, inspect(nonFunction) + ' is not callable'); + }); + + t.test('non-function with function in its [[Prototype]] chain', function (st) { + var Foo = function Bar() {}; + Foo.prototype = noop; + st.equal(isCallable(Foo), true, 'sanity check: Foo is callable'); + st.equal(isCallable(new Foo()), false, 'instance of Foo is not callable'); + st.end(); + }); + + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + var fakeFunction = { + toString: function () { return String(return3); }, + valueOf: return3 + }; + fakeFunction[Symbol.toStringTag] = 'Function'; + t.equal(String(fakeFunction), String(return3)); + t.equal(Number(fakeFunction), return3()); + t.notOk(isCallable(fakeFunction), 'fake Function with @@toStringTag "Function" is not callable'); + t.end(); +}); + +test('Functions', function (t) { + t.ok(isCallable(noop), 'function is callable'); + t.ok(isCallable(classFake), 'function with name containing "class" is callable'); + t.ok(isCallable(returnClass), 'function with string " class " is callable'); + t.ok(isCallable(isCallable), 'isCallable is callable'); + t.end(); +}); + +test('Typed Arrays', { skip: typedArrayNames.length === 0 }, function (st) { + forEach(typedArrayNames, function (typedArray) { + st.ok(isCallable(global[typedArray]), typedArray + ' is callable'); + }); + st.end(); +}); + +test('Generators', { skip: generators.length === 0 }, function (t) { + forEach(generators, function (genFn) { + t.ok(isCallable(genFn), 'generator function ' + genFn + ' is callable'); + }); + t.end(); +}); + +test('Arrow functions', { skip: arrows.length === 0 }, function (t) { + forEach(arrows, function (arrowFn) { + t.ok(isCallable(arrowFn), 'arrow function ' + arrowFn + ' is callable'); + }); + t.ok(isCallable(weirdlyCommentedArrowFn), 'weirdly commented arrow functions are callable'); + t.end(); +}); + +test('"Class" constructors', { + skip: !classConstructor || !commentedClass || !commentedClassOneLine || !classAnonymous, todo: !hasDetectableClasses +}, function (t) { + if (!hasDetectableClasses) { + t.comment('WARNING: This engine does not support detectable classes'); + } + t.notOk(isCallable(classConstructor), 'class constructors are not callable'); + t.notOk(isCallable(commentedClass), 'class constructors with comments in the signature are not callable'); + t.notOk(isCallable(commentedClassOneLine), 'one-line class constructors with comments in the signature are not callable'); + t.notOk(isCallable(classAnonymous), 'anonymous class constructors are not callable'); + t.notOk(isCallable(classAnonymousCommentedOneLine), 'anonymous one-line class constructors with comments in the signature are not callable'); + t.end(); +}); + +test('`async function`s', { skip: asyncs.length === 0 }, function (t) { + forEach(asyncs, function (asyncFn) { + t.ok(isCallable(asyncFn), '`async function` ' + asyncFn + ' is callable'); + }); + t.end(); +}); + +test('proxies of functions', { skip: !proxy }, function (t) { + t.equal(isCallable(proxy), true, 'proxies of functions are callable'); + t.end(); +}); + +test('throwing functions', function (t) { + t.plan(1); + + var thrower = function (a) { return a.b; }; + t.ok(isCallable(thrower), 'a function that throws is callable'); +}); + +test('DOM', function (t) { + /* eslint-env browser */ + + t.test('document.all', { skip: typeof document !== 'object' }, function (st) { + st.notOk(isCallable(document), 'document is not callable'); + + var all = document.all; + var isFF3 = !isIE68 && Object.prototype.toString(all) === Object.prototype.toString.call(document.all); // this test is true in IE 6-8 also + var expected = false; + if (!isFF3) { + try { + expected = document.all('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + st.equal(isCallable(document.all), expected, 'document.all is ' + (isFF3 ? 'not ' : '') + 'callable'); + + st.end(); + }); + + forEach([ + 'HTMLElement', + 'HTMLAnchorElement' + ], function (name) { + var constructor = global[name]; + + t.test(name, { skip: !constructor }, function (st) { + st.match(typeof constructor, /^(?:function|object)$/, name + ' is a function or object'); + + var callable = isCallable(constructor); + st.equal(typeof callable, 'boolean'); + + if (callable) { + st.doesNotThrow( + function () { Function.prototype.toString.call(constructor); }, + 'anything this library claims is callable should be accepted by Function toString' + ); + } else { + st['throws']( + function () { Function.prototype.toString.call(constructor); }, + TypeError, + 'anything this library claims is not callable should not be accepted by Function toString' + ); + } + + st.end(); + }); + }); + + t.end(); +}); diff --git a/node_modules/is-core-module/.eslintrc b/node_modules/is-core-module/.eslintrc new file mode 100644 index 0000000..f2e0726 --- /dev/null +++ b/node_modules/is-core-module/.eslintrc @@ -0,0 +1,18 @@ +{ + "extends": "@ljharb", + "root": true, + "rules": { + "func-style": 1, + }, + "overrides": [ + { + "files": "test/**", + "rules": { + "global-require": 0, + "max-depth": 0, + "max-lines-per-function": 0, + "no-negated-condition": 0, + }, + }, + ], +} diff --git a/node_modules/is-core-module/.nycrc b/node_modules/is-core-module/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-core-module/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-core-module/CHANGELOG.md b/node_modules/is-core-module/CHANGELOG.md new file mode 100644 index 0000000..f44fd84 --- /dev/null +++ b/node_modules/is-core-module/CHANGELOG.md @@ -0,0 +1,173 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.13.0](https://github.com/inspect-js/is-core-module/compare/v2.12.1...v2.13.0) - 2023-08-05 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `semver`, `tape` [`c75b263`](https://github.com/inspect-js/is-core-module/commit/c75b263d047cb53430c3970107e5eb64d6cd6c0c) +- [New] `node:test/reporters` and `wasi`/`node:wasi` are in v18.17 [`d76cbf8`](https://github.com/inspect-js/is-core-module/commit/d76cbf8e9b208acfd98913fed5a5f45cb15fe5dc) + +## [v2.12.1](https://github.com/inspect-js/is-core-module/compare/v2.12.0...v2.12.1) - 2023-05-16 + +### Commits + +- [Fix] `test/reporters` now requires the `node:` prefix as of v20.2 [`12183d0`](https://github.com/inspect-js/is-core-module/commit/12183d0d8e4edf56b6ce18a1b3be54bfce10175b) + +## [v2.12.0](https://github.com/inspect-js/is-core-module/compare/v2.11.0...v2.12.0) - 2023-04-10 + +### Commits + +- [actions] update rebase action to use reusable workflow [`c0a7251`](https://github.com/inspect-js/is-core-module/commit/c0a7251f734f3c621932c5fcdfd1bf966b42ca32) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`9ae8b7f`](https://github.com/inspect-js/is-core-module/commit/9ae8b7fac03c369861d0991b4a2ce8d4848e6a7d) +- [New] `test/reporters` added in v19.9, `wasi` added in v20 [`9d5341a`](https://github.com/inspect-js/is-core-module/commit/9d5341ab32053f25b7fa7db3c0e18461db24a79c) +- [Dev Deps] add missing `in-publish` dep [`5980245`](https://github.com/inspect-js/is-core-module/commit/59802456e9ac919fa748f53be9d8fbf304a197df) + +## [v2.11.0](https://github.com/inspect-js/is-core-module/compare/v2.10.0...v2.11.0) - 2022-10-18 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`3360011`](https://github.com/inspect-js/is-core-module/commit/33600118857b46177178072fba2affcdeb009d12) +- [Dev Deps] update `aud`, `tape` [`651c6b0`](https://github.com/inspect-js/is-core-module/commit/651c6b0cc2799d4130866cf43ad333dcade3d26c) +- [New] `inspector/promises` and `node:inspector/promises` is now available in node 19 [`22d332f`](https://github.com/inspect-js/is-core-module/commit/22d332fe22ac050305444e0781ff85af819abcb0) + +## [v2.10.0](https://github.com/inspect-js/is-core-module/compare/v2.9.0...v2.10.0) - 2022-08-03 + +### Commits + +- [New] `node:test` is now available in node ^16.17 [`e8fd36e`](https://github.com/inspect-js/is-core-module/commit/e8fd36e9b86c917775a07cc473b62a3294f459f2) +- [Tests] improve skip message [`c014a4c`](https://github.com/inspect-js/is-core-module/commit/c014a4c0cd6eb15fff573ae4709191775e70cab4) + +## [v2.9.0](https://github.com/inspect-js/is-core-module/compare/v2.8.1...v2.9.0) - 2022-04-19 + +### Commits + +- [New] add `node:test`, in node 18+ [`f853eca`](https://github.com/inspect-js/is-core-module/commit/f853eca801d0a7d4e1dbb670f1b6d9837d9533c5) +- [Tests] use `mock-property` [`03b3644`](https://github.com/inspect-js/is-core-module/commit/03b3644dff4417f4ba5a7d0aa0138f5f6b3e5c46) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`7c0e2d0`](https://github.com/inspect-js/is-core-module/commit/7c0e2d06ed2a89acf53abe2ab34d703ed5b03455) +- [meta] simplify "exports" [`d6ed201`](https://github.com/inspect-js/is-core-module/commit/d6ed201eba7fbba0e59814a9050fc49a6e9878c8) + +## [v2.8.1](https://github.com/inspect-js/is-core-module/compare/v2.8.0...v2.8.1) - 2022-01-05 + +### Commits + +- [actions] reuse common workflows [`cd2cf9b`](https://github.com/inspect-js/is-core-module/commit/cd2cf9b3b66c8d328f65610efe41e9325db7716d) +- [Fix] update node 0.4 results [`062195d`](https://github.com/inspect-js/is-core-module/commit/062195d89f0876a88b95d378b43f7fcc1205bc5b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0790b62`](https://github.com/inspect-js/is-core-module/commit/0790b6222848c6167132f9f73acc3520fa8d1298) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7d139a6`](https://github.com/inspect-js/is-core-module/commit/7d139a6d767709eabf0a0251e074ec1fb230c06e) +- [Tests] run `nyc` in `tests-only`, not `test` [`780e8a0`](https://github.com/inspect-js/is-core-module/commit/780e8a049951c71cf78b1707f0871c48a28bde14) + +## [v2.8.0](https://github.com/inspect-js/is-core-module/compare/v2.7.0...v2.8.0) - 2021-10-14 + +### Commits + +- [actions] update codecov uploader [`0cfe94e`](https://github.com/inspect-js/is-core-module/commit/0cfe94e106a7d005ea03e008c0a21dec13a77904) +- [New] add `readline/promises` to node v17+ [`4f78c30`](https://github.com/inspect-js/is-core-module/commit/4f78c3008b1b58b4db6dc91d99610b1bc859da7e) +- [Tests] node ^14.18 supports `node:` prefixes for CJS [`43e2f17`](https://github.com/inspect-js/is-core-module/commit/43e2f177452cea2f0eaf34f61b5407217bbdb6f4) + +## [v2.7.0](https://github.com/inspect-js/is-core-module/compare/v2.6.0...v2.7.0) - 2021-09-27 + +### Commits + +- [New] node `v14.18` added `node:`-prefixed core modules to `require` [`6d943ab`](https://github.com/inspect-js/is-core-module/commit/6d943abe81382b9bbe344384d80fbfebe1cc0526) +- [Tests] add coverage for Object.prototype pollution [`c6baf5f`](https://github.com/inspect-js/is-core-module/commit/c6baf5f942311a1945c1af41167bb80b84df2af7) +- [Dev Deps] update `@ljharb/eslint-config` [`6717f00`](https://github.com/inspect-js/is-core-module/commit/6717f000d063ea57beb772bded36c2f056ac404c) +- [eslint] fix linter warning [`594c10b`](https://github.com/inspect-js/is-core-module/commit/594c10bb7d39d7eb00925c90924199ff596184b2) +- [meta] add `sideEffects` flag [`c32cfa5`](https://github.com/inspect-js/is-core-module/commit/c32cfa5195632944c4dd4284a142b8476e75be13) + +## [v2.6.0](https://github.com/inspect-js/is-core-module/compare/v2.5.0...v2.6.0) - 2021-08-17 + +### Commits + +- [Dev Deps] update `eslint`, `tape` [`6cc928f`](https://github.com/inspect-js/is-core-module/commit/6cc928f8a4bba66aeeccc4f6beeac736d4bd3081) +- [New] add `stream/consumers` to node `>= 16.7` [`a1a423e`](https://github.com/inspect-js/is-core-module/commit/a1a423e467e4cc27df180234fad5bab45943e67d) +- [Refactor] Remove duplicated `&&` operand [`86faea7`](https://github.com/inspect-js/is-core-module/commit/86faea738213a2433c62d1098488dc9314dca832) +- [Tests] include prereleases [`a4da7a6`](https://github.com/inspect-js/is-core-module/commit/a4da7a6abf7568e2aa4fd98e69452179f1850963) + +## [v2.5.0](https://github.com/inspect-js/is-core-module/compare/v2.4.0...v2.5.0) - 2021-07-12 + +### Commits + +- [Dev Deps] update `auto-changelog`, `eslint` [`6334cc9`](https://github.com/inspect-js/is-core-module/commit/6334cc94f3af7469685bd8f236740991baaf2705) +- [New] add `stream/web` to node v16.5+ [`17ac59b`](https://github.com/inspect-js/is-core-module/commit/17ac59b662d63e220a2e5728625f005c24f177b2) + +## [v2.4.0](https://github.com/inspect-js/is-core-module/compare/v2.3.0...v2.4.0) - 2021-05-09 + +### Commits + +- [readme] add actions and codecov badges [`82b7faa`](https://github.com/inspect-js/is-core-module/commit/82b7faa12b56dbe47fbea67e1a5b9e447027ba40) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`8096868`](https://github.com/inspect-js/is-core-module/commit/8096868c024a161ccd4d44110b136763e92eace8) +- [Dev Deps] update `eslint` [`6726824`](https://github.com/inspect-js/is-core-module/commit/67268249b88230018c510f6532a8046d7326346f) +- [New] add `diagnostics_channel` to node `^14.17` [`86c6563`](https://github.com/inspect-js/is-core-module/commit/86c65634201b8ff9b3e48a9a782594579c7f5c3c) +- [meta] fix prepublish script [`697a01e`](https://github.com/inspect-js/is-core-module/commit/697a01e3c9c0be074066520954f30fb28532ec57) + +## [v2.3.0](https://github.com/inspect-js/is-core-module/compare/v2.2.0...v2.3.0) - 2021-04-24 + +### Commits + +- [meta] do not publish github action workflow files [`060d4bb`](https://github.com/inspect-js/is-core-module/commit/060d4bb971a29451c19ff336eb56bee27f9fa95a) +- [New] add support for `node:` prefix, in node 16+ [`7341223`](https://github.com/inspect-js/is-core-module/commit/73412230a769f6e81c05eea50b6520cebf54ed2f) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`016269a`](https://github.com/inspect-js/is-core-module/commit/016269abae9f6657a5254adfbb813f09a05067f9) +- [patch] remove unneeded `.0` in version ranges [`cb466a6`](https://github.com/inspect-js/is-core-module/commit/cb466a6d89e52b8389e5c12715efcd550c41cea3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`c9f9c39`](https://github.com/inspect-js/is-core-module/commit/c9f9c396ace60ef81906f98059c064e6452473ed) +- [actions] update workflows [`3ee4a89`](https://github.com/inspect-js/is-core-module/commit/3ee4a89fd5a02fccd43882d905448ea6a98e9a3c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`dee4fed`](https://github.com/inspect-js/is-core-module/commit/dee4fed79690c1d43a22f7fa9426abebdc6d727f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`7d046ba`](https://github.com/inspect-js/is-core-module/commit/7d046ba07ae8c9292e43652694ca808d7b309de8) +- [meta] use `prepublishOnly` script for npm 7+ [`149e677`](https://github.com/inspect-js/is-core-module/commit/149e6771a5ede6d097e71785b467a9c4b4977cc7) +- [readme] remove travis badge [`903b51d`](https://github.com/inspect-js/is-core-module/commit/903b51d6b69b98abeabfbc3695c345b02646f19c) + +## [v2.2.0](https://github.com/inspect-js/is-core-module/compare/v2.1.0...v2.2.0) - 2020-11-26 + +### Commits + +- [Tests] migrate tests to Github Actions [`c919f57`](https://github.com/inspect-js/is-core-module/commit/c919f573c0a92d10a0acad0b650b5aecb033d426) +- [patch] `core.json`: %s/ /\t/g [`db3f685`](https://github.com/inspect-js/is-core-module/commit/db3f68581f53e73cc09cd675955eb1bdd6a5a39b) +- [Tests] run `nyc` on all tests [`b2f925f`](https://github.com/inspect-js/is-core-module/commit/b2f925f8866f210ef441f39fcc8cc42692ab89b1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`; add `safe-publish-latest` [`89f02a2`](https://github.com/inspect-js/is-core-module/commit/89f02a2b4162246dea303a6ee31bb9a550b05c72) +- [New] add `path/posix`, `path/win32`, `util/types` [`77f94f1`](https://github.com/inspect-js/is-core-module/commit/77f94f1e90ffd7c0be2a3f1aa8574ebf7fd981b3) + +## [v2.1.0](https://github.com/inspect-js/is-core-module/compare/v2.0.0...v2.1.0) - 2020-11-04 + +### Commits + +- [Dev Deps] update `eslint` [`5e0034e`](https://github.com/inspect-js/is-core-module/commit/5e0034eae57c09c8f1bd769f502486a00f56c6e4) +- [New] Add `diagnostics_channel` [`c2d83d0`](https://github.com/inspect-js/is-core-module/commit/c2d83d0a0225a1a658945d9bab7036ea347d29ec) + +## [v2.0.0](https://github.com/inspect-js/is-core-module/compare/v1.0.2...v2.0.0) - 2020-09-29 + +### Commits + +- v2 implementation [`865aeb5`](https://github.com/inspect-js/is-core-module/commit/865aeb5ca0e90248a3dfff5d7622e4751fdeb9cd) +- Only apps should have lockfiles [`5a5e660`](https://github.com/inspect-js/is-core-module/commit/5a5e660d568e37eb44e17fb1ebb12a105205fc2b) +- Initial commit for v2 [`5a51524`](https://github.com/inspect-js/is-core-module/commit/5a51524e06f92adece5fbb138c69b7b9748a2348) +- Tests [`116eae4`](https://github.com/inspect-js/is-core-module/commit/116eae4fccd01bc72c1fd3cc4b7561c387afc496) +- [meta] add `auto-changelog` [`c24388b`](https://github.com/inspect-js/is-core-module/commit/c24388bee828d223040519d1f5b226ca35beee63) +- [actions] add "Automatic Rebase" and "require allow edits" actions [`34292db`](https://github.com/inspect-js/is-core-module/commit/34292dbcbadae0868aff03c22dbd8b7b8a11558a) +- [Tests] add `npm run lint` [`4f9eeee`](https://github.com/inspect-js/is-core-module/commit/4f9eeee7ddff10698bbf528620f4dc8d4fa3e697) +- [readme] fix travis badges, https all URLs [`e516a73`](https://github.com/inspect-js/is-core-module/commit/e516a73b0dccce20938c432b1ba512eae8eff9e9) +- [meta] create FUNDING.yml [`1aabebc`](https://github.com/inspect-js/is-core-module/commit/1aabebca98d01f8a04e46bc2e2520fa93cf21ac6) +- [Fix] `domain`: domain landed sometime > v0.7.7 and <= v0.7.12 [`2df7d37`](https://github.com/inspect-js/is-core-module/commit/2df7d37595d41b15eeada732b706b926c2771655) +- [Fix] `sys`: worked in 0.6, not 0.7, and 0.8+ [`a75c134`](https://github.com/inspect-js/is-core-module/commit/a75c134229e1e9441801f6b73f6a52489346eb65) + +## [v1.0.2](https://github.com/inspect-js/is-core-module/compare/v1.0.1...v1.0.2) - 2014-09-28 + +### Commits + +- simpler [`66fe90f`](https://github.com/inspect-js/is-core-module/commit/66fe90f9771581b9adc0c3900baa52c21b5baea2) + +## [v1.0.1](https://github.com/inspect-js/is-core-module/compare/v1.0.0...v1.0.1) - 2014-09-28 + +### Commits + +- remove stupid [`f21f906`](https://github.com/inspect-js/is-core-module/commit/f21f906f882c2bd656a5fc5ed6fbe48ddaffb2ac) +- update readme [`1eff0ec`](https://github.com/inspect-js/is-core-module/commit/1eff0ec69798d1ec65771552d1562911e90a8027) + +## v1.0.0 - 2014-09-28 + +### Commits + +- init [`48e5e76`](https://github.com/inspect-js/is-core-module/commit/48e5e76cac378fddb8c1f7d4055b8dfc943d6b96) diff --git a/node_modules/is-core-module/LICENSE b/node_modules/is-core-module/LICENSE new file mode 100644 index 0000000..2e50287 --- /dev/null +++ b/node_modules/is-core-module/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Dave Justice + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/is-core-module/README.md b/node_modules/is-core-module/README.md new file mode 100644 index 0000000..062d906 --- /dev/null +++ b/node_modules/is-core-module/README.md @@ -0,0 +1,40 @@ +# is-core-module [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version. + +## Example + +```js +var isCore = require('is-core-module'); +var assert = require('assert'); +assert(isCore('fs')); +assert(!isCore('butts')); +``` + +## Tests +Clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-core-module +[2]: https://versionbadg.es/inspect-js/is-core-module.svg +[5]: https://david-dm.org/inspect-js/is-core-module.svg +[6]: https://david-dm.org/inspect-js/is-core-module +[7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies +[11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-core-module.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-core-module +[codecov-image]: https://codecov.io/gh/inspect-js/is-core-module/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-core-module/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-core-module +[actions-url]: https://github.com/inspect-js/is-core-module/actions diff --git a/node_modules/is-core-module/core.json b/node_modules/is-core-module/core.json new file mode 100644 index 0000000..3cda693 --- /dev/null +++ b/node_modules/is-core-module/core.json @@ -0,0 +1,158 @@ +{ + "assert": true, + "node:assert": [">= 14.18 && < 15", ">= 16"], + "assert/strict": ">= 15", + "node:assert/strict": ">= 16", + "async_hooks": ">= 8", + "node:async_hooks": [">= 14.18 && < 15", ">= 16"], + "buffer_ieee754": ">= 0.5 && < 0.9.7", + "buffer": true, + "node:buffer": [">= 14.18 && < 15", ">= 16"], + "child_process": true, + "node:child_process": [">= 14.18 && < 15", ">= 16"], + "cluster": ">= 0.5", + "node:cluster": [">= 14.18 && < 15", ">= 16"], + "console": true, + "node:console": [">= 14.18 && < 15", ">= 16"], + "constants": true, + "node:constants": [">= 14.18 && < 15", ">= 16"], + "crypto": true, + "node:crypto": [">= 14.18 && < 15", ">= 16"], + "_debug_agent": ">= 1 && < 8", + "_debugger": "< 8", + "dgram": true, + "node:dgram": [">= 14.18 && < 15", ">= 16"], + "diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"], + "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"], + "dns": true, + "node:dns": [">= 14.18 && < 15", ">= 16"], + "dns/promises": ">= 15", + "node:dns/promises": ">= 16", + "domain": ">= 0.7.12", + "node:domain": [">= 14.18 && < 15", ">= 16"], + "events": true, + "node:events": [">= 14.18 && < 15", ">= 16"], + "freelist": "< 6", + "fs": true, + "node:fs": [">= 14.18 && < 15", ">= 16"], + "fs/promises": [">= 10 && < 10.1", ">= 14"], + "node:fs/promises": [">= 14.18 && < 15", ">= 16"], + "_http_agent": ">= 0.11.1", + "node:_http_agent": [">= 14.18 && < 15", ">= 16"], + "_http_client": ">= 0.11.1", + "node:_http_client": [">= 14.18 && < 15", ">= 16"], + "_http_common": ">= 0.11.1", + "node:_http_common": [">= 14.18 && < 15", ">= 16"], + "_http_incoming": ">= 0.11.1", + "node:_http_incoming": [">= 14.18 && < 15", ">= 16"], + "_http_outgoing": ">= 0.11.1", + "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"], + "_http_server": ">= 0.11.1", + "node:_http_server": [">= 14.18 && < 15", ">= 16"], + "http": true, + "node:http": [">= 14.18 && < 15", ">= 16"], + "http2": ">= 8.8", + "node:http2": [">= 14.18 && < 15", ">= 16"], + "https": true, + "node:https": [">= 14.18 && < 15", ">= 16"], + "inspector": ">= 8", + "node:inspector": [">= 14.18 && < 15", ">= 16"], + "inspector/promises": [">= 19"], + "node:inspector/promises": [">= 19"], + "_linklist": "< 8", + "module": true, + "node:module": [">= 14.18 && < 15", ">= 16"], + "net": true, + "node:net": [">= 14.18 && < 15", ">= 16"], + "node-inspect/lib/_inspect": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12", + "os": true, + "node:os": [">= 14.18 && < 15", ">= 16"], + "path": true, + "node:path": [">= 14.18 && < 15", ">= 16"], + "path/posix": ">= 15.3", + "node:path/posix": ">= 16", + "path/win32": ">= 15.3", + "node:path/win32": ">= 16", + "perf_hooks": ">= 8.5", + "node:perf_hooks": [">= 14.18 && < 15", ">= 16"], + "process": ">= 1", + "node:process": [">= 14.18 && < 15", ">= 16"], + "punycode": ">= 0.5", + "node:punycode": [">= 14.18 && < 15", ">= 16"], + "querystring": true, + "node:querystring": [">= 14.18 && < 15", ">= 16"], + "readline": true, + "node:readline": [">= 14.18 && < 15", ">= 16"], + "readline/promises": ">= 17", + "node:readline/promises": ">= 17", + "repl": true, + "node:repl": [">= 14.18 && < 15", ">= 16"], + "smalloc": ">= 0.11.5 && < 3", + "_stream_duplex": ">= 0.9.4", + "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"], + "_stream_transform": ">= 0.9.4", + "node:_stream_transform": [">= 14.18 && < 15", ">= 16"], + "_stream_wrap": ">= 1.4.1", + "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"], + "_stream_passthrough": ">= 0.9.4", + "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"], + "_stream_readable": ">= 0.9.4", + "node:_stream_readable": [">= 14.18 && < 15", ">= 16"], + "_stream_writable": ">= 0.9.4", + "node:_stream_writable": [">= 14.18 && < 15", ">= 16"], + "stream": true, + "node:stream": [">= 14.18 && < 15", ">= 16"], + "stream/consumers": ">= 16.7", + "node:stream/consumers": ">= 16.7", + "stream/promises": ">= 15", + "node:stream/promises": ">= 16", + "stream/web": ">= 16.5", + "node:stream/web": ">= 16.5", + "string_decoder": true, + "node:string_decoder": [">= 14.18 && < 15", ">= 16"], + "sys": [">= 0.4 && < 0.7", ">= 0.8"], + "node:sys": [">= 14.18 && < 15", ">= 16"], + "test/reporters": ">= 19.9 && < 20.2", + "node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"], + "node:test": [">= 16.17 && < 17", ">= 18"], + "timers": true, + "node:timers": [">= 14.18 && < 15", ">= 16"], + "timers/promises": ">= 15", + "node:timers/promises": ">= 16", + "_tls_common": ">= 0.11.13", + "node:_tls_common": [">= 14.18 && < 15", ">= 16"], + "_tls_legacy": ">= 0.11.3 && < 10", + "_tls_wrap": ">= 0.11.3", + "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"], + "tls": true, + "node:tls": [">= 14.18 && < 15", ">= 16"], + "trace_events": ">= 10", + "node:trace_events": [">= 14.18 && < 15", ">= 16"], + "tty": true, + "node:tty": [">= 14.18 && < 15", ">= 16"], + "url": true, + "node:url": [">= 14.18 && < 15", ">= 16"], + "util": true, + "node:util": [">= 14.18 && < 15", ">= 16"], + "util/types": ">= 15.3", + "node:util/types": ">= 16", + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8": ">= 1", + "node:v8": [">= 14.18 && < 15", ">= 16"], + "vm": true, + "node:vm": [">= 14.18 && < 15", ">= 16"], + "wasi": [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"], + "node:wasi": [">= 18.17 && < 19", ">= 20"], + "worker_threads": ">= 11.7", + "node:worker_threads": [">= 14.18 && < 15", ">= 16"], + "zlib": ">= 0.5", + "node:zlib": [">= 14.18 && < 15", ">= 16"] +} diff --git a/node_modules/is-core-module/index.js b/node_modules/is-core-module/index.js new file mode 100644 index 0000000..f9637e0 --- /dev/null +++ b/node_modules/is-core-module/index.js @@ -0,0 +1,69 @@ +'use strict'; + +var has = require('has'); + +function specifierIncluded(current, specifier) { + var nodeParts = current.split('.'); + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = parseInt(nodeParts[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } + if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; +} + +function matchesRange(current, range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { + return false; + } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(current, specifiers[i])) { + return false; + } + } + return true; +} + +function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } + + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node + : nodeVersion; + + if (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } + + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(current, specifierValue[i])) { + return true; + } + } + return false; + } + return matchesRange(current, specifierValue); +} + +var data = require('./core.json'); + +module.exports = function isCore(x, nodeVersion) { + return has(data, x) && versionIncluded(nodeVersion, data[x]); +}; diff --git a/node_modules/is-core-module/package.json b/node_modules/is-core-module/package.json new file mode 100644 index 0000000..1269c80 --- /dev/null +++ b/node_modules/is-core-module/package.json @@ -0,0 +1,73 @@ +{ + "name": "is-core-module", + "version": "2.13.0", + "description": "Is this specifier a node.js core module?", + "main": "index.js", + "sideEffects": false, + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/is-core-module.git" + }, + "keywords": [ + "core", + "modules", + "module", + "npm", + "node", + "dependencies" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/is-core-module/issues" + }, + "homepage": "https://github.com/inspect-js/is-core-module", + "dependencies": { + "has": "^1.0.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "mock-property": "^1.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "semver": "^6.3.1", + "tape": "^5.6.6" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github" + ] + } +} diff --git a/node_modules/is-core-module/test/index.js b/node_modules/is-core-module/test/index.js new file mode 100644 index 0000000..912808b --- /dev/null +++ b/node_modules/is-core-module/test/index.js @@ -0,0 +1,133 @@ +'use strict'; + +var test = require('tape'); +var keys = require('object-keys'); +var semver = require('semver'); +var mockProperty = require('mock-property'); + +var isCore = require('../'); +var data = require('../core.json'); + +var supportsNodePrefix = semver.satisfies(process.versions.node, '^14.18 || >= 16', { includePrerelease: true }); + +test('core modules', function (t) { + t.test('isCore()', function (st) { + st.ok(isCore('fs')); + st.ok(isCore('net')); + st.ok(isCore('http')); + + st.ok(!isCore('seq')); + st.ok(!isCore('../')); + + st.ok(!isCore('toString')); + + st.end(); + }); + + t.test('core list', function (st) { + var cores = keys(data); + st.plan(cores.length); + + for (var i = 0; i < cores.length; ++i) { + var mod = cores[i]; + var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func + if (isCore(mod)) { + st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw'); + } else { + st['throws'](requireFunc, mod + ' not supported; requiring throws'); + } + } + + st.end(); + }); + + t.test('core via repl module', { skip: !data.repl }, function (st) { + var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle + if (!libs) { + st.skip('repl._builtinLibs does not exist'); + } else { + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + st.ok(data[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + if (mod.slice(0, 5) !== 'node:') { + if (supportsNodePrefix) { + st.doesNotThrow( + function () { require('node:' + mod); }, // eslint-disable-line no-loop-func + 'requiring node:' + mod + ' does not throw' + ); + } else { + st['throws']( + function () { require('node:' + mod); }, // eslint-disable-line no-loop-func + 'requiring node:' + mod + ' throws' + ); + } + } + } + } + st.end(); + }); + + t.test('core via builtinModules list', { skip: !data.module }, function (st) { + var libs = require('module').builtinModules; + if (!libs) { + st.skip('module.builtinModules does not exist'); + } else { + var excludeList = [ + '_debug_agent', + 'v8/tools/tickprocessor-driver', + 'v8/tools/SourceMap', + 'v8/tools/tickprocessor', + 'v8/tools/profile' + ]; + // see https://github.com/nodejs/node/issues/42785 + if (semver.satisfies(process.version, '>= 18')) { + libs = libs.concat('node:test'); + } + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + if (excludeList.indexOf(mod) === -1) { + st.ok(data[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + if (mod.slice(0, 5) !== 'node:') { + if (supportsNodePrefix) { + st.doesNotThrow( + function () { require('node:' + mod); }, // eslint-disable-line no-loop-func + 'requiring node:' + mod + ' does not throw' + ); + } else { + st['throws']( + function () { require('node:' + mod); }, // eslint-disable-line no-loop-func + 'requiring node:' + mod + ' throws' + ); + } + } + } + } + } + st.end(); + }); + + t.test('Object.prototype pollution', function (st) { + var nonKey = 'not a core module'; + st.teardown(mockProperty(Object.prototype, 'fs', { value: false })); + st.teardown(mockProperty(Object.prototype, 'path', { value: '>= 999999999' })); + st.teardown(mockProperty(Object.prototype, 'http', { value: data.http })); + st.teardown(mockProperty(Object.prototype, nonKey, { value: true })); + + st.equal(isCore('fs'), true, 'fs is a core module even if Object.prototype lies'); + st.equal(isCore('path'), true, 'path is a core module even if Object.prototype lies'); + st.equal(isCore('http'), true, 'path is a core module even if Object.prototype matches data'); + st.equal(isCore(nonKey), false, '"' + nonKey + '" is not a core module even if Object.prototype lies'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/is-date-object/.editorconfig b/node_modules/is-date-object/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/is-date-object/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/is-date-object/.eslintignore b/node_modules/is-date-object/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-date-object/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-date-object/.eslintrc b/node_modules/is-date-object/.eslintrc new file mode 100644 index 0000000..1228f97 --- /dev/null +++ b/node_modules/is-date-object/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements": [2, 12] + } +} diff --git a/node_modules/is-date-object/.github/FUNDING.yml b/node_modules/is-date-object/.github/FUNDING.yml new file mode 100644 index 0000000..9cfa9fd --- /dev/null +++ b/node_modules/is-date-object/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-date-object +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-date-object/.nycrc b/node_modules/is-date-object/.nycrc new file mode 100644 index 0000000..a69aa2d --- /dev/null +++ b/node_modules/is-date-object/.nycrc @@ -0,0 +1,10 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test", + "test-corejs.js" + ] +} diff --git a/node_modules/is-date-object/CHANGELOG.md b/node_modules/is-date-object/CHANGELOG.md new file mode 100644 index 0000000..49f624a --- /dev/null +++ b/node_modules/is-date-object/CHANGELOG.md @@ -0,0 +1,114 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.5](https://github.com/inspect-js/is-date-object/compare/v1.0.4...v1.0.5) - 2021-08-05 + +### Commits + +- [meta] remove `.jscs.json` [`31c731c`](https://github.com/inspect-js/is-date-object/commit/31c731c5efc5b1b86e6426d904373dc6225b929f) +- [Fix] use `has-tostringtag` to behave correctly in the presence of symbol shams [`17a6df4`](https://github.com/inspect-js/is-date-object/commit/17a6df4a3ab9bcb1395a638ced14f571f9549427) +- [Dev Deps] update `eslint`, `auto-changelog`, `tape` [`79db3af`](https://github.com/inspect-js/is-date-object/commit/79db3af1a745042a0a11e03c7dd7db910b5e0d01) + +## [v1.0.4](https://github.com/inspect-js/is-date-object/compare/v1.0.3...v1.0.4) - 2021-05-07 + +### Commits + +- [Fix] do not use `Object.prototype.toString` when `Symbol.toStringTag` is shammed [`8943a4a`](https://github.com/inspect-js/is-date-object/commit/8943a4a5035b3f2c8cee9a5edabb55579c16983d) +- [readme] make all URLs https [`1d4d6cd`](https://github.com/inspect-js/is-date-object/commit/1d4d6cd37365c3a36f98e3f82cfe6262227437db) +- [Dev Deps] update `eslint` [`a7abeaa`](https://github.com/inspect-js/is-date-object/commit/a7abeaa2409d3a34fccebcb5b362e0b90d0a8883) + +## [v1.0.3](https://github.com/inspect-js/is-date-object/compare/v1.0.2...v1.0.3) - 2021-05-05 + +### Commits + +- [Tests] migrate tests to Github Actions [`023504f`](https://github.com/inspect-js/is-date-object/commit/023504f4d48fc8788ff52ee525a1d9ec74fa7df5) +- [readme] add actions and codecov badges [`e63305f`](https://github.com/inspect-js/is-date-object/commit/e63305f2fb9ff3eb0dab7e0716585507a4f95a75) +- [meta] do not publish github action workflow files [`017d906`](https://github.com/inspect-js/is-date-object/commit/017d90679b6b1c16b398c0157904f91f56160219) +- [Tests] run `nyc` on all tests [`0376b6f`](https://github.com/inspect-js/is-date-object/commit/0376b6fb7a0ffcc42107c3c579ba0b3ab635b9e4) +- [readme] fix repo URLs; remove defunct badges [`1c148c6`](https://github.com/inspect-js/is-date-object/commit/1c148c6cb6eb0892b3186e814df3367dabb9732d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`c7a3f54`](https://github.com/inspect-js/is-date-object/commit/c7a3f54a207a6056ffafaa58178889ea1b1b77f7) +- [actions] add "Allow Edits" workflow [`e79b5b2`](https://github.com/inspect-js/is-date-object/commit/e79b5b25c173c3201e8b42a614d5f12c48b74a86) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`da28980`](https://github.com/inspect-js/is-date-object/commit/da28980c5fe86528585b2a420319ca8fc35f763a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`5cabae9`](https://github.com/inspect-js/is-date-object/commit/5cabae9f00bf458a470bde68b734540b8ab78c3b) +- [readme] add actions and codecov badges [`33dfb88`](https://github.com/inspect-js/is-date-object/commit/33dfb881b7abf668cd3bf956e2947a1ece552f25) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`745eb04`](https://github.com/inspect-js/is-date-object/commit/745eb0462ef3838df65f41f4a95453cc4f0aa06e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`466c62b`](https://github.com/inspect-js/is-date-object/commit/466c62b45af5a5a83963f6ef8617da887b0ab272) +- [actions] use checkout v2; remove unneeded env [`ff87a16`](https://github.com/inspect-js/is-date-object/commit/ff87a161e36d76d081d70933bf801a357c3b25fe) +- [Dev Deps] update `auto-changelog`, `tape` [`93188f5`](https://github.com/inspect-js/is-date-object/commit/93188f58e4b2c2b5e978a61a45380101d01f9838) +- [meta] use `prepublishOnly` script for npm 7+ [`1d0e3ea`](https://github.com/inspect-js/is-date-object/commit/1d0e3ea672971f02bb48c88b49079789ab41f574) +- [actions] update workflows [`4d1a235`](https://github.com/inspect-js/is-date-object/commit/4d1a2358de35a9fbe23a1dee10735748ed276301) +- [Dev Deps] update `auto-changelog`; add `aud` [`67be59a`](https://github.com/inspect-js/is-date-object/commit/67be59aa3c0ba44b982aaefb7e42adfb14eb279b) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`a6661c2`](https://github.com/inspect-js/is-date-object/commit/a6661c26af701a7782f6e06ad1b34587ce2b09bc) +- [Tests] only audit prod deps [`dd4a47f`](https://github.com/inspect-js/is-date-object/commit/dd4a47f8bcf82c3090826d890a7766f50d6f7af9) + +## [v1.0.2](https://github.com/inspect-js/is-date-object/compare/v1.0.1...v1.0.2) - 2019-12-18 + +### Commits + +- [Tests] use shared travis-ci configs [`8a378b8`](https://github.com/inspect-js/is-date-object/commit/8a378b8fd6a4202fffc9ec193aca02efe937bc35) +- [Tests] on all node minors; use `nvm install-latest-npm`; fix scripts; improve matrix [`6e97a21`](https://github.com/inspect-js/is-date-object/commit/6e97a21276cf448ce424fb9ea13edd4587f289f1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is`, `jscs`, `nsp`, `semver`, `tape` [`8472b90`](https://github.com/inspect-js/is-date-object/commit/8472b90f82e5153c22e7a8a7726a5cc6110e93d7) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`ae73e38`](https://github.com/inspect-js/is-date-object/commit/ae73e3890df7da0bc4449088e30340cb4df3294d) +- [meta] add `auto-changelog` [`82f8f47`](https://github.com/inspect-js/is-date-object/commit/82f8f473a6ee45e2b66810cb743e0122c18381c5) +- [meta] remove unused Makefile and associated utilities [`788a2cd`](https://github.com/inspect-js/is-date-object/commit/788a2cdfd0bc8f1903967219897f6d00c4c6a26b) +- [Tests] up to `node` `v11.4`, `v10.14`, `v8.14`, `v6.15` [`b9caf7c`](https://github.com/inspect-js/is-date-object/commit/b9caf7c814e5e2549454cb444f8b739f9ce1a388) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v8.15`, `v6.17`; use `nvm install-latest-npm` [`cda0abc`](https://github.com/inspect-js/is-date-object/commit/cda0abc04a21c9b5ec72eabd010155c988032056) +- [Tests] up to `node` `v12.10`, `v10.16`, `v8.16` [`49bc482`](https://github.com/inspect-js/is-date-object/commit/49bc482fd9f71436b663c07144083a8423697299) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `semver`, `tape`; add `safe-publish-latest` [`f77fec4`](https://github.com/inspect-js/is-date-object/commit/f77fec48057e156b2276b4c14cf303306116b9f6) +- [actions] add automatic rebasing / merge commit blocking [`68605fc`](https://github.com/inspect-js/is-date-object/commit/68605fcb6bc0341ff0aae14a94bf5d18e1bc73be) +- [meta] create FUNDING.yml [`4f82d88`](https://github.com/inspect-js/is-date-object/commit/4f82d88e1e6ac1b97f0ce96aa0aa057ad758a581) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`3cbf28a`](https://github.com/inspect-js/is-date-object/commit/3cbf28a185ced940cfce8a09fa8479cc83575876) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config@`, `is`, `semver`, `tape` [`abf9fb0`](https://github.com/inspect-js/is-date-object/commit/abf9fb0d55ef0697e64e888d74f2e5fe53d7cdcb) +- [Tests] switch from `nsp` to `npm audit` [`6543c7d`](https://github.com/inspect-js/is-date-object/commit/6543c7d559d1fb79215b46c8b79e0e3e2a83f5de) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`ba5d2d7`](https://github.com/inspect-js/is-date-object/commit/ba5d2d7fc0975d7c03b8f2b7f43a09af93e365ba) +- [Dev Deps] update `eslint`, `nsp`, `semver`, `tape` [`c1e3525`](https://github.com/inspect-js/is-date-object/commit/c1e3525afa76a696f7cf1b58aab7f55d220b2c20) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`14e4824`](https://github.com/inspect-js/is-date-object/commit/14e4824188c85207ed3b86627b09e9f64b135db7) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` [`68ead64`](https://github.com/inspect-js/is-date-object/commit/68ead64a07e0de282ea3cd38e12cc8b0e0f6d3cd) +- [Dev Deps] update `eslint`, semver`, `tape`, `semver` [`f55453f`](https://github.com/inspect-js/is-date-object/commit/f55453f200903277465d7e9307a9c49120a4f419) +- Only apps should have lockfiles [`6c848eb`](https://github.com/inspect-js/is-date-object/commit/6c848eba982cc58053d4cca08c01f12a433f3695) +- [Tests] remove `jscs` [`3fd3a62`](https://github.com/inspect-js/is-date-object/commit/3fd3a62121607ad074b7fc977f3fc6575b66f755) +- [Dev Deps] update `eslint`, `tape` [`77d3130`](https://github.com/inspect-js/is-date-object/commit/77d3130a0039e5dae24c17de790dd510c265edc6) +- [meta] add `funding` field [`9ef6d58`](https://github.com/inspect-js/is-date-object/commit/9ef6d5888bf829a5812b3b091dc99839d48c355e) + +## [v1.0.1](https://github.com/inspect-js/is-date-object/compare/v1.0.0...v1.0.1) - 2015-09-27 + +### Commits + +- Update `tape`, `semver`, `eslint`; use my personal shared `eslint` config. [`731aa13`](https://github.com/inspect-js/is-date-object/commit/731aa134b0b8dc84e302d0b2264a415cb456ccab) +- Update `is`, `tape`, `covert`, `jscs`, `editorconfig-tools`, `nsp`, `eslint`, `semver` [`53e43a6`](https://github.com/inspect-js/is-date-object/commit/53e43a627dd01757cf3d469599f3dffd9d72b150) +- Update `eslint` [`d2fc304`](https://github.com/inspect-js/is-date-object/commit/d2fc3046f087b0026448ffde0cf46b1f741cbd4e) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`c9568df`](https://github.com/inspect-js/is-date-object/commit/c9568df228fa698dc6fcc9553b5d612e7ee427aa) +- Test on latest `node` and `io.js` versions. [`a21d537`](https://github.com/inspect-js/is-date-object/commit/a21d537562166ebd18bde3a262fd157dd774ae17) +- Update `nsp`, `eslint`, `semver` [`9e1d908`](https://github.com/inspect-js/is-date-object/commit/9e1d9087c0c79c34fcb2abfc701cdfa1efcb327c) +- Update `covert`, `jscs`, `eslint`, `semver` [`f198f6b`](https://github.com/inspect-js/is-date-object/commit/f198f6b997912da10a3d821a089e1581edc730a0) +- [Dev Deps] update `tape`, `jscs`, `eslint` [`ab9bdbb`](https://github.com/inspect-js/is-date-object/commit/ab9bdbbc189cef033346508db47cd1feb04a69d3) +- If `@@toStringTag` is not present, use the old-school `Object#toString` test. [`c03afce`](https://github.com/inspect-js/is-date-object/commit/c03afce001368b29eb929900075749b113a252c8) +- [Dev Deps] update `jscs`, `nsp`, `tape`, `eslint`, `@ljharb/eslint-config` [`9d94ccb`](https://github.com/inspect-js/is-date-object/commit/9d94ccbab4160d2fa649123e37951d86b69a8b15) +- [Dev Deps] update `is`, `eslint`, `@ljharb/eslint-config`, `semver` [`35cbff7`](https://github.com/inspect-js/is-date-object/commit/35cbff7f7c8216fbb79c799f74b2336eaf0d726a) +- Test up to `io.js` `v2.3` [`be5d11e`](https://github.com/inspect-js/is-date-object/commit/be5d11e7ebd9473d7ae554179b3769082485f6f4) +- [Tests] on `io.js` `v3.3`, up to `node` `v4.1` [`20221a3`](https://github.com/inspect-js/is-date-object/commit/20221a34858d2b21e23bdc2c08df23f0bc08d11e) +- [Tests] up to `io.js` `v3.2 ` [`7009b4a`](https://github.com/inspect-js/is-date-object/commit/7009b4a9999e14eacbdf6068afd82f478473f007) +- Test on `io.js` `v2.1` [`68b29b1`](https://github.com/inspect-js/is-date-object/commit/68b29b19a07e6589a7ca37ab764be28f144ac88e) +- Remove `editorconfig-tools` [`8d3972c`](https://github.com/inspect-js/is-date-object/commit/8d3972c1795fdcfd337680e11ab610e4885fb079) +- [Dev Deps] update `tape` [`204945d`](https://github.com/inspect-js/is-date-object/commit/204945d8658a3513ca6315ddf795e4034adb4545) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`7bff214`](https://github.com/inspect-js/is-date-object/commit/7bff214dcb2317b96219921476f990814afbb401) +- Test on `io.js` `v2.5` [`92f7bd6`](https://github.com/inspect-js/is-date-object/commit/92f7bd6747e3259b0ddc9c287876f46a9cd4c270) +- Test on `io.js` `v2.4` [`ebb34bf`](https://github.com/inspect-js/is-date-object/commit/ebb34bf1f58949768063f86ac012f1ca5d7cf6d9) +- Fix tests for faked @@toStringTag [`3b9c26c`](https://github.com/inspect-js/is-date-object/commit/3b9c26c15040af6a87f8d77ce6c85a7bef7a4304) +- Test on `io.js` `v3.0` [`5eedf4b`](https://github.com/inspect-js/is-date-object/commit/5eedf4bea76380a08813fd0977469c2480302a82) + +## v1.0.0 - 2015-01-28 + +### Commits + +- Dotfiles. [`5b6a929`](https://github.com/inspect-js/is-date-object/commit/5b6a9298c6f70882e78e66d64c9c019f85790f52) +- `make release` [`e8d40ce`](https://github.com/inspect-js/is-date-object/commit/e8d40ceca85acd0aa4b2753faa6e41c0c54cf6c3) +- package.json [`a107259`](https://github.com/inspect-js/is-date-object/commit/a1072591ea510a2998298be6cef827b123f4643f) +- Read me [`eb92695`](https://github.com/inspect-js/is-date-object/commit/eb92695664bdee8fc49891cd73aa2f41075f53cb) +- Initial commit [`4fc7755`](https://github.com/inspect-js/is-date-object/commit/4fc7755ff12f1d7a55cf841d486bf6b2350fe5a0) +- Tests. [`b6f432f`](https://github.com/inspect-js/is-date-object/commit/b6f432fb6801c5ff8d89cfec7601d59478e23dd1) +- Implementation. [`dd0fd96`](https://github.com/inspect-js/is-date-object/commit/dd0fd96c4016a66cec7cd59db0fde37c2ef3cdb5) diff --git a/node_modules/is-date-object/LICENSE b/node_modules/is-date-object/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/node_modules/is-date-object/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/is-date-object/README.md b/node_modules/is-date-object/README.md new file mode 100644 index 0000000..1c084ad --- /dev/null +++ b/node_modules/is-date-object/README.md @@ -0,0 +1,52 @@ +# is-date-object [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag. + +## Example + +```js +var isDate = require('is-date-object'); +var assert = require('assert'); + +assert.notOk(isDate(undefined)); +assert.notOk(isDate(null)); +assert.notOk(isDate(false)); +assert.notOk(isDate(true)); +assert.notOk(isDate(42)); +assert.notOk(isDate('foo')); +assert.notOk(isDate(function () {})); +assert.notOk(isDate([])); +assert.notOk(isDate({})); +assert.notOk(isDate(/a/g)); +assert.notOk(isDate(new RegExp('a', 'g'))); + +assert.ok(isDate(new Date())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-date-object +[2]: https://versionbadg.es/inspect-js/is-date-object.svg +[5]: https://david-dm.org/inspect-js/is-date-object.svg +[6]: https://david-dm.org/inspect-js/is-date-object +[7]: https://david-dm.org/inspect-js/is-date-object/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-date-object#info=devDependencies +[11]: https://nodei.co/npm/is-date-object.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-date-object.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-date-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-date-object +[codecov-image]: https://codecov.io/gh/inspect-js/is-date-object/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-date-object/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-date-object +[actions-url]: https://github.com/inspect-js/is-date-object/actions diff --git a/node_modules/is-date-object/index.js b/node_modules/is-date-object/index.js new file mode 100644 index 0000000..11628f3 --- /dev/null +++ b/node_modules/is-date-object/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var getDay = Date.prototype.getDay; +var tryDateObject = function tryDateGetDayCall(value) { + try { + getDay.call(value); + return true; + } catch (e) { + return false; + } +}; + +var toStr = Object.prototype.toString; +var dateClass = '[object Date]'; +var hasToStringTag = require('has-tostringtag/shams')(); + +module.exports = function isDateObject(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; +}; diff --git a/node_modules/is-date-object/package.json b/node_modules/is-date-object/package.json new file mode 100644 index 0000000..7b32ed8 --- /dev/null +++ b/node_modules/is-date-object/package.json @@ -0,0 +1,79 @@ +{ + "name": "is-date-object", + "version": "1.0.5", + "author": "Jordan Harband", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only && npm run test:corejs", + "tests-only": "nyc tape 'test/**/*.js'", + "test:corejs": "nyc tape test-corejs.js", + "posttest": "aud --production", + "lint": "eslint .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-date-object.git" + }, + "keywords": [ + "Date", + "ES6", + "toStringTag", + "@@toStringTag", + "Date object" + ], + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "core-js": "^3.12.0", + "eslint": "^7.32.0", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/is-date-object/test/index.js b/node_modules/is-date-object/test/index.js new file mode 100644 index 0000000..5279dad --- /dev/null +++ b/node_modules/is-date-object/test/index.js @@ -0,0 +1,36 @@ +'use strict'; + +var test = require('tape'); +var isDate = require('../'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('not Dates', function (t) { + t.notOk(isDate(), 'undefined is not Date'); + t.notOk(isDate(null), 'null is not Date'); + t.notOk(isDate(false), 'false is not Date'); + t.notOk(isDate(true), 'true is not Date'); + t.notOk(isDate(42), 'number is not Date'); + t.notOk(isDate('foo'), 'string is not Date'); + t.notOk(isDate([]), 'array is not Date'); + t.notOk(isDate({}), 'object is not Date'); + t.notOk(isDate(function () {}), 'function is not Date'); + t.notOk(isDate(/a/g), 'regex literal is not Date'); + t.notOk(isDate(new RegExp('a', 'g')), 'regex object is not Date'); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + var realDate = new Date(); + var fakeDate = { + toString: function () { return String(realDate); }, + valueOf: function () { return realDate.getTime(); } + }; + fakeDate[Symbol.toStringTag] = 'Date'; + t.notOk(isDate(fakeDate), 'fake Date with @@toStringTag "Date" is not Date'); + t.end(); +}); + +test('Dates', function (t) { + t.ok(isDate(new Date()), 'new Date() is Date'); + t.end(); +}); diff --git a/node_modules/is-docker/cli.js b/node_modules/is-docker/cli.js new file mode 100755 index 0000000..58f2861 --- /dev/null +++ b/node_modules/is-docker/cli.js @@ -0,0 +1,5 @@ +#!/usr/bin/env node +'use strict'; +const isDocker = require('.'); + +process.exitCode = isDocker() ? 0 : 2; diff --git a/node_modules/is-docker/index.d.ts b/node_modules/is-docker/index.d.ts new file mode 100644 index 0000000..c801881 --- /dev/null +++ b/node_modules/is-docker/index.d.ts @@ -0,0 +1,15 @@ +/** +Check if the process is running inside a Docker container. + +@example +``` +import isDocker = require('is-docker'); + +if (isDocker()) { + console.log('Running inside a Docker container'); +} +``` +*/ +declare function isDocker(): boolean; + +export = isDocker; diff --git a/node_modules/is-docker/index.js b/node_modules/is-docker/index.js new file mode 100644 index 0000000..cbb7b6f --- /dev/null +++ b/node_modules/is-docker/index.js @@ -0,0 +1,29 @@ +'use strict'; +const fs = require('fs'); + +let isDocker; + +function hasDockerEnv() { + try { + fs.statSync('/.dockerenv'); + return true; + } catch (_) { + return false; + } +} + +function hasDockerCGroup() { + try { + return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); + } catch (_) { + return false; + } +} + +module.exports = () => { + if (isDocker === undefined) { + isDocker = hasDockerEnv() || hasDockerCGroup(); + } + + return isDocker; +}; diff --git a/node_modules/is-docker/license b/node_modules/is-docker/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/is-docker/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-docker/package.json b/node_modules/is-docker/package.json new file mode 100644 index 0000000..ae28225 --- /dev/null +++ b/node_modules/is-docker/package.json @@ -0,0 +1,42 @@ +{ + "name": "is-docker", + "version": "2.2.1", + "description": "Check if the process is running inside a Docker container", + "license": "MIT", + "repository": "sindresorhus/is-docker", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bin": "cli.js", + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "cli.js" + ], + "keywords": [ + "detect", + "docker", + "dockerized", + "container", + "inside", + "is", + "env", + "environment", + "process" + ], + "devDependencies": { + "ava": "^1.4.1", + "sinon": "^7.3.2", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-docker/readme.md b/node_modules/is-docker/readme.md new file mode 100644 index 0000000..f09b254 --- /dev/null +++ b/node_modules/is-docker/readme.md @@ -0,0 +1,27 @@ +# is-docker + +> Check if the process is running inside a Docker container + +## Install + +``` +$ npm install is-docker +``` + +## Usage + +```js +const isDocker = require('is-docker'); + +if (isDocker()) { + console.log('Running inside a Docker container'); +} +``` + +## CLI + +``` +$ is-docker +``` + +Exits with code 0 if inside a Docker container and 2 if not. diff --git a/node_modules/is-extglob/LICENSE b/node_modules/is-extglob/LICENSE new file mode 100644 index 0000000..842218c --- /dev/null +++ b/node_modules/is-extglob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2016, Jon Schlinkert + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-extglob/README.md b/node_modules/is-extglob/README.md new file mode 100644 index 0000000..0416af5 --- /dev/null +++ b/node_modules/is-extglob/README.md @@ -0,0 +1,107 @@ +# is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) + +> Returns true if a string has an extglob. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-extglob +``` + +## Usage + +```js +var isExtglob = require('is-extglob'); +``` + +**True** + +```js +isExtglob('?(abc)'); +isExtglob('@(abc)'); +isExtglob('!(abc)'); +isExtglob('*(abc)'); +isExtglob('+(abc)'); +``` + +**False** + +Escaped extglobs: + +```js +isExtglob('\\?(abc)'); +isExtglob('\\@(abc)'); +isExtglob('\\!(abc)'); +isExtglob('\\*(abc)'); +isExtglob('\\+(abc)'); +``` + +Everything else... + +```js +isExtglob('foo.js'); +isExtglob('!foo.js'); +isExtglob('*.js'); +isExtglob('**/abc.js'); +isExtglob('abc/*.js'); +isExtglob('abc/(aaa|bbb).js'); +isExtglob('abc/[a-z].js'); +isExtglob('abc/{a,b}.js'); +isExtglob('abc/?.js'); +isExtglob('abc.js'); +isExtglob('abc/def/ghi.js'); +``` + +## History + +**v2.0** + +Adds support for escaping. Escaped exglobs no longer return true. + +## About + +### Related projects + +* [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") +* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") + +### Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +### Building docs + +_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ + +To generate the readme and API documentation with [verb](https://github.com/verbose/verb): + +```sh +$ npm install -g verb verb-generate-readme && verb +``` + +### Running tests + +Install dev dependencies: + +```sh +$ npm install -d && npm test +``` + +### Author + +**Jon Schlinkert** + +* [github/jonschlinkert](https://github.com/jonschlinkert) +* [twitter/jonschlinkert](http://twitter.com/jonschlinkert) + +### License + +Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ \ No newline at end of file diff --git a/node_modules/is-extglob/index.js b/node_modules/is-extglob/index.js new file mode 100644 index 0000000..c1d986f --- /dev/null +++ b/node_modules/is-extglob/index.js @@ -0,0 +1,20 @@ +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +module.exports = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; diff --git a/node_modules/is-extglob/package.json b/node_modules/is-extglob/package.json new file mode 100644 index 0000000..7a90836 --- /dev/null +++ b/node_modules/is-extglob/package.json @@ -0,0 +1,69 @@ +{ + "name": "is-extglob", + "description": "Returns true if a string has an extglob.", + "version": "2.1.1", + "homepage": "https://github.com/jonschlinkert/is-extglob", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/is-extglob", + "bugs": { + "url": "https://github.com/jonschlinkert/is-extglob/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "has-glob", + "is-glob", + "micromatch" + ] + }, + "reflinks": [ + "verb", + "verb-generate-readme" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/is-fullwidth-code-point/index.d.ts b/node_modules/is-fullwidth-code-point/index.d.ts new file mode 100644 index 0000000..729d202 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/index.d.ts @@ -0,0 +1,17 @@ +/** +Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms). + +@param codePoint - The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. + +@example +``` +import isFullwidthCodePoint from 'is-fullwidth-code-point'; + +isFullwidthCodePoint('谢'.codePointAt(0)); +//=> true + +isFullwidthCodePoint('a'.codePointAt(0)); +//=> false +``` +*/ +export default function isFullwidthCodePoint(codePoint: number): boolean; diff --git a/node_modules/is-fullwidth-code-point/index.js b/node_modules/is-fullwidth-code-point/index.js new file mode 100644 index 0000000..671f97f --- /dev/null +++ b/node_modules/is-fullwidth-code-point/index.js @@ -0,0 +1,50 @@ +/* eslint-disable yoda */ +'use strict'; + +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } + + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } + + return false; +}; + +module.exports = isFullwidthCodePoint; +module.exports.default = isFullwidthCodePoint; diff --git a/node_modules/is-fullwidth-code-point/license b/node_modules/is-fullwidth-code-point/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-fullwidth-code-point/package.json b/node_modules/is-fullwidth-code-point/package.json new file mode 100644 index 0000000..2137e88 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/package.json @@ -0,0 +1,42 @@ +{ + "name": "is-fullwidth-code-point", + "version": "3.0.0", + "description": "Check if the character represented by a given Unicode code point is fullwidth", + "license": "MIT", + "repository": "sindresorhus/is-fullwidth-code-point", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "fullwidth", + "full-width", + "full", + "width", + "unicode", + "character", + "string", + "codepoint", + "code", + "point", + "is", + "detect", + "check" + ], + "devDependencies": { + "ava": "^1.3.1", + "tsd-check": "^0.5.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-fullwidth-code-point/readme.md b/node_modules/is-fullwidth-code-point/readme.md new file mode 100644 index 0000000..4236bba --- /dev/null +++ b/node_modules/is-fullwidth-code-point/readme.md @@ -0,0 +1,39 @@ +# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) + +> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) + + +## Install + +``` +$ npm install is-fullwidth-code-point +``` + + +## Usage + +```js +const isFullwidthCodePoint = require('is-fullwidth-code-point'); + +isFullwidthCodePoint('谢'.codePointAt(0)); +//=> true + +isFullwidthCodePoint('a'.codePointAt(0)); +//=> false +``` + + +## API + +### isFullwidthCodePoint(codePoint) + +#### codePoint + +Type: `number` + +The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/is-generator-fn/index.d.ts b/node_modules/is-generator-fn/index.d.ts new file mode 100644 index 0000000..7eabf62 --- /dev/null +++ b/node_modules/is-generator-fn/index.d.ts @@ -0,0 +1,24 @@ +declare const isGeneratorFn: { + /** + Check if something is a generator function. + + @example + ``` + import isGeneratorFn = require('is-generator-fn'); + + isGeneratorFn(function * () {}); + //=> true + + isGeneratorFn(function () {}); + //=> false + ``` + */ + (value: unknown): value is GeneratorFunction; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function isGeneratorFn(value: unknown): value is GeneratorFunction; + // export = isGeneratorFn; + default: typeof isGeneratorFn; +}; + +export = isGeneratorFn; diff --git a/node_modules/is-generator-fn/index.js b/node_modules/is-generator-fn/index.js new file mode 100644 index 0000000..d50f6cf --- /dev/null +++ b/node_modules/is-generator-fn/index.js @@ -0,0 +1,14 @@ +'use strict'; +const {toString} = Object.prototype; + +module.exports = value => { + if (typeof value !== 'function') { + return false; + } + + return (value.constructor && value.constructor.name === 'GeneratorFunction') || + toString.call(value) === '[object GeneratorFunction]'; +}; + +// TODO: Remove this for the next major release +module.exports.default = module.exports; diff --git a/node_modules/is-generator-fn/license b/node_modules/is-generator-fn/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-generator-fn/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-generator-fn/package.json b/node_modules/is-generator-fn/package.json new file mode 100644 index 0000000..65e319e --- /dev/null +++ b/node_modules/is-generator-fn/package.json @@ -0,0 +1,38 @@ +{ + "name": "is-generator-fn", + "version": "2.1.0", + "description": "Check if something is a generator function", + "license": "MIT", + "repository": "sindresorhus/is-generator-fn", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "generator", + "function", + "func", + "fn", + "is", + "check", + "detect", + "yield", + "type" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-generator-fn/readme.md b/node_modules/is-generator-fn/readme.md new file mode 100644 index 0000000..654c2af --- /dev/null +++ b/node_modules/is-generator-fn/readme.md @@ -0,0 +1,33 @@ +# is-generator-fn [![Build Status](https://travis-ci.org/sindresorhus/is-generator-fn.svg?branch=master)](https://travis-ci.org/sindresorhus/is-generator-fn) + +> Check if something is a [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) + + +## Install + +``` +$ npm install is-generator-fn +``` + + +## Usage + +```js +const isGeneratorFn = require('is-generator-fn'); + +isGeneratorFn(function * () {}); +//=> true + +isGeneratorFn(function () {}); +//=> false +``` + + +## Related + +- [is](https://github.com/sindresorhus/is) - Type check values + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/is-glob/LICENSE b/node_modules/is-glob/LICENSE new file mode 100644 index 0000000..3f2eca1 --- /dev/null +++ b/node_modules/is-glob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-glob/README.md b/node_modules/is-glob/README.md new file mode 100644 index 0000000..740724b --- /dev/null +++ b/node_modules/is-glob/README.md @@ -0,0 +1,206 @@ +# is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) + +> Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-glob +``` + +You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). + +## Usage + +```js +var isGlob = require('is-glob'); +``` + +### Default behavior + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js'); +isGlob('*.js'); +isGlob('**/abc.js'); +isGlob('abc/*.js'); +isGlob('abc/(aaa|bbb).js'); +isGlob('abc/[a-z].js'); +isGlob('abc/{a,b}.js'); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js'); +isGlob('abc/!(a).js'); +isGlob('abc/+(a).js'); +isGlob('abc/*(a).js'); +isGlob('abc/?(a).js'); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('abc/\\@(a).js'); +isGlob('abc/\\!(a).js'); +isGlob('abc/\\+(a).js'); +isGlob('abc/\\*(a).js'); +isGlob('abc/\\?(a).js'); +isGlob('\\!foo.js'); +isGlob('\\*.js'); +isGlob('\\*\\*/abc.js'); +isGlob('abc/\\*.js'); +isGlob('abc/\\(aaa|bbb).js'); +isGlob('abc/\\[a-z].js'); +isGlob('abc/\\{a,b}.js'); +//=> false +``` + +Patterns that do not have glob patterns return `false`: + +```js +isGlob('abc.js'); +isGlob('abc/def/ghi.js'); +isGlob('foo.js'); +isGlob('abc/@.js'); +isGlob('abc/+.js'); +isGlob('abc/?.js'); +isGlob(); +isGlob(null); +//=> false +``` + +Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): + +```js +isGlob(['**/*.js']); +isGlob(['foo.js']); +//=> false +``` + +### Option strict + +When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that +some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js', {strict: false}); +isGlob('*.js', {strict: false}); +isGlob('**/abc.js', {strict: false}); +isGlob('abc/*.js', {strict: false}); +isGlob('abc/(aaa|bbb).js', {strict: false}); +isGlob('abc/[a-z].js', {strict: false}); +isGlob('abc/{a,b}.js', {strict: false}); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js', {strict: false}); +isGlob('abc/!(a).js', {strict: false}); +isGlob('abc/+(a).js', {strict: false}); +isGlob('abc/*(a).js', {strict: false}); +isGlob('abc/?(a).js', {strict: false}); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('\\!foo.js', {strict: false}); +isGlob('\\*.js', {strict: false}); +isGlob('\\*\\*/abc.js', {strict: false}); +isGlob('abc/\\*.js', {strict: false}); +isGlob('abc/\\(aaa|bbb).js', {strict: false}); +isGlob('abc/\\[a-z].js', {strict: false}); +isGlob('abc/\\{a,b}.js', {strict: false}); +//=> false +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +* [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") +* [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") +* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 47 | [jonschlinkert](https://github.com/jonschlinkert) | +| 5 | [doowb](https://github.com/doowb) | +| 1 | [phated](https://github.com/phated) | +| 1 | [danhper](https://github.com/danhper) | +| 1 | [paulmillr](https://github.com/paulmillr) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ \ No newline at end of file diff --git a/node_modules/is-glob/index.js b/node_modules/is-glob/index.js new file mode 100644 index 0000000..620f563 --- /dev/null +++ b/node_modules/is-glob/index.js @@ -0,0 +1,150 @@ +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = require('is-extglob'); +var chars = { '{': '}', '(': ')', '[': ']'}; +var strictCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + var pipeIndex = -2; + var closeSquareIndex = -2; + var closeCurlyIndex = -2; + var closeParenIndex = -2; + var backSlashIndex = -2; + while (index < str.length) { + if (str[index] === '*') { + return true; + } + + if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { + return true; + } + + if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { + if (closeSquareIndex < index) { + closeSquareIndex = str.indexOf(']', index); + } + if (closeSquareIndex > index) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + } + } + + if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { + closeCurlyIndex = str.indexOf('}', index); + if (closeCurlyIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { + return true; + } + } + } + + if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { + closeParenIndex = str.indexOf(')', index); + if (closeParenIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + + if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { + if (pipeIndex < index) { + pipeIndex = str.indexOf('|', index); + } + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { + closeParenIndex = str.indexOf(')', pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf('\\', pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var relaxedCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + while (index < str.length) { + if (/[*?{}()[\]]/.test(str[index])) { + return true; + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +module.exports = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var check = strictCheck; + + // optionally relax check + if (options && options.strict === false) { + check = relaxedCheck; + } + + return check(str); +}; diff --git a/node_modules/is-glob/package.json b/node_modules/is-glob/package.json new file mode 100644 index 0000000..858af03 --- /dev/null +++ b/node_modules/is-glob/package.json @@ -0,0 +1,81 @@ +{ + "name": "is-glob", + "description": "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.", + "version": "4.0.3", + "homepage": "https://github.com/micromatch/is-glob", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Brian Woodward (https://twitter.com/doowb)", + "Daniel Perez (https://tuvistavie.com)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "micromatch/is-glob", + "bugs": { + "url": "https://github.com/micromatch/is-glob/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha && node benchmark.js" + }, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "verb": { + "layout": "default", + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "assemble", + "base", + "update", + "verb" + ] + }, + "reflinks": [ + "assemble", + "bach", + "base", + "composer", + "gulp", + "has-glob", + "is-valid-glob", + "micromatch", + "npm", + "scaffold", + "verb", + "vinyl" + ] + } +} diff --git a/node_modules/is-negative-zero/.editorconfig b/node_modules/is-negative-zero/.editorconfig new file mode 100644 index 0000000..aaac325 --- /dev/null +++ b/node_modules/is-negative-zero/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +indent_style = tab +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/node_modules/is-negative-zero/.eslintignore b/node_modules/is-negative-zero/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-negative-zero/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-negative-zero/.eslintrc b/node_modules/is-negative-zero/.eslintrc new file mode 100644 index 0000000..f858c0a --- /dev/null +++ b/node_modules/is-negative-zero/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "no-magic-numbers": 0 + } +} diff --git a/node_modules/is-negative-zero/.github/FUNDING.yml b/node_modules/is-negative-zero/.github/FUNDING.yml new file mode 100644 index 0000000..e34502b --- /dev/null +++ b/node_modules/is-negative-zero/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: ljharb +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-negative-zero +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-negative-zero/.nycrc b/node_modules/is-negative-zero/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-negative-zero/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-negative-zero/CHANGELOG.md b/node_modules/is-negative-zero/CHANGELOG.md new file mode 100644 index 0000000..d00e726 --- /dev/null +++ b/node_modules/is-negative-zero/CHANGELOG.md @@ -0,0 +1,136 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.2](https://github.com/inspect-js/is-negative-zero/compare/v2.0.1...v2.0.2) - 2021-12-10 + +### Commits + +- [actions] reuse common workflows [`ece923d`](https://github.com/inspect-js/is-negative-zero/commit/ece923d6b50820b7832150957774047da43d1743) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`3a26f43`](https://github.com/inspect-js/is-negative-zero/commit/3a26f435434bbfb8a254ddd32d6079bf50263121) +- [meta] do not publish workflow files [`2cea0c2`](https://github.com/inspect-js/is-negative-zero/commit/2cea0c20c7f8b167bb6064f916f3285642bf5ab1) +- [readme] add github actions/codecov badges; update URLs [`0c0be3e`](https://github.com/inspect-js/is-negative-zero/commit/0c0be3eb148ccf9d764e8ed515ef0e1d0ffeed9d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`a93d16e`](https://github.com/inspect-js/is-negative-zero/commit/a93d16eddf46cad6bc9b71a92968ce758e6f4ea4) +- [meta] create FUNDING.yml [`b4f425e`](https://github.com/inspect-js/is-negative-zero/commit/b4f425e49edb8c4aa1efa6ba34c2d5c1150b2a26) +- [actions] update codecov uploader [`7999db3`](https://github.com/inspect-js/is-negative-zero/commit/7999db3bff3f0f9cc729529940b9077a586822e2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `safe-publish-latest`, `tape` [`140e4d9`](https://github.com/inspect-js/is-negative-zero/commit/140e4d95eda9ad821608c28a5f705d84a906096d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`23a8b6d`](https://github.com/inspect-js/is-negative-zero/commit/23a8b6d257cea0b8a608b2319739562ecbc6ba75) +- [readme] add actions and codecov badges [`fe92126`](https://github.com/inspect-js/is-negative-zero/commit/fe9212634346ced7a45905d958cb85d129e4c10b) +- [readme] fix repo URLs [`50c428e`](https://github.com/inspect-js/is-negative-zero/commit/50c428e423e5861a6c231440b8b3e746cbf6230f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`688155f`](https://github.com/inspect-js/is-negative-zero/commit/688155ff0214da72cbafa4c438c3b9629265d82b) +- [meta] use `prepublishOnly` script for npm 7+ [`83171f9`](https://github.com/inspect-js/is-negative-zero/commit/83171f9131aed266f475d7a3283d9c2fc77e1436) +- [actions] update workflows [`e9823db`](https://github.com/inspect-js/is-negative-zero/commit/e9823db3054887d8bb5b3f2c8f698b93cdce7d82) + +## [v2.0.1](https://github.com/inspect-js/is-negative-zero/compare/v2.0.0...v2.0.1) - 2020-12-04 + +### Commits + +- [Tests] use shared travis-ci configs [`5b92482`](https://github.com/inspect-js/is-negative-zero/commit/5b92482ed26e55e1aafcc6b6310d279958af8204) +- [Tests] up to `node` `v11.7`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.16`, `v5.12`, `v4.9`; use `nvm install-latest-npm`; fix test scripts [`0f5d2f8`](https://github.com/inspect-js/is-negative-zero/commit/0f5d2f85ea7fe83de47f39b6b35e489b866d88a7) +- [Tests] migrate tests to Github Actions [`b80f05a`](https://github.com/inspect-js/is-negative-zero/commit/b80f05adb11a6a3232860fb50272b101aacb504f) +- [Tests] remove `jscs` [`7ccaf41`](https://github.com/inspect-js/is-negative-zero/commit/7ccaf4100281b614d61d7c9122e6f87943a89295) +- [meta] add missing changelog [`992bdde`](https://github.com/inspect-js/is-negative-zero/commit/992bddee362cbae71f2cdfd8666f4774b252412e) +- [readme] fix repo URLs; remove defunct badges [`80fd18d`](https://github.com/inspect-js/is-negative-zero/commit/80fd18d2b0191321afe0e1b572200e4c025eb664) +- [Tests] run `nyc` on all tests [`df26f14`](https://github.com/inspect-js/is-negative-zero/commit/df26f14b0b854d82b0d3ca7b4949811c9f151357) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`d7723aa`](https://github.com/inspect-js/is-negative-zero/commit/d7723aa70e5b478adc36d98e1338abe741c1906a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`9fdaabe`](https://github.com/inspect-js/is-negative-zero/commit/9fdaabecfdb25e6e860e5007a91b60ee0f20734f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`f07eeb2`](https://github.com/inspect-js/is-negative-zero/commit/f07eeb2740037c53f270e95d2f62edc051cafc56) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`bd5c751`](https://github.com/inspect-js/is-negative-zero/commit/bd5c751fa4850ba8726dc1c197ed6c843a227b05) +- [actions] add automatic rebasing / merge commit blocking [`5666a91`](https://github.com/inspect-js/is-negative-zero/commit/5666a917db6bdcee63c0a3e28e5e281359975abc) +- [meta] add `auto-changelog` [`f70fb2b`](https://github.com/inspect-js/is-negative-zero/commit/f70fb2b5b9ea53dc52729310717553648292189e) +- [actions] add "Allow Edits" workflow [`2b040a8`](https://github.com/inspect-js/is-negative-zero/commit/2b040a87d362f17d8cab2b0d48058b80e426ad4e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`; add `safe-publish-latest` [`09e2e53`](https://github.com/inspect-js/is-negative-zero/commit/09e2e537390225c1d1a6912be64267eaec6ea367) +- [Tests] use `npm audit` instead of `nsp` [`7df2669`](https://github.com/inspect-js/is-negative-zero/commit/7df2669013ac9328d424e9d8c82a53a0458f0888) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`4ff97c5`](https://github.com/inspect-js/is-negative-zero/commit/4ff97c5891c7a241a91c03fb54bd83e78570ef22) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`9e8cb7b`](https://github.com/inspect-js/is-negative-zero/commit/9e8cb7bca46d325ecf202187c0fde7da8722bcab) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`, `nsp` [`70b9888`](https://github.com/inspect-js/is-negative-zero/commit/70b988802a99c84ab7eb8da287bb8ff0efc5c055) +- [Dev Deps] update `jscs` [`59d0c42`](https://github.com/inspect-js/is-negative-zero/commit/59d0c42131020b74e68fd444798b9a3bf247fb2d) +- Add `npm run security` [`eb418ed`](https://github.com/inspect-js/is-negative-zero/commit/eb418ed7e79216808c206388fbd360cc7a75655f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`86a758d`](https://github.com/inspect-js/is-negative-zero/commit/86a758d42eb7d17a18f7f584c337d8820b842758) +- Only apps should have lockfiles [`a0ab621`](https://github.com/inspect-js/is-negative-zero/commit/a0ab6215590bf6adb3eaf1ff9e7c036d72e807ec) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`5c51349`](https://github.com/inspect-js/is-negative-zero/commit/5c513498fc5a8b2fd06f5e0c1b38b8e93c3477ac) +- [meta] add `funding` field [`1d0b2f4`](https://github.com/inspect-js/is-negative-zero/commit/1d0b2f43bf5bf75176859a440346b3e338ee510e) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`9b12367`](https://github.com/inspect-js/is-negative-zero/commit/9b12367706f1c269a3df406c8e2c211558671a15) +- [Dev Deps] update `auto-changelog`, `tape` [`6d98b8d`](https://github.com/inspect-js/is-negative-zero/commit/6d98b8d1f512c3844d4062215c793070084d1164) +- [Dev Deps] Update `tape`, `eslint` [`a258cdb`](https://github.com/inspect-js/is-negative-zero/commit/a258cdb86691725482d1d43a1f9e7953c3c6733f) +- [Dev Deps] update `auto-changelog`; add `aud` [`2ca2afb`](https://github.com/inspect-js/is-negative-zero/commit/2ca2afb9efef4ebc8b3c19046ab1ab3ad516ea9a) +- Test up to `io.js` `v3.0` [`1254ae8`](https://github.com/inspect-js/is-negative-zero/commit/1254ae80b7706616331ac914654d7a17bff31039) +- [Dev Deps] update `auto-changelog` [`4b54722`](https://github.com/inspect-js/is-negative-zero/commit/4b547228fceaae8f9eccabc9ad8a49046492348d) +- [Tests] only audit prod deps [`86d298b`](https://github.com/inspect-js/is-negative-zero/commit/86d298b56db90f81617ee5d942476eda34afb374) +- [Dev Deps] update `tape` [`3a47e27`](https://github.com/inspect-js/is-negative-zero/commit/3a47e2730f889539f666ef0eb09a93fb9c80bfd1) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`128d9bd`](https://github.com/inspect-js/is-negative-zero/commit/128d9bd4c12385fb5e478ac3dd3138fa4360a777) + +## [v2.0.0](https://github.com/inspect-js/is-negative-zero/compare/v1.0.0...v2.0.0) - 2015-07-24 + +### Commits + +- Update `tape`, `eslint`; use my personal shared `eslint` config. [`648d002`](https://github.com/inspect-js/is-negative-zero/commit/648d0029b177886428a11b07307f233ae2d3175b) +- Add `npm run eslint` [`5a52d80`](https://github.com/inspect-js/is-negative-zero/commit/5a52d80ab052e377044b9b181991a32afaaa3090) +- Using my standard jscs.json file [`5a667d9`](https://github.com/inspect-js/is-negative-zero/commit/5a667d9f8b7402ca3bd134080cd4435b5c7f1462) +- Adding `npm run lint` [`9a85ed9`](https://github.com/inspect-js/is-negative-zero/commit/9a85ed934da65d8733a38bf6ad3c89fd62115194) +- Update `tape`, `covert`, `jscs` [`c6cd3a6`](https://github.com/inspect-js/is-negative-zero/commit/c6cd3a64ea5b98100e10537549f50a9eeadc30ec) +- Update `eslint` [`e9c9b6e`](https://github.com/inspect-js/is-negative-zero/commit/e9c9b6e9623f021b7f3ae4091bf9ea2571ab02b4) +- Test on latest `io.js` [`2f7c8a9`](https://github.com/inspect-js/is-negative-zero/commit/2f7c8a9d174066400c072841d7bcf02cf90f8ebf) +- Adding license and downloads badges [`717087a`](https://github.com/inspect-js/is-negative-zero/commit/717087a013b4cfc9dc7847d3d4a64faf19341be4) +- Remove Number type coercion. [`481295d`](https://github.com/inspect-js/is-negative-zero/commit/481295dbd09dbf81d196dc77382f1b92f534de3f) +- Test up to `io.js` `v2.1` [`139a84a`](https://github.com/inspect-js/is-negative-zero/commit/139a84a3dbdec29682044c6e7ac884a7382ae6e1) +- Update `eslint` [`2f5fbfb`](https://github.com/inspect-js/is-negative-zero/commit/2f5fbfbc436ccd8676fc36fcd9f0edcdda33a1e7) +- Update `eslint` [`53cb4c5`](https://github.com/inspect-js/is-negative-zero/commit/53cb4c5eccecdf2d874e78e5c38cca762ed76a9d) +- Test on `io.js` `v2.2` [`98a1824`](https://github.com/inspect-js/is-negative-zero/commit/98a1824c86366f8a03cf303f46acecd67409f94b) +- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`772d6cd`](https://github.com/inspect-js/is-negative-zero/commit/772d6cdf397e6fc1b26e5ed5f279d07a5ead6df8) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`3e6147e`](https://github.com/inspect-js/is-negative-zero/commit/3e6147ebb5ecdfda4a2bffa441572fe017c7bb73) +- Use SVG badges instead of PNG [`d986cb4`](https://github.com/inspect-js/is-negative-zero/commit/d986cb450e5bd4f373041255b69e18f47c252a1e) +- Update `tape`, `jscs` [`9f9d7e7`](https://github.com/inspect-js/is-negative-zero/commit/9f9d7e751bcf4ceeed8e36e75e31d29c76326b3f) +- Update `jscs` [`079eaf6`](https://github.com/inspect-js/is-negative-zero/commit/079eaf699d53e7e32c54e5233259a00f5f494d9a) +- Update `tape`, `jscs` [`cffe3fc`](https://github.com/inspect-js/is-negative-zero/commit/cffe3fc17c6bfaa6996bf7402446b160631a04b3) +- Update `tape`, `jscs` [`3a16616`](https://github.com/inspect-js/is-negative-zero/commit/3a166165ae8770d59c296794d28547379cebec58) +- Use consistent quotes [`9509a81`](https://github.com/inspect-js/is-negative-zero/commit/9509a8110027b12c5762ba48d03b649a921847d5) +- Test on `io.js` `v2.4` [`a9150a3`](https://github.com/inspect-js/is-negative-zero/commit/a9150a3397db339d992e9e4e6ddb52d1237fd617) +- Test on `io.js` `v2.3` [`36d7acf`](https://github.com/inspect-js/is-negative-zero/commit/36d7acf5bb9193a2b35585e2c49ae8be9f45a55e) +- Lock covert to v1.0.0. [`29d8917`](https://github.com/inspect-js/is-negative-zero/commit/29d89171c3aad69ace372edbf641ec3a5468c760) +- Updating jscs [`fe09c8a`](https://github.com/inspect-js/is-negative-zero/commit/fe09c8a6d16c637ecd83a9a8a7f6192faef0754a) +- Updating jscs [`5877bc7`](https://github.com/inspect-js/is-negative-zero/commit/5877bc7c2ed44c1ecc5d31e1c484c523450722d8) +- Running linter as part of tests [`9e77756`](https://github.com/inspect-js/is-negative-zero/commit/9e777563905f511d915ec7257e2637811b911bd6) +- Updating covert [`520a695`](https://github.com/inspect-js/is-negative-zero/commit/520a695164465b88c76860a638baafd4192bce5c) + +## [v1.0.0](https://github.com/inspect-js/is-negative-zero/compare/v0.1.1...v1.0.0) - 2014-08-08 + +### Commits + +- Updating tape [`31d1942`](https://github.com/inspect-js/is-negative-zero/commit/31d19422ecd9d453677851a9d5a8d9372a16fb39) +- Updating tape [`e7143bf`](https://github.com/inspect-js/is-negative-zero/commit/e7143bf3b67d8881b1b6ee0444637647d7bb1d2b) + +## [v0.1.1](https://github.com/inspect-js/is-negative-zero/compare/v0.1.0...v0.1.1) - 2014-05-13 + +### Merged + +- Simplify code [`#1`](https://github.com/inspect-js/is-negative-zero/pull/1) + +### Commits + +- Adding a trailing newline [`61fb37f`](https://github.com/inspect-js/is-negative-zero/commit/61fb37f677e871cca53d9309e765d808ddddfd5a) + +## [v0.1.0](https://github.com/inspect-js/is-negative-zero/compare/v0.0.0...v0.1.0) - 2014-05-13 + +### Commits + +- Make sure old and unstable nodes don't break Travis [`f627215`](https://github.com/inspect-js/is-negative-zero/commit/f627215527a95dc1ca014600650e00f15fe122c5) +- Updating deps [`b502f48`](https://github.com/inspect-js/is-negative-zero/commit/b502f48e807d7671cb07e2ca247ae2daa62e4165) +- Oops, negative numbers were negative zero! [`746cb97`](https://github.com/inspect-js/is-negative-zero/commit/746cb975d82c0fa0c5058e8e031807f9afcfd6db) +- Updating covert [`99ef4ed`](https://github.com/inspect-js/is-negative-zero/commit/99ef4ed97d2f76f2a5afbef029bf794f1b5bcffa) +- Updating tape [`ee9cfc2`](https://github.com/inspect-js/is-negative-zero/commit/ee9cfc2fd0039bdb65b6493ce0b8e47d18aa17cd) +- Testing on node 0.6 again [`6a9bf0a`](https://github.com/inspect-js/is-negative-zero/commit/6a9bf0a09e210cca09c7a8a225d08ef1e6789b5a) + +## v0.0.0 - 2014-01-19 + +### Commits + +- package.json [`8411d92`](https://github.com/inspect-js/is-negative-zero/commit/8411d92ec787fd522a1b5e65154ae88e9024a23f) +- read me [`5c8bf3c`](https://github.com/inspect-js/is-negative-zero/commit/5c8bf3ce4867dbf2997ef01ea6b712aa294ec959) +- Initial commit [`c06f7dc`](https://github.com/inspect-js/is-negative-zero/commit/c06f7dcf926f5b35ba678787a0f16cdd7b544054) +- Tests. [`5c554d4`](https://github.com/inspect-js/is-negative-zero/commit/5c554d405bfb323a7413fde395d8dc39c5316356) +- Travis CI [`334d000`](https://github.com/inspect-js/is-negative-zero/commit/334d000941fc926493cc7dbdb4e5f7ae481a311b) +- Implementation. [`4ef4491`](https://github.com/inspect-js/is-negative-zero/commit/4ef449189c36d471d283e40aa20a8ebfa4985882) diff --git a/node_modules/is-negative-zero/LICENSE b/node_modules/is-negative-zero/LICENSE new file mode 100644 index 0000000..47b7b50 --- /dev/null +++ b/node_modules/is-negative-zero/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-negative-zero/README.md b/node_modules/is-negative-zero/README.md new file mode 100644 index 0000000..e8193a4 --- /dev/null +++ b/node_modules/is-negative-zero/README.md @@ -0,0 +1,54 @@ +# is-negative-zero [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Is this value negative zero? === will lie to you. + +## Example + +```js +var isNegativeZero = require('is-negative-zero'); +var assert = require('assert'); + +assert.notOk(isNegativeZero(undefined)); +assert.notOk(isNegativeZero(null)); +assert.notOk(isNegativeZero(false)); +assert.notOk(isNegativeZero(true)); +assert.notOk(isNegativeZero(0)); +assert.notOk(isNegativeZero(42)); +assert.notOk(isNegativeZero(Infinity)); +assert.notOk(isNegativeZero(-Infinity)); +assert.notOk(isNegativeZero(NaN)); +assert.notOk(isNegativeZero('foo')); +assert.notOk(isNegativeZero(function () {})); +assert.notOk(isNegativeZero([])); +assert.notOk(isNegativeZero({})); + +assert.ok(isNegativeZero(-0)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/is-negative-zero +[npm-version-svg]: https://versionbadg.es/inspect-js/is-negative-zero.svg +[deps-svg]: https://david-dm.org/inspect-js/is-negative-zero.svg +[deps-url]: https://david-dm.org/inspect-js/is-negative-zero +[dev-deps-svg]: https://david-dm.org/inspect-js/is-negative-zero/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/is-negative-zero#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/is-negative-zero.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-negative-zero.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-negative-zero.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-negative-zero +[codecov-image]: https://codecov.io/gh/inspect-js/is-negative-zero/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-negative-zero/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-negative-zero +[actions-url]: https://github.com/inspect-js/is-negative-zero/actions diff --git a/node_modules/is-negative-zero/index.js b/node_modules/is-negative-zero/index.js new file mode 100644 index 0000000..400e5d1 --- /dev/null +++ b/node_modules/is-negative-zero/index.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function isNegativeZero(number) { + return number === 0 && (1 / number) === -Infinity; +}; + diff --git a/node_modules/is-negative-zero/package.json b/node_modules/is-negative-zero/package.json new file mode 100644 index 0000000..d0aa3d9 --- /dev/null +++ b/node_modules/is-negative-zero/package.json @@ -0,0 +1,79 @@ +{ + "name": "is-negative-zero", + "version": "2.0.2", + "description": "Is this value negative zero? === will lie to you", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "aud --production", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-negative-zero.git" + }, + "bugs": { + "url": "https://github.com/inspect-js/is-negative-zero/issues" + }, + "homepage": "https://github.com/inspect-js/is-negative-zero", + "keywords": [ + "is", + "negative", + "zero", + "negative zero", + "number", + "positive", + "0", + "-0" + ], + "devDependencies": { + "@ljharb/eslint-config": "^20.0.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^8.4.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.3.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..12.0", + "opera/15.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/is-negative-zero/test/index.js b/node_modules/is-negative-zero/test/index.js new file mode 100644 index 0000000..8fd7d16 --- /dev/null +++ b/node_modules/is-negative-zero/test/index.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); +var isNegativeZero = require('../'); + +test('not negative zero', function (t) { + t.notOk(isNegativeZero(), 'undefined is not negative zero'); + t.notOk(isNegativeZero(null), 'null is not negative zero'); + t.notOk(isNegativeZero(false), 'false is not negative zero'); + t.notOk(isNegativeZero(true), 'true is not negative zero'); + t.notOk(isNegativeZero(0), 'positive zero is not negative zero'); + t.notOk(isNegativeZero(Infinity), 'Infinity is not negative zero'); + t.notOk(isNegativeZero(-Infinity), '-Infinity is not negative zero'); + t.notOk(isNegativeZero(NaN), 'NaN is not negative zero'); + t.notOk(isNegativeZero('foo'), 'string is not negative zero'); + t.notOk(isNegativeZero([]), 'array is not negative zero'); + t.notOk(isNegativeZero({}), 'object is not negative zero'); + t.notOk(isNegativeZero(function () {}), 'function is not negative zero'); + t.notOk(isNegativeZero(-1), '-1 is not negative zero'); + + t.end(); +}); + +test('negative zero', function (t) { + t.ok(isNegativeZero(-0), 'negative zero is negative zero'); + t.end(); +}); + diff --git a/node_modules/is-number-object/.editorconfig b/node_modules/is-number-object/.editorconfig new file mode 100644 index 0000000..4e36aee --- /dev/null +++ b/node_modules/is-number-object/.editorconfig @@ -0,0 +1,23 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[CHANGELOG.md] +max_line_length = off diff --git a/node_modules/is-number-object/.eslintrc b/node_modules/is-number-object/.eslintrc new file mode 100644 index 0000000..c7933f4 --- /dev/null +++ b/node_modules/is-number-object/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + }, + + "overrides": [ + { + "files": "test-core-js.js", + "extends": "@ljharb/eslint-config/tests", + }, + ], +} diff --git a/node_modules/is-number-object/.github/FUNDING.yml b/node_modules/is-number-object/.github/FUNDING.yml new file mode 100644 index 0000000..17f4dc5 --- /dev/null +++ b/node_modules/is-number-object/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-number-object +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-number-object/.nycrc b/node_modules/is-number-object/.nycrc new file mode 100644 index 0000000..a69aa2d --- /dev/null +++ b/node_modules/is-number-object/.nycrc @@ -0,0 +1,10 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test", + "test-corejs.js" + ] +} diff --git a/node_modules/is-number-object/CHANGELOG.md b/node_modules/is-number-object/CHANGELOG.md new file mode 100644 index 0000000..028b484 --- /dev/null +++ b/node_modules/is-number-object/CHANGELOG.md @@ -0,0 +1,125 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.7](https://github.com/inspect-js/is-number-object/compare/v1.0.6...v1.0.7) - 2022-04-01 + +### Commits + +- [actions] reuse common workflows [`8f9a1b0`](https://github.com/inspect-js/is-number-object/commit/8f9a1b040a435a5c5d12150952d0e6f96d4f713a) +- [meta] better `eccheck` command [`9dc8dff`](https://github.com/inspect-js/is-number-object/commit/9dc8dff273e4d0b954fd4f2a2eacc849d321b646) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`c50ecbf`](https://github.com/inspect-js/is-number-object/commit/c50ecbfc7577c69324fca4d2b40dd354c5156be9) +- [actions] update codecov uploader [`f1a2560`](https://github.com/inspect-js/is-number-object/commit/f1a2560d4a996abea90f7a792069a35359869b67) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js`, `tape` [`4b06ace`](https://github.com/inspect-js/is-number-object/commit/4b06aceeba2ebf0887af020aa89caad8950e5f47) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `core-js`, `tape` [`3dc0e8b`](https://github.com/inspect-js/is-number-object/commit/3dc0e8b0fcc96a9bc9936e9a62a523fe67bafca5) +- [meta] add `bugs`/`homepage` package.json fields [`d7e0bcf`](https://github.com/inspect-js/is-number-object/commit/d7e0bcf1fe1b4a48d6500266c8b4058c854fecba) + +## [v1.0.6](https://github.com/inspect-js/is-number-object/compare/v1.0.5...v1.0.6) - 2021-08-05 + +### Commits + +- [Tests] run tests with core-js as well [`5177312`](https://github.com/inspect-js/is-number-object/commit/51773120b18e27bfe8a3bd228ef2e21f5802f338) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`ca2b31d`](https://github.com/inspect-js/is-number-object/commit/ca2b31d81c5d7d9b11e812dee58cd627a6d634e2) +- [Dev Deps] update `auto-changelog`, `core-js`, `eslint`, `tape` [`50950f9`](https://github.com/inspect-js/is-number-object/commit/50950f962a4b1188c478f6034194d7eb4314c884) + +## [v1.0.5](https://github.com/inspect-js/is-number-object/compare/v1.0.4...v1.0.5) - 2021-05-07 + +### Commits + +- [Tests] migrate tests to Github Actions [`9666737`](https://github.com/inspect-js/is-number-object/commit/96667372f8e36f70516218f86318f957f8c175ad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`7815ce2`](https://github.com/inspect-js/is-number-object/commit/7815ce21cb5662c2d1651b3ec302f186aa8a016b) +- [meta] do not publish github action workflow files [`80ccb75`](https://github.com/inspect-js/is-number-object/commit/80ccb7509f91732675b018cc1a636d649a92889e) +- [Tests] run `nyc` on all tests [`c9ffb74`](https://github.com/inspect-js/is-number-object/commit/c9ffb74443690ef22f9aa7dd35855fd1e3be5184) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`7e84161`](https://github.com/inspect-js/is-number-object/commit/7e84161d089c87ef42e3639ac1889642624ebd28) +- [readme] add actions and codecov badges [`0c5ec7a`](https://github.com/inspect-js/is-number-object/commit/0c5ec7aa87dac27bdcda2365124c3aa0ccf9c278) +- [actions] add Require Allow Edits workflow [`dd0fb74`](https://github.com/inspect-js/is-number-object/commit/dd0fb74b2ecb630ea7778a6f06dcc017323a3c1d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbols`, `tape` [`2d36f80`](https://github.com/inspect-js/is-number-object/commit/2d36f809a7b9896958b0b0f3b69be0067caedb45) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`77d3140`](https://github.com/inspect-js/is-number-object/commit/77d3140557d483e467ce070b21bf384e9a7562d5) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`75d4abf`](https://github.com/inspect-js/is-number-object/commit/75d4abf34168e69d73f621c696a16179ddc0873c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`0c2a917`](https://github.com/inspect-js/is-number-object/commit/0c2a917e4802b102888759fad912bd9faa5587f7) +- [Fix] do not use `Object.prototype.toString` when `Symbol.toStringTag` is shammed [`8b6ebc4`](https://github.com/inspect-js/is-number-object/commit/8b6ebc489db14a0c369214e081413f326fc0d598) +- [Dev Deps] update `auto-changelog`, `tape`; add `aud` [`62045fc`](https://github.com/inspect-js/is-number-object/commit/62045fcaddb9e4d3ef81068e99d07d21cd62023b) +- [actions] use checkout v2; remove unneeded env [`d48cd06`](https://github.com/inspect-js/is-number-object/commit/d48cd06720ea71f278a6d35c6f0a8ec04242a58f) +- [meta] use `prepublishOnly` script for npm 7+ [`827ab0d`](https://github.com/inspect-js/is-number-object/commit/827ab0d52d25f46d232ae7442ece270dec2de1df) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`bfed500`](https://github.com/inspect-js/is-number-object/commit/bfed500e6cc3cd3b9e7ffea78429c59857035791) +- [meta] remove explicit audit level config [`ce23e5e`](https://github.com/inspect-js/is-number-object/commit/ce23e5e49fbebe190267d8c99ddfd880a963b7ee) +- [meta] gitignore coverage output [`f1ad981`](https://github.com/inspect-js/is-number-object/commit/f1ad98106549c1c88322d8cb206068ea4c5bd424) + +## [v1.0.4](https://github.com/inspect-js/is-number-object/compare/v1.0.3...v1.0.4) - 2019-12-18 + +### Commits + +- [Tests] use shared travis-ci configs [`792b5aa`](https://github.com/inspect-js/is-number-object/commit/792b5aa5e7313ddf5507f7283bb7d5d5c646b11b) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v5.12`, `v4.9`; use `nvm install-latest-npm` [`dc66db7`](https://github.com/inspect-js/is-number-object/commit/dc66db7dd1eca0263f6602597eb40601519e912e) +- Update `eslint`, `tape`, `semver`; use my personal shared `eslint` config [`7660fed`](https://github.com/inspect-js/is-number-object/commit/7660fed03a7060eb5c91e74b9a17303d4fac1056) +- [Tests] remove `jscs` [`f1fee97`](https://github.com/inspect-js/is-number-object/commit/f1fee97423478bcc653c844fadda55138d9b9a54) +- [meta] add `auto-changelog` [`4b1c225`](https://github.com/inspect-js/is-number-object/commit/4b1c2253770eb18761a1e8b157772028d6f742c4) +- [meta] remove unused Makefile and associated utilities [`379b979`](https://github.com/inspect-js/is-number-object/commit/379b9793d9c61d7889e53bd9de9578dca9964ebc) +- Update `covert`, `jscs`, `eslint`, `semver` [`16d2af8`](https://github.com/inspect-js/is-number-object/commit/16d2af82a6c93aee614f7a4b2c468411c743e95f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `is`, `replace`, `semver`, `tape` [`21c0f04`](https://github.com/inspect-js/is-number-object/commit/21c0f0431984b87443c6acb9f003368feb7b4368) +- Update `is`, `tape`, `covert`, `jscs`, `editorconfig-tools`, `nsp`, `eslint`, `semver`. Add `replace`. Use `^` instead of `~`. [`19d6ee3`](https://github.com/inspect-js/is-number-object/commit/19d6ee3a3d4a87764d57316804fd8b882ba5197c) +- Update `eslint` [`d32754b`](https://github.com/inspect-js/is-number-object/commit/d32754bcca0033e01eba531c4353d1239e992203) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `replace` [`1df8165`](https://github.com/inspect-js/is-number-object/commit/1df8165dd63d9f2f78ccb78e905d0a6b3e302884) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`675372b`](https://github.com/inspect-js/is-number-object/commit/675372b115fb20b5034f40bcbb5560c6c0512746) +- [readme] clean up readme; remove testling; fix repo URLs [`80e29c4`](https://github.com/inspect-js/is-number-object/commit/80e29c4d6d0811fc361e95ee83b81280bf3ae3f5) +- [Tests] up to `node` `v12.7`, `v10.16`, `v8.16` [`287a968`](https://github.com/inspect-js/is-number-object/commit/287a9687b1fc3d091ec231c06f19a19ff7b0e8f6) +- Test on latest `iojs` and `node` versions. [`11c98a2`](https://github.com/inspect-js/is-number-object/commit/11c98a23b232cb21c7daab797fd63875c2970681) +- [actions] add automatic rebasing / merge commit blocking [`022d026`](https://github.com/inspect-js/is-number-object/commit/022d026129df445f239ba2ecd8d47a2786242d75) +- [meta] create FUNDING.yml [`7f52710`](https://github.com/inspect-js/is-number-object/commit/7f527107168aad7108b7c262d295dcf44e03214d) +- [Dev Deps] update `is`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`bc8cd50`](https://github.com/inspect-js/is-number-object/commit/bc8cd508fe4440168f9b049be3ddf93c56c06c49) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`1f9200b`](https://github.com/inspect-js/is-number-object/commit/1f9200b7c56840dc23eeeca5d0ee4f64a0446e08) +- [Tests] up to `node` `v12.11` [`706d50a`](https://github.com/inspect-js/is-number-object/commit/706d50a779b90feb3f4d2ae88d8189d19b913073) +- [Dev Deps] update `jscs` [`e3591a4`](https://github.com/inspect-js/is-number-object/commit/e3591a445b1af25d46632eafea51efa07b4eb6dc) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`baf4ee7`](https://github.com/inspect-js/is-number-object/commit/baf4ee749fb65ec12e9cab102e77aa0e14312109) +- Update `nsp`, `eslint` [`61b18d5`](https://github.com/inspect-js/is-number-object/commit/61b18d5b44542fddf4950534d506b20d8c8b1f44) +- Update `eslint`, `semver` [`52e61bd`](https://github.com/inspect-js/is-number-object/commit/52e61bd4334c0a1afacd147fd0bc1e2c1be10df5) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `has-symbols`; add `safe-publish-latest` [`79db7f6`](https://github.com/inspect-js/is-number-object/commit/79db7f610d2bcf5f0d6e8ca834f7402504101072) +- Only apps should have lockfiles [`677b9b4`](https://github.com/inspect-js/is-number-object/commit/677b9b4fb6ad9d7b984cb0f89c8b5a6df143b29a) +- Test on `io.js` `v2.2` [`e8a38b2`](https://github.com/inspect-js/is-number-object/commit/e8a38b2fe73b841b0ed55d9f60573d460a4f2a62) +- [meta] add `funding` field [`85315e7`](https://github.com/inspect-js/is-number-object/commit/85315e75c119a2aef70a766f2ddc1079b64d006b) +- [Dev Deps] update `eslint`, `tape` [`f3581aa`](https://github.com/inspect-js/is-number-object/commit/f3581aaea310546f6ee4612990468d39f058d320) +- [Tests] use `eclint` instead of `editorconfig-tools` [`7b53680`](https://github.com/inspect-js/is-number-object/commit/7b5368071000eb1c715aeeee5ff47ffdbee9fe5c) +- [Dev Deps] update `semver`, `tape` [`d6b524a`](https://github.com/inspect-js/is-number-object/commit/d6b524ac2e8c0240c436cbe8828671e383d51fd5) +- [Dev Deps] Update `tape`, `eslint` [`be19203`](https://github.com/inspect-js/is-number-object/commit/be19203dee0aa70ff8f09823bf880a38b824e1ed) +- Test up to `io.js` `v2.1` [`feb7ba6`](https://github.com/inspect-js/is-number-object/commit/feb7ba63a0816f1d36419ce240f96e9b4e4c90ba) +- Test up to `io.js` `v3.0` [`7be1f0a`](https://github.com/inspect-js/is-number-object/commit/7be1f0a25dc59b6606be9ee1ace38cb7039a59d2) +- [Dev Deps] update `tape` [`d9a2318`](https://github.com/inspect-js/is-number-object/commit/d9a2318bc82477e9321e961def11e28d364e5562) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`a6cd411`](https://github.com/inspect-js/is-number-object/commit/a6cd411c6bd92691a48b52683afce584c2c6b21b) +- Test on `io.js` `v2.4` [`46c2e7f`](https://github.com/inspect-js/is-number-object/commit/46c2e7f2ce8ad7f8ab3c1da827d93fc2780eff06) +- Test on `io.js` `v2.3` [`9c344b0`](https://github.com/inspect-js/is-number-object/commit/9c344b0df83628908a1f776a3f2e5fc4fae1d4d2) +- Fix tests for faked @@toStringTag [`f8c446e`](https://github.com/inspect-js/is-number-object/commit/f8c446e9fc320c23807717356e259529f494b9f3) + +## [v1.0.3](https://github.com/inspect-js/is-number-object/compare/v1.0.2...v1.0.3) - 2015-01-29 + +### Commits + +- If @@toStringTag is not present, use the old-school Object#toString test. [`9b2a4df`](https://github.com/inspect-js/is-number-object/commit/9b2a4df6ccf903e89198d4244eeb7f47a7056327) + +## [v1.0.2](https://github.com/inspect-js/is-number-object/compare/v1.0.1...v1.0.2) - 2015-01-29 + +### Commits + +- Improve optimizability of the non-try/catch part. [`7e6be2f`](https://github.com/inspect-js/is-number-object/commit/7e6be2fd2346557fc81bd544ac8745021c50e266) +- Fix package.json [`4f2ebea`](https://github.com/inspect-js/is-number-object/commit/4f2ebeae09c45e1eefeb2c10a011ff2ef0aca921) + +## [v1.0.1](https://github.com/inspect-js/is-number-object/compare/v1.0.0...v1.0.1) - 2015-01-29 + +### Commits + +- Use Object() instead of new Number() [`1aaa746`](https://github.com/inspect-js/is-number-object/commit/1aaa746c26878a0f698aabea4d88215311f2a38d) +- Add early exits for typeof number, or typeof not "object". [`eae4337`](https://github.com/inspect-js/is-number-object/commit/eae43375d3f88e04bb10eabd954e5a6b66ad5305) + +## v1.0.0 - 2015-01-28 + +### Commits + +- Dotfiles. [`9c74e3e`](https://github.com/inspect-js/is-number-object/commit/9c74e3eb2b10398d4022de7c4015531e874f06c8) +- `make release` [`a99e5ae`](https://github.com/inspect-js/is-number-object/commit/a99e5aeb3995a7d543fc5833722bc02011fabad6) +- package.json [`4fed9ef`](https://github.com/inspect-js/is-number-object/commit/4fed9ef7c35ccfc45ca8acd3c92c9cb91c7daa6d) +- Read me [`c91d6ba`](https://github.com/inspect-js/is-number-object/commit/c91d6ba00de79eaaac5fec7c9d8866d61d0abb62) +- Initial commit [`629fb96`](https://github.com/inspect-js/is-number-object/commit/629fb969f076e0802c799b368c7b02556bb0750e) +- Tests. [`a39de62`](https://github.com/inspect-js/is-number-object/commit/a39de624785cc204ed7c0ea5518f1c878870ceb1) +- Implementation. [`aedd91e`](https://github.com/inspect-js/is-number-object/commit/aedd91e6fc23f00852ad1266b6c19f32b7f93a22) diff --git a/node_modules/is-number-object/LICENSE b/node_modules/is-number-object/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/node_modules/is-number-object/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/is-number-object/README.md b/node_modules/is-number-object/README.md new file mode 100644 index 0000000..a5f1e5b --- /dev/null +++ b/node_modules/is-number-object/README.md @@ -0,0 +1,55 @@ +# is-number-object [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this value a JS Number object? This module works cross-realm/iframe, and despite ES6 @@toStringTag. + +## Example + +```js +var isNumber = require('is-number-object'); +var assert = require('assert'); + +assert.notOk(isNumber(undefined)); +assert.notOk(isNumber(null)); +assert.notOk(isNumber(false)); +assert.notOk(isNumber(true)); +assert.notOk(isNumber('foo')); +assert.notOk(isNumber(function () {})); +assert.notOk(isNumber([])); +assert.notOk(isNumber({})); +assert.notOk(isNumber(/a/g)); +assert.notOk(isNumber(new RegExp('a', 'g'))); +assert.notOk(isNumber(new Date())); + +assert.ok(isNumber(42)); +assert.ok(isNumber(NaN)); +assert.ok(isNumber(Infinity)); +assert.ok(isNumber(new Number(42))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-number-object +[2]: https://versionbadg.es/inspect-js/is-number-object.svg +[5]: https://david-dm.org/inspect-js/is-number-object.svg +[6]: https://david-dm.org/inspect-js/is-number-object +[7]: https://david-dm.org/inspect-js/is-number-object/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-number-object#info=devDependencies +[11]: https://nodei.co/npm/is-number-object.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-number-object.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-number-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-number-object +[codecov-image]: https://codecov.io/gh/inspect-js/is-number-object/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-number-object/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-number-object +[actions-url]: https://github.com/inspect-js/is-number-object/actions diff --git a/node_modules/is-number-object/index.js b/node_modules/is-number-object/index.js new file mode 100644 index 0000000..9107c31 --- /dev/null +++ b/node_modules/is-number-object/index.js @@ -0,0 +1,24 @@ +'use strict'; + +var numToStr = Number.prototype.toString; +var tryNumberObject = function tryNumberObject(value) { + try { + numToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var numClass = '[object Number]'; +var hasToStringTag = require('has-tostringtag/shams')(); + +module.exports = function isNumberObject(value) { + if (typeof value === 'number') { + return true; + } + if (typeof value !== 'object') { + return false; + } + return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass; +}; diff --git a/node_modules/is-number-object/package.json b/node_modules/is-number-object/package.json new file mode 100644 index 0000000..2c8b16d --- /dev/null +++ b/node_modules/is-number-object/package.json @@ -0,0 +1,85 @@ +{ + "name": "is-number-object", + "version": "1.0.7", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "Is this value a JS Number object? This module works cross-realm/iframe, and despite ES6 @@toStringTag.", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test:corejs": "nyc tape test-corejs.js", + "test": "npm run tests-only && npm run test:corejs", + "posttest": "aud --production", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-number-object.git" + }, + "keywords": [ + "Number", + "ES6", + "toStringTag", + "@@toStringTag", + "Number object" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/is-number-object/issues" + }, + "homepage": "https://github.com/inspect-js/is-number-object#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.2.3", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "core-js": "^3.21.1", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "has-tostringtag": "^1.0.0" + } +} diff --git a/node_modules/is-number-object/test/index.js b/node_modules/is-number-object/test/index.js new file mode 100644 index 0000000..bca48b2 --- /dev/null +++ b/node_modules/is-number-object/test/index.js @@ -0,0 +1,38 @@ +'use strict'; + +var test = require('tape'); +var isNumber = require('../'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('not Numbers', function (t) { + t.notOk(isNumber(), 'undefined is not Number'); + t.notOk(isNumber(null), 'null is not Number'); + t.notOk(isNumber(false), 'false is not Number'); + t.notOk(isNumber(true), 'true is not Number'); + t.notOk(isNumber('foo'), 'string is not Number'); + t.notOk(isNumber([]), 'array is not Number'); + t.notOk(isNumber({}), 'object is not Number'); + t.notOk(isNumber(function () {}), 'function is not Number'); + t.notOk(isNumber(/a/g), 'regex literal is not Number'); + t.notOk(isNumber(new RegExp('a', 'g')), 'regex object is not Number'); + t.notOk(isNumber(new Date()), 'new Date() is not Number'); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + var fakeNumber = { + toString: function () { return '7'; }, + valueOf: function () { return 42; } + }; + fakeNumber[Symbol.toStringTag] = 'Number'; + t.notOk(isNumber(fakeNumber), 'fake Number with @@toStringTag "Number" is not Number'); + t.end(); +}); + +test('Numbers', function (t) { + t.ok(isNumber(42), 'number is Number'); + t.ok(isNumber(Object(42)), 'number object is Number'); + t.ok(isNumber(NaN), 'NaN is Number'); + t.ok(isNumber(Infinity), 'Infinity is Number'); + t.end(); +}); diff --git a/node_modules/is-number/LICENSE b/node_modules/is-number/LICENSE new file mode 100644 index 0000000..9af4a67 --- /dev/null +++ b/node_modules/is-number/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-number/README.md b/node_modules/is-number/README.md new file mode 100644 index 0000000..eb8149e --- /dev/null +++ b/node_modules/is-number/README.md @@ -0,0 +1,187 @@ +# is-number [![NPM version](https://img.shields.io/npm/v/is-number.svg?style=flat)](https://www.npmjs.com/package/is-number) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![NPM total downloads](https://img.shields.io/npm/dt/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-number.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-number) + +> Returns true if the value is a finite number. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-number +``` + +## Why is this needed? + +In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use `+`, `-`, or `Number()` to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results: + +```js +console.log(+[]); //=> 0 +console.log(+''); //=> 0 +console.log(+' '); //=> 0 +console.log(typeof NaN); //=> 'number' +``` + +This library offers a performant way to smooth out edge cases like these. + +## Usage + +```js +const isNumber = require('is-number'); +``` + +See the [tests](./test.js) for more examples. + +### true + +```js +isNumber(5e3); // true +isNumber(0xff); // true +isNumber(-1.1); // true +isNumber(0); // true +isNumber(1); // true +isNumber(1.1); // true +isNumber(10); // true +isNumber(10.10); // true +isNumber(100); // true +isNumber('-1.1'); // true +isNumber('0'); // true +isNumber('012'); // true +isNumber('0xff'); // true +isNumber('1'); // true +isNumber('1.1'); // true +isNumber('10'); // true +isNumber('10.10'); // true +isNumber('100'); // true +isNumber('5e3'); // true +isNumber(parseInt('012')); // true +isNumber(parseFloat('012')); // true +``` + +### False + +Everything else is false, as you would expect: + +```js +isNumber(Infinity); // false +isNumber(NaN); // false +isNumber(null); // false +isNumber(undefined); // false +isNumber(''); // false +isNumber(' '); // false +isNumber('foo'); // false +isNumber([1]); // false +isNumber([]); // false +isNumber(function () {}); // false +isNumber({}); // false +``` + +## Release history + +### 7.0.0 + +* Refactor. Now uses `.isFinite` if it exists. +* Performance is about the same as v6.0 when the value is a string or number. But it's now 3x-4x faster when the value is not a string or number. + +### 6.0.0 + +* Optimizations, thanks to @benaadams. + +### 5.0.0 + +**Breaking changes** + +* removed support for `instanceof Number` and `instanceof String` + +## Benchmarks + +As with all benchmarks, take these with a grain of salt. See the [benchmarks](./benchmark/index.js) for more detail. + +``` +# all +v7.0 x 413,222 ops/sec ±2.02% (86 runs sampled) +v6.0 x 111,061 ops/sec ±1.29% (85 runs sampled) +parseFloat x 317,596 ops/sec ±1.36% (86 runs sampled) +fastest is 'v7.0' + +# string +v7.0 x 3,054,496 ops/sec ±1.05% (89 runs sampled) +v6.0 x 2,957,781 ops/sec ±0.98% (88 runs sampled) +parseFloat x 3,071,060 ops/sec ±1.13% (88 runs sampled) +fastest is 'parseFloat,v7.0' + +# number +v7.0 x 3,146,895 ops/sec ±0.89% (89 runs sampled) +v6.0 x 3,214,038 ops/sec ±1.07% (89 runs sampled) +parseFloat x 3,077,588 ops/sec ±1.07% (87 runs sampled) +fastest is 'v6.0' +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") +* [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") +* [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") +* [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 49 | [jonschlinkert](https://github.com/jonschlinkert) | +| 5 | [charlike-old](https://github.com/charlike-old) | +| 1 | [benaadams](https://github.com/benaadams) | +| 1 | [realityking](https://github.com/realityking) | + +### Author + +**Jon Schlinkert** + +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) + +### License + +Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 15, 2018._ \ No newline at end of file diff --git a/node_modules/is-number/index.js b/node_modules/is-number/index.js new file mode 100644 index 0000000..27f19b7 --- /dev/null +++ b/node_modules/is-number/index.js @@ -0,0 +1,18 @@ +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +module.exports = function(num) { + if (typeof num === 'number') { + return num - num === 0; + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; +}; diff --git a/node_modules/is-number/package.json b/node_modules/is-number/package.json new file mode 100644 index 0000000..3715072 --- /dev/null +++ b/node_modules/is-number/package.json @@ -0,0 +1,82 @@ +{ + "name": "is-number", + "description": "Returns true if a number or string value is a finite number. Useful for regex matches, parsing, user input, etc.", + "version": "7.0.0", + "homepage": "https://github.com/jonschlinkert/is-number", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Olsten Larck (https://i.am.charlike.online)", + "Rouven Weßling (www.rouvenwessling.de)" + ], + "repository": "jonschlinkert/is-number", + "bugs": { + "url": "https://github.com/jonschlinkert/is-number/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.12.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "gulp-format-md": "^1.0.0", + "mocha": "^3.5.3" + }, + "keywords": [ + "cast", + "check", + "coerce", + "coercion", + "finite", + "integer", + "is", + "isnan", + "is-nan", + "is-num", + "is-number", + "isnumber", + "isfinite", + "istype", + "kind", + "math", + "nan", + "num", + "number", + "numeric", + "parseFloat", + "parseInt", + "test", + "type", + "typeof", + "value" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "related": { + "list": [ + "is-plain-object", + "is-primitive", + "isobject", + "kind-of" + ] + }, + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/is-path-inside/index.d.ts b/node_modules/is-path-inside/index.d.ts new file mode 100644 index 0000000..5cc3d80 --- /dev/null +++ b/node_modules/is-path-inside/index.d.ts @@ -0,0 +1,27 @@ +/** +Check if a path is inside another path. + +Note that relative paths are resolved against `process.cwd()` to make them absolute. + +_Important:_ This package is meant for use with path manipulation. It does not check if the paths exist nor does it resolve symlinks. You should not use this as a security mechanism to guard against access to certain places on the file system. + +@example +``` +import isPathInside = require('is-path-inside'); + +isPathInside('a/b/c', 'a/b'); +//=> true + +isPathInside('a/b/c', 'x/y'); +//=> false + +isPathInside('a/b/c', 'a/b/c'); +//=> false + +isPathInside('/Users/sindresorhus/dev/unicorn', '/Users/sindresorhus'); +//=> true +``` +*/ +declare function isPathInside(childPath: string, parentPath: string): boolean; + +export = isPathInside; diff --git a/node_modules/is-path-inside/index.js b/node_modules/is-path-inside/index.js new file mode 100644 index 0000000..28ed79c --- /dev/null +++ b/node_modules/is-path-inside/index.js @@ -0,0 +1,12 @@ +'use strict'; +const path = require('path'); + +module.exports = (childPath, parentPath) => { + const relation = path.relative(parentPath, childPath); + return Boolean( + relation && + relation !== '..' && + !relation.startsWith(`..${path.sep}`) && + relation !== path.resolve(childPath) + ); +}; diff --git a/node_modules/is-path-inside/license b/node_modules/is-path-inside/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-path-inside/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-path-inside/package.json b/node_modules/is-path-inside/package.json new file mode 100644 index 0000000..88c154a --- /dev/null +++ b/node_modules/is-path-inside/package.json @@ -0,0 +1,36 @@ +{ + "name": "is-path-inside", + "version": "3.0.3", + "description": "Check if a path is inside another path", + "license": "MIT", + "repository": "sindresorhus/is-path-inside", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "inside", + "folder", + "directory", + "dir", + "file", + "resolve" + ], + "devDependencies": { + "ava": "^2.1.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-path-inside/readme.md b/node_modules/is-path-inside/readme.md new file mode 100644 index 0000000..e8c4f92 --- /dev/null +++ b/node_modules/is-path-inside/readme.md @@ -0,0 +1,63 @@ +# is-path-inside + +> Check if a path is inside another path + + +## Install + +``` +$ npm install is-path-inside +``` + + +## Usage + +```js +const isPathInside = require('is-path-inside'); + +isPathInside('a/b/c', 'a/b'); +//=> true + +isPathInside('a/b/c', 'x/y'); +//=> false + +isPathInside('a/b/c', 'a/b/c'); +//=> false + +isPathInside('/Users/sindresorhus/dev/unicorn', '/Users/sindresorhus'); +//=> true +``` + + +## API + +### isPathInside(childPath, parentPath) + +Note that relative paths are resolved against `process.cwd()` to make them absolute. + +**Important:** This package is meant for use with path manipulation. It does not check if the paths exist nor does it resolve symlinks. You should not use this as a security mechanism to guard against access to certain places on the file system. + +#### childPath + +Type: `string` + +The path that should be inside `parentPath`. + +#### parentPath + +Type: `string` + +The path that should contain `childPath`. + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/is-regex/.editorconfig b/node_modules/is-regex/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/is-regex/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/is-regex/.eslintignore b/node_modules/is-regex/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-regex/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-regex/.eslintrc b/node_modules/is-regex/.eslintrc new file mode 100644 index 0000000..1f6f127 --- /dev/null +++ b/node_modules/is-regex/.eslintrc @@ -0,0 +1,19 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": [1], + "operator-linebreak": [2, "before"], + }, + + "overrides": [ + { + "files": ["test/**/*.js"], + "globals": { + "Proxy": false, + }, + }, + ], +} diff --git a/node_modules/is-regex/.nycrc b/node_modules/is-regex/.nycrc new file mode 100644 index 0000000..a69aa2d --- /dev/null +++ b/node_modules/is-regex/.nycrc @@ -0,0 +1,10 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test", + "test-corejs.js" + ] +} diff --git a/node_modules/is-regex/CHANGELOG.md b/node_modules/is-regex/CHANGELOG.md new file mode 100644 index 0000000..b7496b2 --- /dev/null +++ b/node_modules/is-regex/CHANGELOG.md @@ -0,0 +1,197 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.4](https://github.com/inspect-js/is-regex/compare/v1.1.3...v1.1.4) - 2021-08-05 + +### Commits + +- [Dev Deps] update `auto-changelog`, `core-js`, `eslint`, `tape` [`4b17cad`](https://github.com/inspect-js/is-regex/commit/4b17cad8496b1ae621b18335fa3afe94d0c65e83) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`2dad4af`](https://github.com/inspect-js/is-regex/commit/2dad4afffa15f07cbbf7675b77d1f650c92652c4) + +## [v1.1.3](https://github.com/inspect-js/is-regex/compare/v1.1.2...v1.1.3) - 2021-05-07 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c681ab9`](https://github.com/inspect-js/is-regex/commit/c681ab99c07f8b3b7ae5f652b3105a30bce94f69) +- [Fix] do not use `Object.prototype.toString` when `Symbol.toStringTag` is shammed [`ca019fd`](https://github.com/inspect-js/is-regex/commit/ca019fdb828dc7d32e323213403ac9995d8604e3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`605a66f`](https://github.com/inspect-js/is-regex/commit/605a66f278900f1c8ae9d1dfcec31e5f61b10ad3) +- [readme] add actions and codecov badges [`8d7c6f0`](https://github.com/inspect-js/is-regex/commit/8d7c6f0e007bd982f21b958e0abc98b8a84e2a24) +- [meta] use `prepublishOnly` script for npm 7+ [`8e50e91`](https://github.com/inspect-js/is-regex/commit/8e50e91f51aa5038745526710ef2e030527982a7) +- [Deps] update `has-symbols` [`4742c81`](https://github.com/inspect-js/is-regex/commit/4742c81260c3db9a8c9ef57110981fb6175f58e0) + +## [v1.1.2](https://github.com/inspect-js/is-regex/compare/v1.1.1...v1.1.2) - 2021-02-01 + +### Commits + +- [Tests] migrate tests to Github Actions [`cc1686e`](https://github.com/inspect-js/is-regex/commit/cc1686e25f446ca6948f43b3f180d6e55e31fb4e) +- [readme] fix repo URLs; remove travis badge [`d1d1da6`](https://github.com/inspect-js/is-regex/commit/d1d1da647bb4e91589606f12470cd27a47b3bb81) +- [meta] do not publish github action workflow files [`9f84b99`](https://github.com/inspect-js/is-regex/commit/9f84b993a995f057b4d2d097ef47b1ff9c84115d) +- [Tests] run `nyc` on all tests [`c37aab9`](https://github.com/inspect-js/is-regex/commit/c37aab9d332c4834b08ada94736c45ab1d39cd2f) +- [Robustness] use `call-bind` [`fbb61bf`](https://github.com/inspect-js/is-regex/commit/fbb61bf3e19ccc178e6ed1e0d7ab9cc7c7167393) +- [actions] add "Allow Edits" workflow [`9022b53`](https://github.com/inspect-js/is-regex/commit/9022b53cb05b0f105cd179800cf96e055b249f08) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`d60f28f`](https://github.com/inspect-js/is-regex/commit/d60f28f7f2fb21dade7bce302b3e0246206423d3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`2c35c43`](https://github.com/inspect-js/is-regex/commit/2c35c437edf3eeb37129eea2404d8f465d27620f) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`1009e25`](https://github.com/inspect-js/is-regex/commit/1009e259d49a63753dc6e79e2b876a30c00c6de6) +- [meta] gitignore coverage output [`3b5fa9e`](https://github.com/inspect-js/is-regex/commit/3b5fa9ed2882c65ee81dff979f79f1a2751d3772) +- [actions] update workflows [`1843ef6`](https://github.com/inspect-js/is-regex/commit/1843ef65b8b8c24a44e91bc4ed5ee60dffc31c2d) + +## [v1.1.1](https://github.com/inspect-js/is-regex/compare/v1.1.0...v1.1.1) - 2020-08-03 + +### Commits + +- [Performance] Re-add lastIndex check to improve performance [`d8495cd`](https://github.com/inspect-js/is-regex/commit/d8495cd22d475ddca250818921b6088f631c1972) +- [Dev Deps] update `auto-changelog`, `eslint` [`778fa6b`](https://github.com/inspect-js/is-regex/commit/778fa6b9d2b182ee6d73993e103532855e956f85) + +## [v1.1.0](https://github.com/inspect-js/is-regex/compare/v1.0.5...v1.1.0) - 2020-06-03 + +### Commits + +- [New] use `badStringifier`‑based RegExp detection [`31eff67`](https://github.com/inspect-js/is-regex/commit/31eff673243d65c3d6c05848c0eb52f5380f1be3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`fc91458`](https://github.com/inspect-js/is-regex/commit/fc914588187b8bb00d8d792c84f06a6e15d883c1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`; add `safe-publish-latest` [`d43ed83`](https://github.com/inspect-js/is-regex/commit/d43ed83db54ea727bb0b1b77a50af79d1edb8a6d) +- [Dev Deps] update `auto-changelog`, `tape`; add `aud` [`56647d1`](https://github.com/inspect-js/is-regex/commit/56647d196be34ef3c118ad67726e75169fbcb875) +- [meta] only run `aud` on prod deps [`e0865b8`](https://github.com/inspect-js/is-regex/commit/e0865b8360b0ac1b9d17b7b81ae5f339e5c9036b) + +## [v1.0.5](https://github.com/inspect-js/is-regex/compare/v1.0.4...v1.0.5) - 2019-12-15 + +### Commits + +- [Tests] use shared travis-ci configs [`af728b2`](https://github.com/inspect-js/is-regex/commit/af728b21c5cc9e41234fb4015594bffdcfff597c) +- [Tests] remove `jscs` [`1b8cfe8`](https://github.com/inspect-js/is-regex/commit/1b8cfe8cfb14820c196775f19d370276e4034791) +- [meta] add `auto-changelog` [`c3131d8`](https://github.com/inspect-js/is-regex/commit/c3131d8ab5d06ea5fa05a4bb2ad28bbfb81668ad) +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`, `v4.8`; newer npm fails on older nodes [`660b658`](https://github.com/inspect-js/is-regex/commit/660b6585d1a9607dbdae879b70ce2f6a5684616c) +- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS [`7c25218`](https://github.com/inspect-js/is-regex/commit/7c25218d540ab17c18e4ae333677c5725806a778) +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`fa95547`](https://github.com/inspect-js/is-regex/commit/fa955478950a5ba0a920010d5daaa29487500b30) +- [meta] remove unused Makefile and associated utilities [`9fd2a29`](https://github.com/inspect-js/is-regex/commit/9fd2a29dc57ed125f3d61e94f6254a9dd8ee0044) +- [Tests] up to `node` `v11.3`, `v10.14`, `v8.14`, `v6.15` [`7f2ac41`](https://github.com/inspect-js/is-regex/commit/7f2ac41ef5dc4d53bfe2fb1c24486c688a2537bd) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`6fa2b0f`](https://github.com/inspect-js/is-regex/commit/6fa2b0fe171a5b02086a06679a92d989e83a8b8e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`697e1de`](https://github.com/inspect-js/is-regex/commit/697e1de1c9e69f08e591cc0040d81fdbbde6fe4e) +- [actions] add automatic rebasing / merge commit blocking [`ad86dc9`](https://github.com/inspect-js/is-regex/commit/ad86dc97a52e4f66fbfb3b8c9c78da3963588b54) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `jscs`, `nsp`, `replace`, `semver`, `tape` [`5c99c8e`](https://github.com/inspect-js/is-regex/commit/5c99c8e384d5ce2ef434be5853c301477cf35456) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `replace`, `semver`, `tape` [`bb63686`](https://github.com/inspect-js/is-regex/commit/bb63686a9d0fc586d121549cf484da95edec3b0a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config@`, `replace`, `semver`, `tape` [`ddf3670`](https://github.com/inspect-js/is-regex/commit/ddf36705e5f7bd29832721e4a23abf06195032c6) +- [Dev Deps] update `tape`, `nsp`, `eslint`, `@ljharb/eslint-config` [`e7b5a62`](https://github.com/inspect-js/is-regex/commit/e7b5a626eef3b9648c7d52d4620ce2e2a98a9ab8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`c803db5`](https://github.com/inspect-js/is-regex/commit/c803db5cd94cf9e0a559617adbc1e4c9d22007ff) +- [Tests] switch from `nsp` to `npm audit` [`b7239be`](https://github.com/inspect-js/is-regex/commit/b7239be9da263a0f7066f79d087eaf700a9613e9) +- [Dev Deps] update `eslint`, `nsp`, `semver`, `tape` [`347ee6c`](https://github.com/inspect-js/is-regex/commit/347ee6c67ba0f56b03f21a5abe743658f6515963) +- Only apps should have lockfiles. [`3866575`](https://github.com/inspect-js/is-regex/commit/38665755ecf028061f15816059e26023890a0dc7) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`d099a39`](https://github.com/inspect-js/is-regex/commit/d099a3943eb7e156a3e64fb8b74e11d7c83a4bec) +- [meta] add `funding` field [`741aecd`](https://github.com/inspect-js/is-regex/commit/741aecd92cd49868b3606c8cc99ce299e5f3c7d5) +- [Tests] use `eclint` instead of `editorconfig-tools` [`bc6aa75`](https://github.com/inspect-js/is-regex/commit/bc6aa7539e506788709b96f7bf3d7549850a81c3) +- [Tests] on `node` `v10.1` [`262226f`](https://github.com/inspect-js/is-regex/commit/262226f08fa34dff9a8dffd16daabb3dc6e262eb) +- [Dev Deps] update `eslint` [`31fd719`](https://github.com/inspect-js/is-regex/commit/31fd719dd59a6111ca710cdb0d19a8adadf9b8c6) +- [Deps] update `has` [`e9e25a3`](https://github.com/inspect-js/is-regex/commit/e9e25a3de7e89faaa6aadf5010477074140e8218) +- [Dev Deps] update `replace` [`aeeb968`](https://github.com/inspect-js/is-regex/commit/aeeb968bf5a4fc07f0fa6905f2c699fc563b6c32) +- [Tests] set audit level [`2a6290e`](https://github.com/inspect-js/is-regex/commit/2a6290e78b58bf14b734d7998fe53b4a84db5e44) +- [Tests] remove `nsp` [`fc74c2b`](https://github.com/inspect-js/is-regex/commit/fc74c2bb6970a7f3280abe6eff3b492d77d89c9f) + +## [v1.0.4](https://github.com/inspect-js/is-regex/compare/v1.0.3...v1.0.4) - 2017-02-18 + +### Fixed + +- [Fix] ensure that `lastIndex` is not mutated [`#3`](https://github.com/inspect-js/is-regex/issues/3) + +### Commits + +- Update `eslint`, `tape`, `semver`; use my personal shared `eslint` config [`c4a41c3`](https://github.com/inspect-js/is-regex/commit/c4a41c3a8203a3919b01cd0d1b577daadf30a452) +- [Tests] on all node minors; improve test matrix [`58d7508`](https://github.com/inspect-js/is-regex/commit/58d7508a36eb92bd76717486b9e78bde502ffe3e) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`7290076`](https://github.com/inspect-js/is-regex/commit/729007606e9ed162953d1f5812c37eb06c554ec2) +- Update `covert`, `jscs`, `eslint`, `semver` [`dabc729`](https://github.com/inspect-js/is-regex/commit/dabc729cfc4458264c6f7642004d41dd5c214bfd) +- Update `eslint` [`a946b05`](https://github.com/inspect-js/is-regex/commit/a946b051159396b4311c564880f96e3d00e8b8e2) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`1744dde`](https://github.com/inspect-js/is-regex/commit/1744dde77526841f216fa2c1c866c5a82b1638c0) +- [Refactor] when try/catch is needed, bail early if the value lacks an own `lastIndex` data property. [`288ad93`](https://github.com/inspect-js/is-regex/commit/288ad93dbfed9f6828de20de67105ee6d6504425) +- Update `editorconfig-tools`, `eslint`, `semver`, `replace` [`4d895c6`](https://github.com/inspect-js/is-regex/commit/4d895c68a0cdbb5803185928963c15147aad0404) +- Update `eslint`, `tape`, `semver` [`f387f03`](https://github.com/inspect-js/is-regex/commit/f387f03b260b56372bfca301d4e79c4067633854) +- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`55e480f`](https://github.com/inspect-js/is-regex/commit/55e480f407cafb6c21a6c32aef04ccaa3ba4216c) +- [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`89d9528`](https://github.com/inspect-js/is-regex/commit/89d95285b364913ebcd8ac7e0872570fe009a5d3) +- [Dev Deps] update `jscs` [`eb222a8`](https://github.com/inspect-js/is-regex/commit/eb222a8435e59909354f3700fd4880e4ce1cb13e) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`c65429c`](https://github.com/inspect-js/is-regex/commit/c65429cea0366508c10ad2ab773af7b83a34fc81) +- Update `nsp`, `eslint` [`c60fbd8`](https://github.com/inspect-js/is-regex/commit/c60fbd8680f7fb3508ec3c5be8ebb788672516c8) +- Update `eslint`, `semver` [`6a62116`](https://github.com/inspect-js/is-regex/commit/6a621168c63616bf004ca8b1f885b4eb8a58a3e5) +- [Tests] on `node` `v7.5`, `v4.7` [`e764651`](https://github.com/inspect-js/is-regex/commit/e764651336f5da5e239e9fe8869f3a3201c19d2b) +- Test up to `io.js` `v2.1` [`3bf326a`](https://github.com/inspect-js/is-regex/commit/3bf326a9bcd530fd16c9fc806e249a68e25ab7e3) +- Test on the latest `io.js` versions. [`693d047`](https://github.com/inspect-js/is-regex/commit/693d0477631c5d7671f6c99eca5594ffffa75771) +- [Refactor] use an early return instead of a ternary. [`31eaca2`](https://github.com/inspect-js/is-regex/commit/31eaca28b7d0aaac0599fe7a569b93b842f8ab16) +- Test on `io.js` `v2.2` [`c18c55a`](https://github.com/inspect-js/is-regex/commit/c18c55aee6358d70531f935e98851e42b698d93c) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`a1c237d`](https://github.com/inspect-js/is-regex/commit/a1c237d35f880fe0bcbc9275254611a6a2300aaf) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`aa3ea0f`](https://github.com/inspect-js/is-regex/commit/aa3ea0f148af31d75f7ef8a800412729d82def04) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`d97831d`](https://github.com/inspect-js/is-regex/commit/d97831d0e2ccd3d00d1f7354b7f81e2575f90953) +- [Dev Deps] Update `tape`, `eslint` [`95e6def`](https://github.com/inspect-js/is-regex/commit/95e6defe3178c45dc9df16e474e558979d5f5c05) +- Update `eslint`, `nsp` [`3844c93`](https://github.com/inspect-js/is-regex/commit/3844c935cfe7c52fae0dc74d27e884c417cb4616) +- Update `tape`, `jscs` [`0d6dac8`](https://github.com/inspect-js/is-regex/commit/0d6dac818ed251910171965932f021291919e770) +- Fix tests for faked @@toStringTag [`2ebef9f`](https://github.com/inspect-js/is-regex/commit/2ebef9f0759843e9a063de7a512b46e3e7daea7e) +- Test up to `io.js` `v3.0` [`ec1d2d4`](https://github.com/inspect-js/is-regex/commit/ec1d2d44481fa0fa11448527da8030c99fe47a12) +- [Refactor] bail earlier when the value is falsy. [`a9e333e`](https://github.com/inspect-js/is-regex/commit/a9e333e2ac8912ca05b7e31d30e4eea683c0da4b) +- [Dev Deps] update `tape` [`8cdcaae`](https://github.com/inspect-js/is-regex/commit/8cdcaae07be8c790cdb99849e6076ea7702a4c84) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`281c4ef`](https://github.com/inspect-js/is-regex/commit/281c4efeb71c86dd380e741bcaee3f7dbf956151) +- Test on `io.js` `v2.4` [`4d54c68`](https://github.com/inspect-js/is-regex/commit/4d54c68a81b5332a3b76259d8aa8f514be5efd13) +- Test on `io.js` `v2.3` [`23170f5`](https://github.com/inspect-js/is-regex/commit/23170f5cae632d0377de73bd2febc53db8aebbc9) +- Test on `iojs-v1.6` [`4487ad0`](https://github.com/inspect-js/is-regex/commit/4487ad0194a5684223bfa2690da4e0a441f7132a) + +## [v1.0.3](https://github.com/inspect-js/is-regex/compare/v1.0.2...v1.0.3) - 2015-01-29 + +### Commits + +- Update npm run scripts. [`dc528dd`](https://github.com/inspect-js/is-regex/commit/dc528dd25e775089bc0a3f5a8f7ae7ffc4cdf52a) +- Add toStringTag tests. [`f48a83a`](https://github.com/inspect-js/is-regex/commit/f48a83a78720b78ab60ca586c16f6f3dbcfec825) +- If @@toStringTag is not present, use the old-school Object#toString test. [`50b0ffd`](https://github.com/inspect-js/is-regex/commit/50b0ffd9c7fdbd54aee8cde1b07e680ae84f6a0d) + +## [v1.0.2](https://github.com/inspect-js/is-regex/compare/v1.0.1...v1.0.2) - 2015-01-29 + +### Commits + +- `make release` [`a1de7ec`](https://github.com/inspect-js/is-regex/commit/a1de7eca4cecc8015fd27804669f8fc61bd16a68) +- Improve optimization by separating the try/catch, and bailing out early when not typeof "object". [`5ab7632`](https://github.com/inspect-js/is-regex/commit/5ab76322a348487fa8b16761e83f6824c3c27d11) + +## [v1.0.1](https://github.com/inspect-js/is-regex/compare/v1.0.0...v1.0.1) - 2015-01-28 + +### Commits + +- Using my standard jscs.json file [`1f1733a`](https://github.com/inspect-js/is-regex/commit/1f1733ac8433cdcceb25356f86b74136a4477cb9) +- Adding `npm run lint` [`51ea70f`](https://github.com/inspect-js/is-regex/commit/51ea70fa7e461d022f611c195f343ea8d0333d71) +- Use RegExp#exec to test if something is a regex, which works even with ES6 @@toStringTag. [`042c8c7`](https://github.com/inspect-js/is-regex/commit/042c8c734faade9015932b61f1e8ea4f3a93b1b3) +- Adding license and downloads badges [`366d619`](https://github.com/inspect-js/is-regex/commit/366d61965d3a4119126e78e09b2166bbcddd0c5a) +- Use SVG badges instead of PNG [`6a32e4f`](https://github.com/inspect-js/is-regex/commit/6a32e4fc87d7d3a3787b800dd033c9293aead6df) +- Update `tape`, `jscs` [`f1b9462`](https://github.com/inspect-js/is-regex/commit/f1b9462f86d1b69de07176e7f277f668757ba964) +- Update `jscs` [`1bff23f`](https://github.com/inspect-js/is-regex/commit/1bff23ff0fe88c8263e8bf04cf99e290af96d5b0) +- Update `tape`, `jscs` [`c22ea2e`](https://github.com/inspect-js/is-regex/commit/c22ea2e7967f45618deed01ff5ea483f918be216) +- Update `tape`, `jscs` [`b0479db`](https://github.com/inspect-js/is-regex/commit/b0479db99a1b1b872d1618fb0a71f0c74a78b29b) +- Use consistent quotes [`1a6e347`](https://github.com/inspect-js/is-regex/commit/1a6e34730d9270f3f20519139faa4c4e6ec2e1f5) +- Make travis builds faster. [`090a4ea`](https://github.com/inspect-js/is-regex/commit/090a4ea7c5fa709d108d596e3bc304e6ce973dec) +- Update `tape` [`7d76129`](https://github.com/inspect-js/is-regex/commit/7d7612928bdd43230fbd835db71797249ca24f35) +- Lock covert to v1.0.0. [`9a90b03`](https://github.com/inspect-js/is-regex/commit/9a90b03fb390e66f874223a34c58ba2bb109edd3) +- Updating tape [`bfbc7f5`](https://github.com/inspect-js/is-regex/commit/bfbc7f593a007acd0411152bbb55f724dc4ca935) +- Updating jscs [`13ad511`](https://github.com/inspect-js/is-regex/commit/13ad511d80cd67300c2c0c5387fc4b3b423e2768) +- Updating jscs [`cda1945`](https://github.com/inspect-js/is-regex/commit/cda1945d603dfe99e24d5a909a931d366451bc4d) +- Updating jscs [`de96c99`](https://github.com/inspect-js/is-regex/commit/de96c99d4bf5787df671de6df9138b6547a6545b) +- Running linter as part of tests [`2cb6567`](https://github.com/inspect-js/is-regex/commit/2cb656733b1ed0af14ad11fb584006d22de0c69d) +- Updating covert [`a56ae74`](https://github.com/inspect-js/is-regex/commit/a56ae74ec8d5f0473295a8b10519a18580f16624) +- Updating tape [`ffe47f7`](https://github.com/inspect-js/is-regex/commit/ffe47f7fe9cf6d16896b4bdc286bd1d0805d5c49) + +## [v1.0.0](https://github.com/inspect-js/is-regex/compare/v0.0.0...v1.0.0) - 2014-05-19 + +### Commits + +- Make sure old and unstable nodes don't break Travis [`05da747`](https://github.com/inspect-js/is-regex/commit/05da7478f960dc131ec3ad864e27e8c6b7d74a80) +- toString is a reserved var name in old Opera [`885c48c`](https://github.com/inspect-js/is-regex/commit/885c48c120f921a55f1842b0607d3e7875379821) +- Updating deps [`2ca0e79`](https://github.com/inspect-js/is-regex/commit/2ca0e79a2443ca34d85e8b2ea2e26f55855b74a7) +- Updating tape. [`9678435`](https://github.com/inspect-js/is-regex/commit/96784355611deb0c23b9064be774216d76e3e457) +- Updating covert [`c3bb898`](https://github.com/inspect-js/is-regex/commit/c3bb8985a422e3e0c81f9c43899b6c19a72c755f) +- Updating tape [`7811708`](https://github.com/inspect-js/is-regex/commit/78117089688258b8f939b397b37897b5b3e30f74) +- Testing on node 0.6 again [`dec36ae`](https://github.com/inspect-js/is-regex/commit/dec36ae58a39a3f80e832b702c3e19406363c160) +- Run code coverage as part of tests [`e6f4ebe`](https://github.com/inspect-js/is-regex/commit/e6f4ebec26894543747603f2cb360e839f2ca290) + +## v0.0.0 - 2014-01-15 + +### Commits + +- package.json [`aa60d43`](https://github.com/inspect-js/is-regex/commit/aa60d43d2c8adb9fdd47f5898e5e1e570bd238d8) +- read me [`861e944`](https://github.com/inspect-js/is-regex/commit/861e944de88e84010eaa662ea9ea9f17c90cff8c) +- Initial commit [`d0cdd71`](https://github.com/inspect-js/is-regex/commit/d0cdd71a637d8490b7ee3eaaf75c7e31d0f9242f) +- Tests. [`b533f74`](https://github.com/inspect-js/is-regex/commit/b533f741a88dff002790fb7af054b2a74e72d4da) +- Implementation. [`3c9a8c0`](https://github.com/inspect-js/is-regex/commit/3c9a8c06994003cdfffeb3620f251f4c4cae7755) +- Travis CI [`742c440`](https://github.com/inspect-js/is-regex/commit/742c4407015f9108875fd108fde137f5245e9e7a) diff --git a/node_modules/is-regex/LICENSE b/node_modules/is-regex/LICENSE new file mode 100644 index 0000000..47b7b50 --- /dev/null +++ b/node_modules/is-regex/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-regex/README.md b/node_modules/is-regex/README.md new file mode 100644 index 0000000..d61332b --- /dev/null +++ b/node_modules/is-regex/README.md @@ -0,0 +1,52 @@ +# is-regex [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this value a JS regex? +This module works cross-realm/iframe, and despite ES6 @@toStringTag. + +## Example + +```js +var isRegex = require('is-regex'); +var assert = require('assert'); + +assert.notOk(isRegex(undefined)); +assert.notOk(isRegex(null)); +assert.notOk(isRegex(false)); +assert.notOk(isRegex(true)); +assert.notOk(isRegex(42)); +assert.notOk(isRegex('foo')); +assert.notOk(isRegex(function () {})); +assert.notOk(isRegex([])); +assert.notOk(isRegex({})); + +assert.ok(isRegex(/a/g)); +assert.ok(isRegex(new RegExp('a', 'g'))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-regex +[2]: https://versionbadg.es/inspect-js/is-regex.svg +[5]: https://david-dm.org/inspect-js/is-regex.svg +[6]: https://david-dm.org/inspect-js/is-regex +[7]: https://david-dm.org/inspect-js/is-regex/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-regex#info=devDependencies +[11]: https://nodei.co/npm/is-regex.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-regex.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-regex.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-regex +[codecov-image]: https://codecov.io/gh/inspect-js/is-regex/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-regex/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-regex +[actions-url]: https://github.com/inspect-js/is-regex/actions diff --git a/node_modules/is-regex/index.js b/node_modules/is-regex/index.js new file mode 100644 index 0000000..19780f4 --- /dev/null +++ b/node_modules/is-regex/index.js @@ -0,0 +1,58 @@ +'use strict'; + +var callBound = require('call-bind/callBound'); +var hasToStringTag = require('has-tostringtag/shams')(); +var has; +var $exec; +var isRegexMarker; +var badStringifier; + +if (hasToStringTag) { + has = callBound('Object.prototype.hasOwnProperty'); + $exec = callBound('RegExp.prototype.exec'); + isRegexMarker = {}; + + var throwRegexMarker = function () { + throw isRegexMarker; + }; + badStringifier = { + toString: throwRegexMarker, + valueOf: throwRegexMarker + }; + + if (typeof Symbol.toPrimitive === 'symbol') { + badStringifier[Symbol.toPrimitive] = throwRegexMarker; + } +} + +var $toString = callBound('Object.prototype.toString'); +var gOPD = Object.getOwnPropertyDescriptor; +var regexClass = '[object RegExp]'; + +module.exports = hasToStringTag + // eslint-disable-next-line consistent-return + ? function isRegex(value) { + if (!value || typeof value !== 'object') { + return false; + } + + var descriptor = gOPD(value, 'lastIndex'); + var hasLastIndexDataProperty = descriptor && has(descriptor, 'value'); + if (!hasLastIndexDataProperty) { + return false; + } + + try { + $exec(value, badStringifier); + } catch (e) { + return e === isRegexMarker; + } + } + : function isRegex(value) { + // In older browsers, typeof regex incorrectly returns 'function' + if (!value || (typeof value !== 'object' && typeof value !== 'function')) { + return false; + } + + return $toString(value) === regexClass; + }; diff --git a/node_modules/is-regex/package.json b/node_modules/is-regex/package.json new file mode 100644 index 0000000..094fd41 --- /dev/null +++ b/node_modules/is-regex/package.json @@ -0,0 +1,86 @@ +{ + "name": "is-regex", + "version": "1.1.4", + "description": "Is this value a JS regex? Works cross-realm/iframe, and despite ES6 @@toStringTag", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only && npm run test:harmony", + "tests-only": "nyc node test", + "test:harmony": "nyc node --harmony --es-staging test", + "test:corejs": "nyc tape test-corejs.js", + "posttest": "npx aud --production", + "lint": "eslint .", + "eccheck": "eclint check *.js **/*.js > /dev/null", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-regex.git" + }, + "bugs": { + "url": "https://github.com/inspect-js/is-regex/issues" + }, + "homepage": "https://github.com/inspect-js/is-regex", + "keywords": [ + "regex", + "regexp", + "is", + "regular expression", + "regular", + "expression" + ], + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "core-js": "^3.16.0", + "eclint": "^2.8.1", + "eslint": "^7.32.0", + "foreach": "^2.0.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/is-regex/test/index.js b/node_modules/is-regex/test/index.js new file mode 100644 index 0000000..f6c0802 --- /dev/null +++ b/node_modules/is-regex/test/index.js @@ -0,0 +1,104 @@ +'use strict'; + +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('foreach'); +var test = require('tape'); +var isRegex = require('..'); + +test('not regexes', function (t) { + t.notOk(isRegex(), 'undefined is not regex'); + t.notOk(isRegex(null), 'null is not regex'); + t.notOk(isRegex(false), 'false is not regex'); + t.notOk(isRegex(true), 'true is not regex'); + t.notOk(isRegex(42), 'number is not regex'); + t.notOk(isRegex('foo'), 'string is not regex'); + t.notOk(isRegex([]), 'array is not regex'); + t.notOk(isRegex({}), 'object is not regex'); + t.notOk(isRegex(function () {}), 'function is not regex'); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + var regex = /a/g; + var fakeRegex = { + toString: function () { return String(regex); }, + valueOf: function () { return regex; } + }; + fakeRegex[Symbol.toStringTag] = 'RegExp'; + t.notOk(isRegex(fakeRegex), 'fake RegExp with @@toStringTag "RegExp" is not regex'); + t.end(); +}); + +test('regexes', function (t) { + t.ok(isRegex(/a/g), 'regex literal is regex'); + t.ok(isRegex(new RegExp('a', 'g')), 'regex object is regex'); + t.end(); +}); + +test('does not mutate regexes', function (t) { + t.test('lastIndex is a marker object', function (st) { + var regex = /a/; + var marker = {}; + regex.lastIndex = marker; + st.equal(regex.lastIndex, marker, 'lastIndex is the marker object'); + st.ok(isRegex(regex), 'is regex'); + st.equal(regex.lastIndex, marker, 'lastIndex is the marker object after isRegex'); + st.end(); + }); + + t.test('lastIndex is nonzero', function (st) { + var regex = /a/; + regex.lastIndex = 3; + st.equal(regex.lastIndex, 3, 'lastIndex is 3'); + st.ok(isRegex(regex), 'is regex'); + st.equal(regex.lastIndex, 3, 'lastIndex is 3 after isRegex'); + st.end(); + }); + + t.end(); +}); + +test('does not perform operations observable to Proxies', { skip: typeof Proxy !== 'function' }, function (t) { + var Handler = function () { + this.trapCalls = []; + }; + + forEach([ + 'defineProperty', + 'deleteProperty', + 'get', + 'getOwnPropertyDescriptor', + 'getPrototypeOf', + 'has', + 'isExtensible', + 'ownKeys', + 'preventExtensions', + 'set', + 'setPrototypeOf' + ], function (trapName) { + Handler.prototype[trapName] = function () { + this.trapCalls.push(trapName); + return Reflect[trapName].apply(Reflect, arguments); + }; + }); + + t.test('proxy of object', function (st) { + var handler = new Handler(); + var proxy = new Proxy({ lastIndex: 0 }, handler); + + st.equal(isRegex(proxy), false, 'proxy of plain object is not regex'); + st.deepEqual(handler.trapCalls, ['getOwnPropertyDescriptor'], 'no unexpected proxy traps were triggered'); + st.end(); + }); + + t.test('proxy of RegExp instance', function (st) { + var handler = new Handler(); + var proxy = new Proxy(/a/, handler); + + st.equal(isRegex(proxy), false, 'proxy of RegExp instance is not regex'); + st.deepEqual(handler.trapCalls, ['getOwnPropertyDescriptor'], 'no unexpected proxy traps were triggered'); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/is-shared-array-buffer/.eslintignore b/node_modules/is-shared-array-buffer/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-shared-array-buffer/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-shared-array-buffer/.eslintrc b/node_modules/is-shared-array-buffer/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/is-shared-array-buffer/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/is-shared-array-buffer/.github/FUNDING.yml b/node_modules/is-shared-array-buffer/.github/FUNDING.yml new file mode 100644 index 0000000..61db3c4 --- /dev/null +++ b/node_modules/is-shared-array-buffer/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-shared-array-buffer +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-shared-array-buffer/.nycrc b/node_modules/is-shared-array-buffer/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-shared-array-buffer/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-shared-array-buffer/CHANGELOG.md b/node_modules/is-shared-array-buffer/CHANGELOG.md new file mode 100644 index 0000000..6536f8f --- /dev/null +++ b/node_modules/is-shared-array-buffer/CHANGELOG.md @@ -0,0 +1,44 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/inspect-js/is-shared-array-buffer/compare/v1.0.1...v1.0.2) - 2022-04-01 + +### Commits + +- [actions] reuse common workflows [`48d01e6`](https://github.com/inspect-js/is-shared-array-buffer/commit/48d01e690f76c92f5c9072fbcb9b6215402db8a7) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`7b0e12a`](https://github.com/inspect-js/is-shared-array-buffer/commit/7b0e12a4e8f5db8eac586be68c879119a4a12e7a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `safe-publish-latest`, `tape` [`8d57a8e`](https://github.com/inspect-js/is-shared-array-buffer/commit/8d57a8e1d9ce093f04f83e196ca7c80a02617939) +- [readme] update URLs [`dca4d27`](https://github.com/inspect-js/is-shared-array-buffer/commit/dca4d27d35352309da5abb4feb584158004008cf) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`2a7bb99`](https://github.com/inspect-js/is-shared-array-buffer/commit/2a7bb990610d7f6c058bdae7f21c49cc7276848f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `object-inspect`, `safe-publish-latest`, `tape` [`389c6db`](https://github.com/inspect-js/is-shared-array-buffer/commit/389c6db4311a85a84fd4cb75646f26023b0c1685) +- [actions] update codecov uploader [`b9661f9`](https://github.com/inspect-js/is-shared-array-buffer/commit/b9661f9ac2e1e002372b9b1e136faca837a6647f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect` [`f99cd48`](https://github.com/inspect-js/is-shared-array-buffer/commit/f99cd4827e23bc893ed711cbffe28f3e51a4d401) +- [readme] add actions and codecov badges [`9515ed2`](https://github.com/inspect-js/is-shared-array-buffer/commit/9515ed2184a3ed1ce913b92b5092884dad5ac794) +- [Fix] add missing `call-bind` dependency [`cff5358`](https://github.com/inspect-js/is-shared-array-buffer/commit/cff53582740f9f053ec67e1acbf2bafc83bdb7b5) +- [meta] add `safe-publish-latest`; use `prepublishOnly` script for npm 7+ [`ba0b719`](https://github.com/inspect-js/is-shared-array-buffer/commit/ba0b7190a42d4290d31a5fce215e874da573dd77) + +## [v1.0.1](https://github.com/inspect-js/is-shared-array-buffer/compare/v1.0.0...v1.0.1) - 2021-03-04 + +### Commits + +- [readme] fix repo URLs [`37c38f3`](https://github.com/inspect-js/is-shared-array-buffer/commit/37c38f347392da177197dd2fd518b61240a56203) + +## v1.0.0 - 2021-03-04 + +### Commits + +- [Tests] add tests [`9c7b806`](https://github.com/inspect-js/is-shared-array-buffer/commit/9c7b806ab1528814308a7420f8198644f55c916f) +- Initial commit [`4e65c5e`](https://github.com/inspect-js/is-shared-array-buffer/commit/4e65c5ecdaa255162bc6507de4ff98cea2472e3b) +- [meta] do not publish github action workflow files [`ac3693d`](https://github.com/inspect-js/is-shared-array-buffer/commit/ac3693db8ec26db5444ef4b46aa38a81e8841d30) +- readme [`7a984d0`](https://github.com/inspect-js/is-shared-array-buffer/commit/7a984d0db73b77943f6731098134e3351a36793b) +- npm init [`a586c99`](https://github.com/inspect-js/is-shared-array-buffer/commit/a586c99316f3c8ae4fd5125621ea933e97a1bf1b) +- [actions] add automatic rebasing / merge commit blocking [`184fe62`](https://github.com/inspect-js/is-shared-array-buffer/commit/184fe622680d523e89ac322fa1a52dbba46a8fc0) +- Implementation [`207e26d`](https://github.com/inspect-js/is-shared-array-buffer/commit/207e26d1128930f28384cb213b38d69fd52bbd7c) +- [meta] create `FUNDING.yml`; add "funding" field [`3cad3fc`](https://github.com/inspect-js/is-shared-array-buffer/commit/3cad3fc9509f91fbc71e84565529f53a94d538d4) +- [meta] add auto-changelog [`31f1f2c`](https://github.com/inspect-js/is-shared-array-buffer/commit/31f1f2cbcd616d6c09089d62198d5cc775053324) +- [Tests] add `npm run lint` [`2e5146e`](https://github.com/inspect-js/is-shared-array-buffer/commit/2e5146e18f44533382a781fa09a50d4f47caa0e5) +- Only apps should have lockfiles [`7b2adfa`](https://github.com/inspect-js/is-shared-array-buffer/commit/7b2adfad6dcd95271ab6ba34658a9a1a21dbeacf) diff --git a/node_modules/is-shared-array-buffer/LICENSE b/node_modules/is-shared-array-buffer/LICENSE new file mode 100644 index 0000000..7948bc0 --- /dev/null +++ b/node_modules/is-shared-array-buffer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/is-shared-array-buffer/README.md b/node_modules/is-shared-array-buffer/README.md new file mode 100644 index 0000000..c2b6710 --- /dev/null +++ b/node_modules/is-shared-array-buffer/README.md @@ -0,0 +1,58 @@ +# is-shared-array-buffer [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Is this value a JS SharedArrayBuffer? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag. + +## Example + +```js +var assert = require('assert'); +var isSharedArrayBuffer = require('is-shared-array-buffer'); + +assert(!isSharedArrayBuffer(function () {})); +assert(!isSharedArrayBuffer(null)); +assert(!isSharedArrayBuffer(function* () { yield 42; return Infinity; }); +assert(!isSharedArrayBuffer(Symbol('foo'))); +assert(!isSharedArrayBuffer(1n)); +assert(!isSharedArrayBuffer(Object(1n))); + +assert(!isSharedArrayBuffer(new Set())); +assert(!isSharedArrayBuffer(new WeakSet())); +assert(!isSharedArrayBuffer(new Map())); +assert(!isSharedArrayBuffer(new WeakMap())); +assert(!isSharedArrayBuffer(new WeakRef({}))); +assert(!isSharedArrayBuffer(new FinalizationRegistry(() => {}))); +assert(!isSharedArrayBuffer(new ArrayBuffer())); + +assert(isSharedArrayBuffer(new SharedArrayBuffer())); + +class MySharedArrayBuffer extends SharedArrayBuffer {} +assert(isSharedArrayBuffer(new MySharedArrayBuffer())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/is-shared-array-buffer +[npm-version-svg]: https://versionbadg.es/inspect-js/is-shared-array-buffer.svg +[deps-svg]: https://david-dm.org/inspect-js/is-shared-array-buffer.svg +[deps-url]: https://david-dm.org/inspect-js/is-shared-array-buffer +[dev-deps-svg]: https://david-dm.org/inspect-js/is-shared-array-buffer/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/is-shared-array-buffer#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/is-shared-array-buffer.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-shared-array-buffer.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-shared-array-buffer.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-shared-array-buffer +[codecov-image]: https://codecov.io/gh/inspect-js/is-shared-array-buffer/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-shared-array-buffer/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-shared-array-buffer +[actions-url]: https://github.com/inspect-js/is-shared-array-buffer/actions diff --git a/node_modules/is-shared-array-buffer/index.js b/node_modules/is-shared-array-buffer/index.js new file mode 100644 index 0000000..8704304 --- /dev/null +++ b/node_modules/is-shared-array-buffer/index.js @@ -0,0 +1,21 @@ +'use strict'; + +var callBound = require('call-bind/callBound'); + +var $byteLength = callBound('SharedArrayBuffer.prototype.byteLength', true); + +module.exports = $byteLength + ? function isSharedArrayBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + try { + $byteLength(obj); + return true; + } catch (e) { + return false; + } + } + : function isSharedArrayBuffer(obj) { // eslint-disable-line no-unused-vars + return false; + }; diff --git a/node_modules/is-shared-array-buffer/package.json b/node_modules/is-shared-array-buffer/package.json new file mode 100644 index 0000000..511a9f6 --- /dev/null +++ b/node_modules/is-shared-array-buffer/package.json @@ -0,0 +1,70 @@ +{ + "name": "is-shared-array-buffer", + "version": "1.0.2", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "Is this value a JS SharedArrayBuffer?", + "license": "MIT", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only --", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/is-shared-array-buffer.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "is", + "sharedarraybuffer", + "shared", + "array", + "buffer" + ], + "bugs": { + "url": "https://github.com/inspect-js/is-shared-array-buffer/issues" + }, + "homepage": "https://github.com/inspect-js/is-shared-array-buffer#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.2.3", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.2.1", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "nyc": "^10.3.2", + "object-inspect": "^1.12.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.2" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "call-bind": "^1.0.2" + } +} diff --git a/node_modules/is-shared-array-buffer/test/index.js b/node_modules/is-shared-array-buffer/test/index.js new file mode 100644 index 0000000..9bc2c56 --- /dev/null +++ b/node_modules/is-shared-array-buffer/test/index.js @@ -0,0 +1,27 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var forEach = require('for-each'); +var v = require('es-value-fixtures'); + +var isSharedArrayBuffer = require('..'); + +test('isSharedArrayBuffer', function (t) { + t.equal(typeof isSharedArrayBuffer, 'function', 'is a function'); + + var nonSABs = v.primitives.concat(v.objects); + forEach(nonSABs, function (nonSAB) { + t.equal(isSharedArrayBuffer(nonSAB), false, inspect(nonSAB) + ' is not a SharedArrayBuffer'); + }); + + t.test('actual SharedArrayBuffer instances', { skip: typeof SharedArrayBuffer === 'undefined' }, function (st) { + var sab = new SharedArrayBuffer(); + + st.equal(isSharedArrayBuffer(sab), true, inspect(sab) + ' is a SharedArrayBuffer'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/is-stream/index.d.ts b/node_modules/is-stream/index.d.ts new file mode 100644 index 0000000..eee2e83 --- /dev/null +++ b/node_modules/is-stream/index.d.ts @@ -0,0 +1,79 @@ +import * as stream from 'stream'; + +declare const isStream: { + /** + @returns Whether `stream` is a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream(fs.createReadStream('unicorn.png')); + //=> true + + isStream({}); + //=> false + ``` + */ + (stream: unknown): stream is stream.Stream; + + /** + @returns Whether `stream` is a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.writable(fs.createWriteStrem('unicorn.txt')); + //=> true + ``` + */ + writable(stream: unknown): stream is stream.Writable; + + /** + @returns Whether `stream` is a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.readable(fs.createReadStream('unicorn.png')); + //=> true + ``` + */ + readable(stream: unknown): stream is stream.Readable; + + /** + @returns Whether `stream` is a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + + @example + ``` + import {Duplex} from 'stream'; + import isStream = require('is-stream'); + + isStream.duplex(new Duplex()); + //=> true + ``` + */ + duplex(stream: unknown): stream is stream.Duplex; + + /** + @returns Whether `stream` is a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + + @example + ``` + import * as fs from 'fs'; + import Stringify = require('streaming-json-stringify'); + import isStream = require('is-stream'); + + isStream.transform(Stringify()); + //=> true + ``` + */ + transform(input: unknown): input is stream.Transform; +}; + +export = isStream; diff --git a/node_modules/is-stream/index.js b/node_modules/is-stream/index.js new file mode 100644 index 0000000..2e43434 --- /dev/null +++ b/node_modules/is-stream/index.js @@ -0,0 +1,28 @@ +'use strict'; + +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); + +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function'; + +module.exports = isStream; diff --git a/node_modules/is-stream/license b/node_modules/is-stream/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/is-stream/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-stream/package.json b/node_modules/is-stream/package.json new file mode 100644 index 0000000..c3b5673 --- /dev/null +++ b/node_modules/is-stream/package.json @@ -0,0 +1,42 @@ +{ + "name": "is-stream", + "version": "2.0.1", + "description": "Check if something is a Node.js stream", + "license": "MIT", + "repository": "sindresorhus/is-stream", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "stream", + "type", + "streams", + "writable", + "readable", + "duplex", + "transform", + "check", + "detect", + "is" + ], + "devDependencies": { + "@types/node": "^11.13.6", + "ava": "^1.4.1", + "tempy": "^0.3.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-stream/readme.md b/node_modules/is-stream/readme.md new file mode 100644 index 0000000..19308e7 --- /dev/null +++ b/node_modules/is-stream/readme.md @@ -0,0 +1,60 @@ +# is-stream + +> Check if something is a [Node.js stream](https://nodejs.org/api/stream.html) + +## Install + +``` +$ npm install is-stream +``` + +## Usage + +```js +const fs = require('fs'); +const isStream = require('is-stream'); + +isStream(fs.createReadStream('unicorn.png')); +//=> true + +isStream({}); +//=> false +``` + +## API + +### isStream(stream) + +Returns a `boolean` for whether it's a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + +#### isStream.writable(stream) + +Returns a `boolean` for whether it's a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + +#### isStream.readable(stream) + +Returns a `boolean` for whether it's a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +#### isStream.duplex(stream) + +Returns a `boolean` for whether it's a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + +#### isStream.transform(stream) + +Returns a `boolean` for whether it's a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + +## Related + +- [is-file-stream](https://github.com/jamestalmage/is-file-stream) - Detect if a stream is a file stream + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/is-string/.eslintignore b/node_modules/is-string/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-string/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-string/.eslintrc b/node_modules/is-string/.eslintrc new file mode 100644 index 0000000..5bf1191 --- /dev/null +++ b/node_modules/is-string/.eslintrc @@ -0,0 +1,19 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "max-statements": [2, 15] + }, + + "overrides": [ + { + "files": ["test.js"], + "rules": { + "no-magic-numbers": 0, + }, + }, + ], +} diff --git a/node_modules/is-string/.github/FUNDING.yml b/node_modules/is-string/.github/FUNDING.yml new file mode 100644 index 0000000..519746b --- /dev/null +++ b/node_modules/is-string/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-string +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-string/.nycrc b/node_modules/is-string/.nycrc new file mode 100644 index 0000000..a69aa2d --- /dev/null +++ b/node_modules/is-string/.nycrc @@ -0,0 +1,10 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test", + "test-corejs.js" + ] +} diff --git a/node_modules/is-string/CHANGELOG.md b/node_modules/is-string/CHANGELOG.md new file mode 100644 index 0000000..6f62043 --- /dev/null +++ b/node_modules/is-string/CHANGELOG.md @@ -0,0 +1,114 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). + +## [v1.0.7](https://github.com/inspect-js/is-string/compare/v1.0.6...v1.0.7) - 2021-08-05 + +### Commits + +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`d973ffd`](https://github.com/inspect-js/is-string/commit/d973ffd2268e10c0e2cd4f0c57ecf8ce0a8d8578) +- [Dev Deps] update `auto-changelog`, `core-js`, `eslint`, `tape` [`4bfaabf`](https://github.com/inspect-js/is-string/commit/4bfaabf877e874ca21d2c44be26f13add8ee2761) + +## [v1.0.6](https://github.com/inspect-js/is-string/compare/v1.0.5...v1.0.6) - 2021-05-07 + +### Commits + +- [Tests] migrate tests to Github Actions [`c7790c8`](https://github.com/inspect-js/is-string/commit/c7790c89e5077251fe7ca32ac29eeee02f1b2751) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`1e52bbd`](https://github.com/inspect-js/is-string/commit/1e52bbd19b1608f6932c0335d9981824584c3186) +- [Fix] do not use `Object.prototype.toString` when `Symbol.toStringTag` is shammed [`83337eb`](https://github.com/inspect-js/is-string/commit/83337ebf55308b7bb9c1befae420760e0f8d8016) +- [meta] do not publish github action workflow files [`b25aea2`](https://github.com/inspect-js/is-string/commit/b25aea2e8a53ed9e9090cf96481590cdc00a0957) +- [readme] update badges [`759ccd9`](https://github.com/inspect-js/is-string/commit/759ccd94de4a2000231a179f91af6b5c12c11e00) +- [Tests] run `nyc` on all tests [`dc02f70`](https://github.com/inspect-js/is-string/commit/dc02f7080c355f0d24368c1622db09f7cc30cdbd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `tape`; add `aud` [`a0f76fa`](https://github.com/inspect-js/is-string/commit/a0f76fa1990bb580948f9e2daa89bdcda3fae7f0) +- [actions] add "Allow Edits" workflow [`9ec3902`](https://github.com/inspect-js/is-string/commit/9ec390295b4faef7744d2b579c1050be66168cb7) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`57fbe21`](https://github.com/inspect-js/is-string/commit/57fbe215da83a3b601855a9c6543ad1a96de5702) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`191e55f`](https://github.com/inspect-js/is-string/commit/191e55ff1fa782654ffcce2df922e23345b56690) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`1ea2b81`](https://github.com/inspect-js/is-string/commit/1ea2b81e866775a7890e75c44c742204124aa354) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`105d1b9`](https://github.com/inspect-js/is-string/commit/105d1b9851e366ef23c2a27d4064e0d36da25939) +- [Dev Deps] update `auto-changelog`, `tape`; add `aud` [`114cfad`](https://github.com/inspect-js/is-string/commit/114cfad854d8860421f847cd99a3bdb8ef1353dc) +- [meta] use `prepublishOnly` script for npm 7+ [`fc38f26`](https://github.com/inspect-js/is-string/commit/fc38f26adb486f50880c5771d145ab2bffb6247a) +- [meta] gitignore coverage output [`3419127`](https://github.com/inspect-js/is-string/commit/34191278f1fa09ba4da801a6fd7a32e31050e759) +- [actions] update rebase action to use checkout v2 [`334eca0`](https://github.com/inspect-js/is-string/commit/334eca02d40f4cf7dc15a8e7d5ff06852028abb5) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`7a332e9`](https://github.com/inspect-js/is-string/commit/7a332e963f1ab717fafa671e0fa8a1b20c53d861) +- [meta] remove explicit audit level config [`04630b1`](https://github.com/inspect-js/is-string/commit/04630b1b535084322ddeae8efb79a8810d7cf325) + +## [v1.0.5](https://github.com/inspect-js/is-string/compare/v1.0.4...v1.0.5) - 2019-12-18 + +### Commits + +- [Tests] use shared travis-ci configs [`4121d6b`](https://github.com/inspect-js/is-string/commit/4121d6b168ae1d54a81791ee6877f9813cab6253) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v5.12`, `v4.9`; use `nvm install-latest-npm` [`e7a3e89`](https://github.com/inspect-js/is-string/commit/e7a3e89ccb9638d73f45dbcb2a42e509bd3153c4) +- Update `eslint`, `tape`, `semver`; use my personal shared `eslint` config [`6c380a7`](https://github.com/inspect-js/is-string/commit/6c380a70011714370e754fa0df95f56cdcaa3e60) +- [Tests] remove `jscs` [`3d49592`](https://github.com/inspect-js/is-string/commit/3d49592b9880fcb1a23b67286445281131a553e3) +- Update `is`, `tape`, `covert`, `jscs`, `editorconfig-tools`, `eslint`, `nsp`, `semver`. [`cc6983d`](https://github.com/inspect-js/is-string/commit/cc6983d06bc98f4ae9b7c9439d5d73c7318d8acd) +- [meta] add `auto-changelog` [`b857897`](https://github.com/inspect-js/is-string/commit/b85789723ce3a7064536598e0fcdd495257c6134) +- [meta] remove unused Makefile and associated utilities [`3f0f51c`](https://github.com/inspect-js/is-string/commit/3f0f51cbae1f97dbe1466eee88d105b3df0d2f0a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is`, `covert`, `tape`, `semver` [`9d4a95e`](https://github.com/inspect-js/is-string/commit/9d4a95e4473fe8195501878525b5af5948aa45c9) +- Update `eslint` [`e861b4b`](https://github.com/inspect-js/is-string/commit/e861b4bc71f5390670aebdff91119a1f8aeeb88a) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`172e2dd`](https://github.com/inspect-js/is-string/commit/172e2dd1a0b9eb042bcb9a80ff5e774a90ff0695) +- Test on `node` and `io.js` latest. [`fd426cd`](https://github.com/inspect-js/is-string/commit/fd426cd18b22b0d0e1731598125393dcfe0c5704) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` [`23bdf83`](https://github.com/inspect-js/is-string/commit/23bdf83cf42138eba09f45bd0b040b069f9839d4) +- [actions] add automatic rebasing / merge commit blocking [`96153c0`](https://github.com/inspect-js/is-string/commit/96153c0d687a7fda2261f4c02add5d0b41e8aed7) +- [meta] create FUNDING.yml [`66ae246`](https://github.com/inspect-js/is-string/commit/66ae246d6cdaa4ccbc21f7c144b672139b8ccef6) +- [Dev Deps] update `is`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`817361a`](https://github.com/inspect-js/is-string/commit/817361a9673cd1ec9854b52578a980159f7d8701) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `semver`, `tape` [`fc35d3f`](https://github.com/inspect-js/is-string/commit/fc35d3feb40921bb22e1639903cb7f2fab77814b) +- [Dev Deps] update `jscs` [`886767e`](https://github.com/inspect-js/is-string/commit/886767e04e5ad59ac0bc926a87233cc8546c8b4f) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`3410922`](https://github.com/inspect-js/is-string/commit/341092203c11a3b92eee55a7ecb7b8265e8fcecd) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`4d6c73b`](https://github.com/inspect-js/is-string/commit/4d6c73b507bcd39050ef71e554069f72fc5b222a) +- Update `nsp`, `eslint` [`b11de49`](https://github.com/inspect-js/is-string/commit/b11de4910beee1ffe1e67fbe25ec6707ca796b27) +- Update `eslint`, `semver` [`0777977`](https://github.com/inspect-js/is-string/commit/0777977757a85a1db75831d03a14b4b1fde05d7e) +- Only apps should have lockfiles [`78b49ff`](https://github.com/inspect-js/is-string/commit/78b49ffd04d4cd8c57d9e7b485421fbf3641b41b) +- [meta] add `funding` field [`81328a6`](https://github.com/inspect-js/is-string/commit/81328a6ef3eee989164127e4c0c82f1da73d3567) +- [Dev Deps] update `eslint`, `tape` [`fc9a225`](https://github.com/inspect-js/is-string/commit/fc9a225b27935f7c9c2704281d7fddd3614d3cb8) +- [Tests] use `eclint` instead of `editorconfig-tools` [`59c2c61`](https://github.com/inspect-js/is-string/commit/59c2c610dbd8e8ca1e4aa3fa9c9f93205cab9b07) +- [Dev Deps] Update `tape`, `eslint` [`a429816`](https://github.com/inspect-js/is-string/commit/a429816688e23c81948b4ae72324c26c27849b7c) +- Test on `io.js` `v2.2` [`08b476e`](https://github.com/inspect-js/is-string/commit/08b476ed0734a70e3091c04ddd2f173a2df21eb2) +- Test up to `io.js` `v3.0` [`22637ef`](https://github.com/inspect-js/is-string/commit/22637ef9e0030533df85cf1992fc099a88b1924c) +- [meta] add `safe-publish-latest` [`20ccb48`](https://github.com/inspect-js/is-string/commit/20ccb48fd85f0245eb893507d00003090da020d0) +- [Dev Deps] update `tape` [`06b58a0`](https://github.com/inspect-js/is-string/commit/06b58a048c2a820e5611ad2bd9ddfbe893295a57) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`ea7cf84`](https://github.com/inspect-js/is-string/commit/ea7cf849b952c924d1687a302098251a7b827c80) +- Test on `io.js` `v2.4` [`66ec3ea`](https://github.com/inspect-js/is-string/commit/66ec3ea390b364583a792799b53857fd186ccc88) +- Test on `io.js` `v2.3` [`ca6e796`](https://github.com/inspect-js/is-string/commit/ca6e796f16ec433b88962162fde8012f28e18f1e) +- Fix tests for faked @@toStringTag [`3cce832`](https://github.com/inspect-js/is-string/commit/3cce8329133dfd233987359df151018b3b136be1) + +## [v1.0.4](https://github.com/inspect-js/is-string/compare/v1.0.3...v1.0.4) - 2015-01-29 + +### Commits + +- If @@toStringTag is not present, use the old-school Object#toString test. [`30675ec`](https://github.com/inspect-js/is-string/commit/30675ecb5c5cc43873918661a414a1d0f8b77325) + +## [v1.0.3](https://github.com/inspect-js/is-string/compare/v1.0.2...v1.0.3) - 2015-01-29 + +### Commits + +- Refactor to aid optimization of non-try/catch code. [`9b2772a`](https://github.com/inspect-js/is-string/commit/9b2772abe09ba8cbaa631322cc226ee906d2db22) + +## [v1.0.2](https://github.com/inspect-js/is-string/compare/v1.0.1...v1.0.2) - 2015-01-29 + +### Commits + +- Fix broken package.json [`dc921d3`](https://github.com/inspect-js/is-string/commit/dc921d332b64e4041162f04e4712b0dc687863a5) + +## [v1.0.1](https://github.com/inspect-js/is-string/compare/v1.0.0...v1.0.1) - 2015-01-29 + +### Commits + +- Fix eslint config. [`c4e05bd`](https://github.com/inspect-js/is-string/commit/c4e05bd171da6002d432e451fd48912db8b048e0) +- Add early exits for typeof "string", or typeof not "object". [`82f41d3`](https://github.com/inspect-js/is-string/commit/82f41d36a599bc6a06152792c84c7683e412c513) + +## v1.0.0 - 2015-01-29 + +### Commits + +- Dotfiles. [`45bc9dd`](https://github.com/inspect-js/is-string/commit/45bc9dd60201722344986a6c7536be9ea9ccefbf) +- `make release` [`23707f5`](https://github.com/inspect-js/is-string/commit/23707f5ecfdf00afb0e57c06ac07f7f49cdeb606) +- package.json [`575ad81`](https://github.com/inspect-js/is-string/commit/575ad811c61b156cfbcc60ff61947183c6ebe6a2) +- Read me [`3f67c9a`](https://github.com/inspect-js/is-string/commit/3f67c9a0725f811845d38646a19322895cd03981) +- Initial commit [`2c26a7a`](https://github.com/inspect-js/is-string/commit/2c26a7a2e41dec77be2c59d5847f29a6ab7c0b29) +- Tests. [`38c987b`](https://github.com/inspect-js/is-string/commit/38c987b8513b0ac03b0897e0fce7de8135d4ee0f) +- Implementation. [`0471d59`](https://github.com/inspect-js/is-string/commit/0471d59078d7f3f77619913ec21c57c0af27114c) diff --git a/node_modules/is-string/LICENSE b/node_modules/is-string/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/node_modules/is-string/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/is-string/README.md b/node_modules/is-string/README.md new file mode 100644 index 0000000..d9d7edf --- /dev/null +++ b/node_modules/is-string/README.md @@ -0,0 +1,56 @@ +# is-string [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this value a JS String object or primitive? This module works cross-realm/iframe, and despite ES6 @@toStringTag. + +## Example + +```js +var isString = require('is-string'); +var assert = require('assert'); + +assert.notOk(isString(undefined)); +assert.notOk(isString(null)); +assert.notOk(isString(false)); +assert.notOk(isString(true)); +assert.notOk(isString(function () {})); +assert.notOk(isString([])); +assert.notOk(isString({})); +assert.notOk(isString(/a/g)); +assert.notOk(isString(new RegExp('a', 'g'))); +assert.notOk(isString(new Date())); +assert.notOk(isString(42)); +assert.notOk(isString(NaN)); +assert.notOk(isString(Infinity)); +assert.notOk(isString(new Number(42))); + +assert.ok(isString('foo')); +assert.ok(isString(Object('foo'))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-string +[2]: https://versionbadg.es/inspect-js/is-string.svg +[5]: https://david-dm.org/inspect-js/is-string.svg +[6]: https://david-dm.org/inspect-js/is-string +[7]: https://david-dm.org/inspect-js/is-string/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-string#info=devDependencies +[11]: https://nodei.co/npm/is-string.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-string.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-string.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-string +[codecov-image]: https://codecov.io/gh/inspect-js/is-string/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-string/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-string +[actions-url]: https://github.com/inspect-js/is-string/actions diff --git a/node_modules/is-string/index.js b/node_modules/is-string/index.js new file mode 100644 index 0000000..f44f7bb --- /dev/null +++ b/node_modules/is-string/index.js @@ -0,0 +1,24 @@ +'use strict'; + +var strValue = String.prototype.valueOf; +var tryStringObject = function tryStringObject(value) { + try { + strValue.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var strClass = '[object String]'; +var hasToStringTag = require('has-tostringtag/shams')(); + +module.exports = function isString(value) { + if (typeof value === 'string') { + return true; + } + if (typeof value !== 'object') { + return false; + } + return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass; +}; diff --git a/node_modules/is-string/package.json b/node_modules/is-string/package.json new file mode 100644 index 0000000..9b36548 --- /dev/null +++ b/node_modules/is-string/package.json @@ -0,0 +1,81 @@ +{ + "name": "is-string", + "version": "1.0.7", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "Is this value a JS String object or primitive? This module works cross-realm/iframe, and despite ES6 @@toStringTag.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test:corejs": "nyc tape test-corejs.js", + "test": "npm run tests-only && npm run test:corejs", + "posttest": "npx aud --production", + "lint": "eslint .", + "eccheck": "eclint check *.js **/*.js > /dev/null", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/ljharb/is-string.git" + }, + "keywords": [ + "String", + "string", + "ES6", + "toStringTag", + "@@toStringTag", + "String object" + ], + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "core-js": "^3.16.0", + "eclint": "^2.8.1", + "eslint": "^7.32.0", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false + } +} diff --git a/node_modules/is-string/test/index.js b/node_modules/is-string/test/index.js new file mode 100644 index 0000000..5239dfa --- /dev/null +++ b/node_modules/is-string/test/index.js @@ -0,0 +1,39 @@ +'use strict'; + +var test = require('tape'); +var isString = require('../'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('not Strings', function (t) { + t.notOk(isString(), 'undefined is not String'); + t.notOk(isString(null), 'null is not String'); + t.notOk(isString(false), 'false is not String'); + t.notOk(isString(true), 'true is not String'); + t.notOk(isString([]), 'array is not String'); + t.notOk(isString({}), 'object is not String'); + t.notOk(isString(function () {}), 'function is not String'); + t.notOk(isString(/a/g), 'regex literal is not String'); + t.notOk(isString(new RegExp('a', 'g')), 'regex object is not String'); + t.notOk(isString(new Date()), 'new Date() is not String'); + t.notOk(isString(42), 'number is not String'); + t.notOk(isString(Object(42)), 'number object is not String'); + t.notOk(isString(NaN), 'NaN is not String'); + t.notOk(isString(Infinity), 'Infinity is not String'); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + var fakeString = { + toString: function () { return '7'; }, + valueOf: function () { return '42'; } + }; + fakeString[Symbol.toStringTag] = 'String'; + t.notOk(isString(fakeString), 'fake String with @@toStringTag "String" is not String'); + t.end(); +}); + +test('Strings', function (t) { + t.ok(isString('foo'), 'string primitive is String'); + t.ok(isString(Object('foo')), 'string object is String'); + t.end(); +}); diff --git a/node_modules/is-symbol/.editorconfig b/node_modules/is-symbol/.editorconfig new file mode 100644 index 0000000..eaa2141 --- /dev/null +++ b/node_modules/is-symbol/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/node_modules/is-symbol/.eslintignore b/node_modules/is-symbol/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-symbol/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-symbol/.eslintrc b/node_modules/is-symbol/.eslintrc new file mode 100644 index 0000000..046dd07 --- /dev/null +++ b/node_modules/is-symbol/.eslintrc @@ -0,0 +1,14 @@ +{ + "root": true, + + "extends": "@ljharb", + + "overrides": [ + { + "files": "test/**", + "rules": { + "no-restricted-properties": 0, + }, + }, + ], +} diff --git a/node_modules/is-symbol/.github/FUNDING.yml b/node_modules/is-symbol/.github/FUNDING.yml new file mode 100644 index 0000000..a65600e --- /dev/null +++ b/node_modules/is-symbol/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-symbol +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-symbol/.nycrc b/node_modules/is-symbol/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-symbol/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-symbol/CHANGELOG.md b/node_modules/is-symbol/CHANGELOG.md new file mode 100644 index 0000000..ce8dd99 --- /dev/null +++ b/node_modules/is-symbol/CHANGELOG.md @@ -0,0 +1,113 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/inspect-js/is-symbol/compare/v1.0.3...v1.0.4) - 2021-05-08 + +### Commits + +- [Tests] migrate tests to Github Actions [`997d43c`](https://github.com/inspect-js/is-symbol/commit/997d43c091d1f8d3a2b3d7dfb17a73cdc5a75dde) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`fe0ccb7`](https://github.com/inspect-js/is-symbol/commit/fe0ccb7b7b64e74e095ef782dcc1d24d6c4b0be4) +- [meta] remove unused Makefile and associated utilities [`3ab2748`](https://github.com/inspect-js/is-symbol/commit/3ab2748ab6c2de21fc24f131bb880c68ba0b7b34) +- [meta] do not publish github action workflow files [`f20fafe`](https://github.com/inspect-js/is-symbol/commit/f20fafeb21585c7b4871ea19f104fd7696734fe8) +- [Tests] run `nyc` on all tests [`5c332fc`](https://github.com/inspect-js/is-symbol/commit/5c332fc92cecbed4a2041bc0c52b991b4a593f34) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c5a58a8`](https://github.com/inspect-js/is-symbol/commit/c5a58a8bea390a9b02e1c8c4aac30c223370297b) +- [readme] fix repo URLs; remove travis badge [`bcd9258`](https://github.com/inspect-js/is-symbol/commit/bcd9258d161fe709148fcc47962df3372c544727) +- [actions] add "Allow Edits" workflow [`33ae2d3`](https://github.com/inspect-js/is-symbol/commit/33ae2d3940e9daa6003a84c232874ee558b2fb44) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`e53def0`](https://github.com/inspect-js/is-symbol/commit/e53def0b77c38cbfae87fd8bbfd78953b845ea94) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect` [`ae36504`](https://github.com/inspect-js/is-symbol/commit/ae365048c0c1b13457faa78658b80561f5a0bcd0) +- [readme] add actions and codecov badges [`aae7f09`](https://github.com/inspect-js/is-symbol/commit/aae7f09bd59d36df69d3b66d9b351c39fe072330) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`d993fae`](https://github.com/inspect-js/is-symbol/commit/d993fae6d89856d4ab7818874be597249cb8a8cc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`51808a5`](https://github.com/inspect-js/is-symbol/commit/51808a55f272023201f40a59b2459ec6305bf73a) +- [Dev Deps] update `auto-changelog`, `tape` [`c90040f`](https://github.com/inspect-js/is-symbol/commit/c90040f0aeded8d0071a78d5cd593b385f8828ee) +- [Dev Deps] update `eslint`, `tape` [`9fee159`](https://github.com/inspect-js/is-symbol/commit/9fee159403d499a5ed2f5cb5db03747d09ab1766) +- [meta] use `prepublishOnly` script for npm 7+ [`b166afc`](https://github.com/inspect-js/is-symbol/commit/b166afc3ae3c6d11721a9558ddb112a28261688d) +- [meta] gitignore coverage output [`4a0fe3a`](https://github.com/inspect-js/is-symbol/commit/4a0fe3aa074b933074fcc231ce739005e1fec195) +- [actions] update workflows [`fbcbc9e`](https://github.com/inspect-js/is-symbol/commit/fbcbc9eb5bfe2cf9a77d5bd86bb1dece8e5f81d0) +- [Dev Deps] update `auto-changelog`; add `aud` [`e66ab98`](https://github.com/inspect-js/is-symbol/commit/e66ab989e48b81b48bd443d35dba0071950c5d7a) +- [Deps] update `has-symbols` [`6ce7de5`](https://github.com/inspect-js/is-symbol/commit/6ce7de53c866c068de2c28d97b3a64cf6d5f6a76) +- [actions] update rebase action to use checkout v2 [`1173c79`](https://github.com/inspect-js/is-symbol/commit/1173c79914076d73aec9aebc22dce4122e7bd3ae) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`94a6348`](https://github.com/inspect-js/is-symbol/commit/94a6348f6274eac9bf4c5a6057b4f6120fc7d1d1) +- [Tests] only audit prod deps [`0692681`](https://github.com/inspect-js/is-symbol/commit/06926811fa029fe0fded5d0af4553a7808c143d1) +- [meta] do not publish .nvmrc file [`ed47833`](https://github.com/inspect-js/is-symbol/commit/ed478333c72384f8dbeb51e5fd501238f52a4972) + +## [v1.0.3](https://github.com/inspect-js/is-symbol/compare/v1.0.2...v1.0.3) - 2019-11-20 + +### Commits + +- [Tests] use shared travis-ci configs [`034afdd`](https://github.com/inspect-js/is-symbol/commit/034afdd677c1b72b76751f3e5131acc927a32916) +- [Tests] remove `jscs` [`0c026a0`](https://github.com/inspect-js/is-symbol/commit/0c026a06815e46a33a8a5b4b1be8965d32d38e5c) +- [meta] add `auto-changelog` [`9a1776b`](https://github.com/inspect-js/is-symbol/commit/9a1776bb49f3e6ac12a5b3a447edcc651216891b) +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`23a6db4`](https://github.com/inspect-js/is-symbol/commit/23a6db49a338d19eab19d876745513820bb6a9dc) +- [Tests] up to `node` `v11.7`, `v10.15`, `v8.15`, `v6.16` [`892d92e`](https://github.com/inspect-js/is-symbol/commit/892d92e7c40f3c0577583a98134106181c38bb7e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `semver`, `tape` [`c2e6d6a`](https://github.com/inspect-js/is-symbol/commit/c2e6d6a71f839522bbd124b7419f5fc42ffff6d3) +- [readme] fix repo URLs [`655c288`](https://github.com/inspect-js/is-symbol/commit/655c288a815856e647dba4b6049b1743cec3533c) +- [actions] add automatic rebasing / merge commit blocking [`97b1229`](https://github.com/inspect-js/is-symbol/commit/97b12296bf8fa1ce0c6121bf3de56c413da10aae) +- [meta] add FUNDING.yml [`94c64a3`](https://github.com/inspect-js/is-symbol/commit/94c64a367a1c34f960cf6007fc65cfbbcba34ba3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape`, `semver` [`71ab543`](https://github.com/inspect-js/is-symbol/commit/71ab543e09b820378362f4f66248addd410c6388) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `semver`, `tape` [`c6212f9`](https://github.com/inspect-js/is-symbol/commit/c6212f94e28622c94bb37189ffc241ee88b5b1dd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `object-inspect` [`91bc802`](https://github.com/inspect-js/is-symbol/commit/91bc802e18e63f4e8230ee0148302ce849e2f733) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`8cbe69c`](https://github.com/inspect-js/is-symbol/commit/8cbe69c3fafe9cfbe7d27f710c88d02d2d2c6a00) +- [Tests] use `npm audit` instead of `nsp` [`741b51d`](https://github.com/inspect-js/is-symbol/commit/741b51dac868f6b22736c204910d257bcf4d5044) +- [meta] add `funding` field [`65b58d1`](https://github.com/inspect-js/is-symbol/commit/65b58d1e9fc572712d462d615e6b2418627d8fb9) +- [Deps] update `has-symbols` [`9cb5b2a`](https://github.com/inspect-js/is-symbol/commit/9cb5b2a9a3b89e8e0246be8df4fff3f5ceac7309) + +## [v1.0.2](https://github.com/inspect-js/is-symbol/compare/v1.0.1...v1.0.2) - 2018-09-20 + +### Commits + +- Update `eslint`, `tape`, `semver`; use my personal shared `eslint` config [`e86aaea`](https://github.com/inspect-js/is-symbol/commit/e86aaea8d81356801ecfc60540523e9b809a55f4) +- [Tests] on all node minors; improve test matrix [`50bc07f`](https://github.com/inspect-js/is-symbol/commit/50bc07f2ff73e5499b02a61f0a00ea48a84ae213) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `semver`, `eslint`, `@ljharb/eslint-config` [`45e17bd`](https://github.com/inspect-js/is-symbol/commit/45e17bdf145846f30122348a94c5e506b90836ba) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9`; use `nvm install-latest-npm` [`44402cb`](https://github.com/inspect-js/is-symbol/commit/44402cb82d4499e947b48b31b14667d1ebe7e2b4) +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`, `v4.8`; improve matrix; old npm breaks on newer nodes [`9047c23`](https://github.com/inspect-js/is-symbol/commit/9047c232857ecb80551a21cc0b1cc4c91d28da1f) +- Update `tape`, `covert`, `jscs`, `semver` [`d57d1ce`](https://github.com/inspect-js/is-symbol/commit/d57d1ce3fc0b740885a1ed5c0738d4a27b29ab07) +- Add `npm run eslint` [`0d75a66`](https://github.com/inspect-js/is-symbol/commit/0d75a6638ad6f7ff7d5bc958531a6328fb13e3fe) +- Update `eslint` [`042fb3a`](https://github.com/inspect-js/is-symbol/commit/042fb3aec590f0c0d205b15812b285ad95cfff6b) +- [Refactor] use `has-symbols` and `object-inspect` [`129bc68`](https://github.com/inspect-js/is-symbol/commit/129bc68dd619b789b9956ac9b63b46257ee1060c) +- [Tests] up to `node` `v10.11`, `v8.12` [`c1822e8`](https://github.com/inspect-js/is-symbol/commit/c1822e84d6cc0cee9f1c2893e91b1aa999ad41db) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`089d2cf`](https://github.com/inspect-js/is-symbol/commit/089d2cf7cad87b75aa534769af11524ad2e79080) +- [Tests] up to `node` `v8.4`; newer npm breaks on older node [`05ce701`](https://github.com/inspect-js/is-symbol/commit/05ce701e3c1be8b3266ffac49806832e410491c1) +- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`241e6a6`](https://github.com/inspect-js/is-symbol/commit/241e6a655c0e19e9dcf0ae88e7fddd4cde394c5c) +- Test on latest `node` and `io.js` versions. [`5c8d5de`](https://github.com/inspect-js/is-symbol/commit/5c8d5deb9b7c01a8cdf959082a3d619c19751b0a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `semver`, `tape` [`06047bf`](https://github.com/inspect-js/is-symbol/commit/06047bf72b20a66c0b455e80856b2d00b1910391) +- [Dev Deps] update `jscs`, `nsp`, `semver`, `eslint`, `@ljharb/eslint-config` [`9d25dd7`](https://github.com/inspect-js/is-symbol/commit/9d25dd79347c89f98207a3bad39f667f1f8a410e) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`ce173bd`](https://github.com/inspect-js/is-symbol/commit/ce173bda6e146907e3061a0e70463107d955de35) +- Update `nsp`, `eslint` [`29e5214`](https://github.com/inspect-js/is-symbol/commit/29e52140fac2049b4a32e175787bb3b184a1dd72) +- Update `semver`, `eslint` [`53be884`](https://github.com/inspect-js/is-symbol/commit/53be884c2811f7a4452581003d9cdaf6f9bddd3c) +- [Dev Deps] update `eslint`, `nsp`, `semver`, `tape` [`3bd149c`](https://github.com/inspect-js/is-symbol/commit/3bd149c869c099b07104b06c0692755a01f8298c) +- [Dev Deps] update `jscs` [`69b4231`](https://github.com/inspect-js/is-symbol/commit/69b4231632b170e5ddb350db2f0c59e6cad6f548) +- Test up to `io.js` `v2.1` [`0b61ac7`](https://github.com/inspect-js/is-symbol/commit/0b61ac7ac4de390296aeefb9395549592ea87da4) +- [Dev Deps] update `tape` [`5e1b200`](https://github.com/inspect-js/is-symbol/commit/5e1b2008c910bcdabee299a1ac599143ea07c3f9) +- Only apps should have lockfiles. [`a191ff5`](https://github.com/inspect-js/is-symbol/commit/a191ff5f0320fc16db42fdaa40f0c21d4326255e) +- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`97c87ef`](https://github.com/inspect-js/is-symbol/commit/97c87ef52b966f211e231092a54ef6ed05c99a26) +- Test on `io.js` `v2.2` [`42560e4`](https://github.com/inspect-js/is-symbol/commit/42560e466e17cbbb9fa71c0121f4bbbcf266c887) +- [Dev Deps] Update `tape`, `eslint` [`149b2f2`](https://github.com/inspect-js/is-symbol/commit/149b2f20bde92b2da12ccfeb8988beb2dc95c37c) +- [Tests] fix test messages [`28bd1ed`](https://github.com/inspect-js/is-symbol/commit/28bd1eda310590e13ada19cbd718c85c25d8a0c5) +- Test up to `io.js` `v3.0` [`c0dcc98`](https://github.com/inspect-js/is-symbol/commit/c0dcc98313d17151ec043e5452df306618be865e) +- `node` now supports Symbols now. [`d1853ad`](https://github.com/inspect-js/is-symbol/commit/d1853adf6369ab9d4c4516bdb032c2e42f52f90a) +- [Dev Deps] update `tape` [`f7a6575`](https://github.com/inspect-js/is-symbol/commit/f7a6575fbdef13abcc412c63d22b56943ed85969) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`aae9c6a`](https://github.com/inspect-js/is-symbol/commit/aae9c6a724578659976ea74e11ec9fe35608607b) +- Test on `io.js` `v2.4` [`ab8f449`](https://github.com/inspect-js/is-symbol/commit/ab8f4492115270cc00a479915b02ac1bac75dfed) +- Test on `io.js` `v2.3` [`58ce871`](https://github.com/inspect-js/is-symbol/commit/58ce871674e857955b333aa057eeecd68b40e988) + +## [v1.0.1](https://github.com/inspect-js/is-symbol/compare/v1.0.0...v1.0.1) - 2015-01-26 + +### Commits + +- Correct package description. [`f4d15b9`](https://github.com/inspect-js/is-symbol/commit/f4d15b928b4b754b097a84f7c3ceac73c486aceb) + +## v1.0.0 - 2015-01-24 + +### Commits + +- Dotfiles. [`5d9a744`](https://github.com/inspect-js/is-symbol/commit/5d9a7441f724630070e9bd74a995191cafa1064b) +- Tests. [`8af5663`](https://github.com/inspect-js/is-symbol/commit/8af56631950dcee48b36f517837273193a6ba119) +- `make release` [`6293446`](https://github.com/inspect-js/is-symbol/commit/629344654a72e7fc8059607d6a86c64b002c3e5d) +- package.json [`7d4082c`](https://github.com/inspect-js/is-symbol/commit/7d4082ca9502118e70d24f526704d45a1a7f2067) +- Initial commit [`cbb179f`](https://github.com/inspect-js/is-symbol/commit/cbb179f677bd3dcb56ac5e3f0a7a9af503fd8952) +- Read me. [`099a775`](https://github.com/inspect-js/is-symbol/commit/099a775e7e751706283ae1cab7a8635c094773a9) +- Implementation. [`cb51248`](https://github.com/inspect-js/is-symbol/commit/cb51248eedaf55e0b8ad7dacdab179db2d76e96e) diff --git a/node_modules/is-symbol/LICENSE b/node_modules/is-symbol/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/node_modules/is-symbol/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/is-symbol/README.md b/node_modules/is-symbol/README.md new file mode 100644 index 0000000..5432594 --- /dev/null +++ b/node_modules/is-symbol/README.md @@ -0,0 +1,45 @@ +# is-symbol [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this an ES6 Symbol value? + +## Example + +```js +var isSymbol = require('is-symbol'); +assert(!isSymbol(function () {})); +assert(!isSymbol(null)); +assert(!isSymbol(function* () { yield 42; return Infinity; }); + +assert(isSymbol(Symbol.iterator)); +assert(isSymbol(Symbol('foo'))); +assert(isSymbol(Symbol.for('foo'))); +assert(isSymbol(Object(Symbol('foo')))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-symbol +[2]: https://versionbadg.es/inspect-js/is-symbol.svg +[5]: https://david-dm.org/inspect-js/is-symbol.svg +[6]: https://david-dm.org/inspect-js/is-symbol +[7]: https://david-dm.org/inspect-js/is-symbol/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-symbol#info=devDependencies +[11]: https://nodei.co/npm/is-symbol.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-symbol.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-symbol.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-symbol +[codecov-image]: https://codecov.io/gh/inspect-js/is-symbol/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-symbol/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-symbol +[actions-url]: https://github.com/inspect-js/is-symbol/actions diff --git a/node_modules/is-symbol/index.js b/node_modules/is-symbol/index.js new file mode 100644 index 0000000..3d653e2 --- /dev/null +++ b/node_modules/is-symbol/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var toStr = Object.prototype.toString; +var hasSymbols = require('has-symbols')(); + +if (hasSymbols) { + var symToStr = Symbol.prototype.toString; + var symStringRegex = /^Symbol\(.*\)$/; + var isSymbolObject = function isRealSymbolObject(value) { + if (typeof value.valueOf() !== 'symbol') { + return false; + } + return symStringRegex.test(symToStr.call(value)); + }; + + module.exports = function isSymbol(value) { + if (typeof value === 'symbol') { + return true; + } + if (toStr.call(value) !== '[object Symbol]') { + return false; + } + try { + return isSymbolObject(value); + } catch (e) { + return false; + } + }; +} else { + + module.exports = function isSymbol(value) { + // this environment does not support Symbols. + return false && value; + }; +} diff --git a/node_modules/is-symbol/package.json b/node_modules/is-symbol/package.json new file mode 100644 index 0000000..4472b17 --- /dev/null +++ b/node_modules/is-symbol/package.json @@ -0,0 +1,77 @@ +{ + "name": "is-symbol", + "version": "1.0.4", + "description": "Determine if a value is an ES6 Symbol or not.", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx aud --production", + "lint": "eslint .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-symbol.git" + }, + "keywords": [ + "symbol", + "es6", + "is", + "Symbol" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/is-symbol/issues" + }, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.2.1", + "eslint": "^7.26.0", + "nyc": "^10.3.2", + "object-inspect": "^1.10.3", + "safe-publish-latest": "^1.1.4", + "tape": "^5.2.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/is-symbol/test/index.js b/node_modules/is-symbol/test/index.js new file mode 100644 index 0000000..e01f035 --- /dev/null +++ b/node_modules/is-symbol/test/index.js @@ -0,0 +1,92 @@ +'use strict'; + +var test = require('tape'); +var isSymbol = require('../index'); + +var forEach = function (arr, func) { + var i; + for (i = 0; i < arr.length; ++i) { + func(arr[i], i, arr); + } +}; + +var hasSymbols = require('has-symbols')(); +var inspect = require('object-inspect'); +var debug = function (v, m) { return inspect(v) + ' ' + m; }; + +test('non-symbol values', function (t) { + var nonSymbols = [ + true, + false, + Object(true), + Object(false), + null, + undefined, + {}, + [], + /a/g, + 'string', + 42, + new Date(), + function () {}, + NaN + ]; + t.plan(nonSymbols.length); + forEach(nonSymbols, function (nonSymbol) { + t.equal(false, isSymbol(nonSymbol), debug(nonSymbol, 'is not a symbol')); + }); + t.end(); +}); + +test('faked symbol values', function (t) { + t.test('real symbol valueOf', { skip: !hasSymbols }, function (st) { + var fakeSymbol = { valueOf: function () { return Symbol('foo'); } }; + st.equal(false, isSymbol(fakeSymbol), 'object with valueOf returning a symbol is not a symbol'); + st.end(); + }); + + t.test('faked @@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (st) { + var fakeSymbol = { valueOf: function () { return Symbol('foo'); } }; + fakeSymbol[Symbol.toStringTag] = 'Symbol'; + st.equal(false, isSymbol(fakeSymbol), 'object with fake Symbol @@toStringTag and valueOf returning a symbol is not a symbol'); + var notSoFakeSymbol = { valueOf: function () { return 42; } }; + notSoFakeSymbol[Symbol.toStringTag] = 'Symbol'; + st.equal(false, isSymbol(notSoFakeSymbol), 'object with fake Symbol @@toStringTag and valueOf not returning a symbol is not a symbol'); + st.end(); + }); + + var fakeSymbolString = { toString: function () { return 'Symbol(foo)'; } }; + t.equal(false, isSymbol(fakeSymbolString), 'object with toString returning Symbol(foo) is not a symbol'); + + t.end(); +}); + +test('Symbol support', { skip: !hasSymbols }, function (t) { + t.test('well-known Symbols', function (st) { + var isWellKnown = function filterer(name) { + return name !== 'for' && name !== 'keyFor' && !(name in filterer); + }; + var wellKnownSymbols = Object.getOwnPropertyNames(Symbol).filter(isWellKnown); + wellKnownSymbols.forEach(function (name) { + var sym = Symbol[name]; + st.equal(true, isSymbol(sym), debug(sym, ' is a symbol')); + }); + st.end(); + }); + + t.test('user-created symbols', function (st) { + var symbols = [ + Symbol(), + Symbol('foo'), + Symbol['for']('foo'), + Object(Symbol('object')) + ]; + symbols.forEach(function (sym) { + st.equal(true, isSymbol(sym), debug(sym, ' is a symbol')); + }); + st.end(); + }); + + t.end(); +}); + diff --git a/node_modules/is-typed-array/.editorconfig b/node_modules/is-typed-array/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/is-typed-array/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/is-typed-array/.eslintrc b/node_modules/is-typed-array/.eslintrc new file mode 100644 index 0000000..34a6262 --- /dev/null +++ b/node_modules/is-typed-array/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "globals": { + "globalThis": false + }, + + "rules": { + "max-statements-per-line": [2, { "max": 2 }] + }, +} diff --git a/node_modules/is-typed-array/.github/FUNDING.yml b/node_modules/is-typed-array/.github/FUNDING.yml new file mode 100644 index 0000000..7dd24b9 --- /dev/null +++ b/node_modules/is-typed-array/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-typed-array +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-typed-array/.nycrc b/node_modules/is-typed-array/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-typed-array/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-typed-array/CHANGELOG.md b/node_modules/is-typed-array/CHANGELOG.md new file mode 100644 index 0000000..b139d2d --- /dev/null +++ b/node_modules/is-typed-array/CHANGELOG.md @@ -0,0 +1,134 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.12](https://github.com/inspect-js/is-typed-array/compare/v1.1.11...v1.1.12) - 2023-07-17 + +### Commits + +- [Refactor] use `which-typed-array` for all internals [`7619405`](https://github.com/inspect-js/is-typed-array/commit/761940532de595f6721fed101b02814dcfa7fe4e) + +## [v1.1.11](https://github.com/inspect-js/is-typed-array/compare/v1.1.10...v1.1.11) - 2023-07-17 + +### Commits + +- [Fix] `node < v0.6` lacks proper Object toString behavior [`c94b90d`](https://github.com/inspect-js/is-typed-array/commit/c94b90dc6bc457783d6f8cc208415a49da0933b7) +- [Robustness] use `call-bind` [`573b00b`](https://github.com/inspect-js/is-typed-array/commit/573b00b8deec42ac1ac262415e442ea0b7e1c96b) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`c88c2d4`](https://github.com/inspect-js/is-typed-array/commit/c88c2d479976110478fa4038fe8921251c06a163) + +## [v1.1.10](https://github.com/inspect-js/is-typed-array/compare/v1.1.9...v1.1.10) - 2022-11-02 + +### Commits + +- [meta] add `auto-changelog` [`cf6d86b`](https://github.com/inspect-js/is-typed-array/commit/cf6d86bf2f693eca357439d4d12e76d641f91f92) +- [actions] update rebase action to use reusable workflow [`8da51a5`](https://github.com/inspect-js/is-typed-array/commit/8da51a5dce6d2442ae31ccbc2be136f2e04d6bef) +- [Dev Deps] update `aud`, `is-callable`, `object-inspect`, `tape` [`554e3de`](https://github.com/inspect-js/is-typed-array/commit/554e3deec59dec926d0badc628e589ab363e465b) +- [Refactor] use `gopd` instead of an `es-abstract` helper` [`cdaa465`](https://github.com/inspect-js/is-typed-array/commit/cdaa465d5f94bfc9e32475e31209e1c2458a9603) +- [Deps] update `es-abstract` [`677ae4b`](https://github.com/inspect-js/is-typed-array/commit/677ae4b3c8323b59d6650a9254ab945045c33f79) + + + +1.1.9 / 2022-05-13 +================= + * [Refactor] use `foreach` instead of `for-each` + * [readme] markdown URL cleanup + * [Deps] update `es-abstract` + * [meta] use `npmignore` to autogenerate an npmignore file + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `safe-publish-latest`, `tape` + * [actions] reuse common workflows + * [actions] update codecov uploader + +1.1.8 / 2021-08-30 +================= + * [Refactor] use `globalThis` if available (#53) + * [Deps] update `available-typed-arrays` + * [Dev Deps] update `@ljharb/eslint-config` + +1.1.7 / 2021-08-07 +================= + * [Fix] if Symbol.toStringTag exists but is not present, use Object.prototype.toString + * [Dev Deps] update `is-callable`, `tape` + +1.1.6 / 2021-08-05 +================= + * [Fix] use `has-tostringtag` to behave correctly in the presence of symbol shams + * [readme] add actions and codecov badges + * [meta] use `prepublishOnly` script for npm 7+ + * [Deps] update `available-typed-arrays`, `es-abstract` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` + * [actions] use `node/install` instead of `node/run`; use `codecov` action + +1.1.5 / 2021-02-14 +================= + * [meta] do not publish github action workflow files or nyc output + * [Deps] update `call-bind`, `es-abstract` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `is-callable`, `tape` + +1.1.4 / 2020-12-05 +================= + * [readme] fix repo URLs, remove defunct badges + * [Deps] update `available-typed-arrays`, `es-abstract`; use `call-bind` where applicable + * [meta] gitignore nyc output + * [meta] only audit prod deps + * [actions] add "Allow Edits" workflow + * [actions] switch Automatic Rebase workflow to `pull_request_target` event + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is-callable`, `make-arrow-function`, `make-generator-function`, `object-inspect`, `tape`; add `aud` + * [Tests] migrate tests to Github Actions + * [Tests] run `nyc` on all tests + +1.1.3 / 2020-01-24 +================= + * [Refactor] use `es-abstract`’s `callBound`, `available-typed-arrays`, `has-symbols` + +1.1.2 / 2020-01-20 +================= + * [Fix] in envs without Symbol.toStringTag, dc8a8cc made arrays return `true` + * [Tests] add `evalmd` to `prelint` + +1.1.1 / 2020-01-18 +================= + * [Robustness] don’t rely on Array.prototype.indexOf existing + * [meta] remove unused Makefile and associated utilities + * [meta] add `funding` field; create FUNDING.yml + * [actions] add automatic rebasing / merge commit blocking + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is-callable`, `replace`, `semver`, `tape`; add `safe-publish-latest` + * [Tests] use shared travis-ci configs + * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops + +1.1.0 / 2019-02-16 +================= + * [New] add `BigInt64Array` and `BigUint64Array` + * [Refactor] use an array instead of an object for storing Typed Array names + * [meta] ignore `test.html` + * [Tests] up to `node` `v11.10`, `v10.15`, `v8.15`, `v7.10`, `v6.16`, `v5.10`, `v4.9` + * [Tests] remove `jscs` + * [Tests] use `npm audit` instead of `nsp` + * [Dev Deps] update `eslint`,` @ljharb/eslint-config`, `is-callable`, `tape`, `replace`, `semver` + * [Dev Deps] remove unused eccheck script + dep + +1.0.4 / 2016-03-19 +================= + * [Fix] `Symbol.toStringTag` is on the super-`[[Prototype]]` of Float32Array, not the `[[Prototype]]` (#3) + * [Tests] up to `node` `v5.9`, `v4.4` + * [Tests] use pretest/posttest for linting/security + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `is-callable` + +1.0.3 / 2015-10-13 +================= + * [Deps] Add missing `foreach` dependency (#1) + +1.0.2 / 2015-10-05 +================= + * [Deps] Remove unneeded "isarray" dependency + * [Dev Deps] update `eslint`, `@ljharb/eslint-config` + +1.0.1 / 2015-10-02 +================= + * Rerelease: avoid instanceof and the constructor property; work cross-realm; work with Symbol.toStringTag. + +1.0.0 / 2015-05-06 +================= + * Initial release. diff --git a/node_modules/is-typed-array/LICENSE b/node_modules/is-typed-array/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/node_modules/is-typed-array/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/is-typed-array/README.md b/node_modules/is-typed-array/README.md new file mode 100644 index 0000000..5075257 --- /dev/null +++ b/node_modules/is-typed-array/README.md @@ -0,0 +1,70 @@ +# is-typed-array [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Is this value a JS Typed Array? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag. + +## Example + +```js +var isTypedArray = require('is-typed-array'); +var assert = require('assert'); + +assert.equal(false, isTypedArray(undefined)); +assert.equal(false, isTypedArray(null)); +assert.equal(false, isTypedArray(false)); +assert.equal(false, isTypedArray(true)); +assert.equal(false, isTypedArray([])); +assert.equal(false, isTypedArray({})); +assert.equal(false, isTypedArray(/a/g)); +assert.equal(false, isTypedArray(new RegExp('a', 'g'))); +assert.equal(false, isTypedArray(new Date())); +assert.equal(false, isTypedArray(42)); +assert.equal(false, isTypedArray(NaN)); +assert.equal(false, isTypedArray(Infinity)); +assert.equal(false, isTypedArray(new Number(42))); +assert.equal(false, isTypedArray('foo')); +assert.equal(false, isTypedArray(Object('foo'))); +assert.equal(false, isTypedArray(function () {})); +assert.equal(false, isTypedArray(function* () {})); +assert.equal(false, isTypedArray(x => x * x)); +assert.equal(false, isTypedArray([])); + +assert.ok(isTypedArray(new Int8Array())); +assert.ok(isTypedArray(new Uint8Array())); +assert.ok(isTypedArray(new Uint8ClampedArray())); +assert.ok(isTypedArray(new Int16Array())); +assert.ok(isTypedArray(new Uint16Array())); +assert.ok(isTypedArray(new Int32Array())); +assert.ok(isTypedArray(new Uint32Array())); +assert.ok(isTypedArray(new Float32Array())); +assert.ok(isTypedArray(new Float64Array())); +assert.ok(isTypedArray(new BigInt64Array())); +assert.ok(isTypedArray(new BigUint64Array())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/is-typed-array +[npm-version-svg]: https://versionbadg.es/inspect-js/is-typed-array.svg +[deps-svg]: https://david-dm.org/inspect-js/is-typed-array.svg +[deps-url]: https://david-dm.org/inspect-js/is-typed-array +[dev-deps-svg]: https://david-dm.org/inspect-js/is-typed-array/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/is-typed-array#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/is-typed-array.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-typed-array.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-typed-array.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-typed-array +[codecov-image]: https://codecov.io/gh/inspect-js/is-typed-array/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-typed-array/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-typed-array +[actions-url]: https://github.com/inspect-js/is-typed-array/actions diff --git a/node_modules/is-typed-array/index.js b/node_modules/is-typed-array/index.js new file mode 100644 index 0000000..08c3163 --- /dev/null +++ b/node_modules/is-typed-array/index.js @@ -0,0 +1,7 @@ +'use strict'; + +var whichTypedArray = require('which-typed-array'); + +module.exports = function isTypedArray(value) { + return !!whichTypedArray(value); +}; diff --git a/node_modules/is-typed-array/package.json b/node_modules/is-typed-array/package.json new file mode 100644 index 0000000..e2fc302 --- /dev/null +++ b/node_modules/is-typed-array/package.json @@ -0,0 +1,116 @@ +{ + "name": "is-typed-array", + "version": "1.1.12", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Is this value a JS Typed Array? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run --silent lint", + "test": "npm run tests-only && npm run test:harmony", + "tests-only": "nyc tape test", + "test:harmony": "nyc node --harmony --es-staging test", + "posttest": "npx aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-typed-array.git" + }, + "keywords": [ + "array", + "TypedArray", + "typed array", + "is", + "typed", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "ES6", + "toStringTag", + "Symbol.toStringTag", + "@@toStringTag" + ], + "dependencies": { + "which-typed-array": "^1.1.11" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "has-tostringtag": "^1.0.0", + "in-publish": "^2.0.1", + "is-callable": "^1.2.7", + "make-arrow-function": "^1.2.0", + "make-generator-function": "^2.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.5" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true, + "startingVersion": "1.1.10" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/is-typed-array/test/index.js b/node_modules/is-typed-array/test/index.js new file mode 100644 index 0000000..8e7a16b --- /dev/null +++ b/node_modules/is-typed-array/test/index.js @@ -0,0 +1,103 @@ +'use strict'; + +var test = require('tape'); +var isTypedArray = require('../'); +var isCallable = require('is-callable'); +var hasToStringTag = require('has-tostringtag/shams')(); +var generators = require('make-generator-function')(); +var arrowFn = require('make-arrow-function')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); + +var typedArrayNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +]; + +test('not arrays', function (t) { + t.test('non-number/string primitives', function (st) { + st.notOk(isTypedArray(), 'undefined is not typed array'); + st.notOk(isTypedArray(null), 'null is not typed array'); + st.notOk(isTypedArray(false), 'false is not typed array'); + st.notOk(isTypedArray(true), 'true is not typed array'); + st.end(); + }); + + t.notOk(isTypedArray({}), 'object is not typed array'); + t.notOk(isTypedArray(/a/g), 'regex literal is not typed array'); + t.notOk(isTypedArray(new RegExp('a', 'g')), 'regex object is not typed array'); + t.notOk(isTypedArray(new Date()), 'new Date() is not typed array'); + + t.test('numbers', function (st) { + st.notOk(isTypedArray(42), 'number is not typed array'); + st.notOk(isTypedArray(Object(42)), 'number object is not typed array'); + st.notOk(isTypedArray(NaN), 'NaN is not typed array'); + st.notOk(isTypedArray(Infinity), 'Infinity is not typed array'); + st.end(); + }); + + t.test('strings', function (st) { + st.notOk(isTypedArray('foo'), 'string primitive is not typed array'); + st.notOk(isTypedArray(Object('foo')), 'string object is not typed array'); + st.end(); + }); + + t.end(); +}); + +test('Functions', function (t) { + t.notOk(isTypedArray(function () {}), 'function is not typed array'); + t.end(); +}); + +test('Generators', { skip: generators.length === 0 }, function (t) { + forEach(generators, function (genFn) { + t.notOk(isTypedArray(genFn), 'generator function ' + inspect(genFn) + ' is not typed array'); + }); + t.end(); +}); + +test('Arrow functions', { skip: !arrowFn }, function (t) { + t.notOk(isTypedArray(arrowFn), 'arrow function is not typed array'); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + forEach(typedArrayNames, function (typedArray) { + if (typeof global[typedArray] === 'function') { + var fakeTypedArray = []; + fakeTypedArray[Symbol.toStringTag] = typedArray; + t.notOk(isTypedArray(fakeTypedArray), 'faked ' + typedArray + ' is not typed array'); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); + +test('non-Typed Arrays', function (t) { + t.notOk(isTypedArray([]), '[] is not typed array'); + t.end(); +}); + +test('Typed Arrays', function (t) { + forEach(typedArrayNames, function (typedArray) { + var TypedArray = global[typedArray]; + if (isCallable(TypedArray)) { + var arr = new TypedArray(10); + t.ok(isTypedArray(arr), 'new ' + typedArray + '(10) is typed array'); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); diff --git a/node_modules/is-weakref/.eslintignore b/node_modules/is-weakref/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/is-weakref/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/is-weakref/.eslintrc b/node_modules/is-weakref/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/is-weakref/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/is-weakref/.github/FUNDING.yml b/node_modules/is-weakref/.github/FUNDING.yml new file mode 100644 index 0000000..a9ccddf --- /dev/null +++ b/node_modules/is-weakref/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-weakref +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-weakref/.nycrc b/node_modules/is-weakref/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-weakref/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-weakref/CHANGELOG.md b/node_modules/is-weakref/CHANGELOG.md new file mode 100644 index 0000000..573938d --- /dev/null +++ b/node_modules/is-weakref/CHANGELOG.md @@ -0,0 +1,54 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/inspect-js/is-weakref/compare/v1.0.1...v1.0.2) - 2021-12-10 + +### Commits + +- [actions] reuse common workflows [`2375b1f`](https://github.com/inspect-js/is-weakref/commit/2375b1f9798b08c7af98481bbb38b4105835dacf) +- [meta] do not publish workflow files [`4c1be42`](https://github.com/inspect-js/is-weakref/commit/4c1be423afacabf2f3aa9e8bf02f668bdeaf3a20) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`7ec78ce`](https://github.com/inspect-js/is-weakref/commit/7ec78ce58c7553469eee97ae82fe147dfccde611) +- [readme] update URLs [`6306f09`](https://github.com/inspect-js/is-weakref/commit/6306f09a7df388150fb1d0b855b6f9e60165a457) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `safe-publish-latest`, `tape` [`7a1601e`](https://github.com/inspect-js/is-weakref/commit/7a1601e93ae50a791751a96d33073f5e65f3d3c9) +- [readme] add actions and codecov badges [`67ecd14`](https://github.com/inspect-js/is-weakref/commit/67ecd14b8b0192456932d1d54838accbf90ff5c0) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `object-inspect`, `safe-publish-latest`, `tape` [`1a5013b`](https://github.com/inspect-js/is-weakref/commit/1a5013bddcb9edc23025571810f9a2eebda53683) +- [actions] update codecov uploader [`b57b037`](https://github.com/inspect-js/is-weakref/commit/b57b037a547f3ecfa3d3f079a8015ec005c7181b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`da49017`](https://github.com/inspect-js/is-weakref/commit/da49017800d628c9bcd2f094d49783d6ee649c50) +- [meta] simplify "exports" [`9b88835`](https://github.com/inspect-js/is-weakref/commit/9b8883585506c135a3fcb9f55d0944a13b4eb3e6) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`c7e77f4`](https://github.com/inspect-js/is-weakref/commit/c7e77f495308f3385adfaa1f4ac78a2632e0bcde) +- [Dev Deps] update `eslint` [`417b29e`](https://github.com/inspect-js/is-weakref/commit/417b29e7ceacebe24aef15422544443f4b59e181) +- [meta] add `safe-publish-latest`; use `prepublishOnly` script for npm 7+ [`b1b99f4`](https://github.com/inspect-js/is-weakref/commit/b1b99f45e0977d10f8472e9272e48a696145c2b1) +- [Deps] update `call-bind` [`aea342e`](https://github.com/inspect-js/is-weakref/commit/aea342e9e301deeb938e62b92a37cf991c5f7dbc) +- [actions] update workflows [`786c2d3`](https://github.com/inspect-js/is-weakref/commit/786c2d3dd4486acec09786220d3dd9fd48e70e93) + +## [v1.0.1](https://github.com/inspect-js/is-weakref/compare/v1.0.0...v1.0.1) - 2020-12-04 + +### Commits + +- [Tests] migrate tests to Github Actions [`05b4faa`](https://github.com/inspect-js/is-weakref/commit/05b4faa167c67f42c792e35c07adcb6b87e7dea0) +- [Tests] run `nyc` on all tests [`8df2e4b`](https://github.com/inspect-js/is-weakref/commit/8df2e4bd66bb6b7d55f389f28e6bb167fe1deb5a) +- [actions] add "Allow Edits" workflow [`4a716b8`](https://github.com/inspect-js/is-weakref/commit/4a716b8fcc025fe889a0f09ccaee7a9f748b1c66) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect` [`be23cf3`](https://github.com/inspect-js/is-weakref/commit/be23cf305f46db8b1c8a26d1c74b096fdba00056) +- [Refactor] use `call-bind` instead of `es-abstract` [`a933a96`](https://github.com/inspect-js/is-weakref/commit/a933a9643ddf7cddfd9f9f3cf44d675cc4c86ce5) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4473ed2`](https://github.com/inspect-js/is-weakref/commit/4473ed2e73fed47cd2fa42b8d9cac17e941d2c08) +- [readme] remove travis badge [`bd3bfcd`](https://github.com/inspect-js/is-weakref/commit/bd3bfcd2c187099d2215232a7621fb960e1e2807) + +## v1.0.0 - 2020-08-01 + +### Commits + +- Initial commit [`dd86394`](https://github.com/inspect-js/is-weakref/commit/dd86394d7da000724c6e17c79077879c381e9ea3) +- readme [`f4defca`](https://github.com/inspect-js/is-weakref/commit/f4defcac48d1d99b019b596ab26bd868de1adfe9) +- Tests [`13d8139`](https://github.com/inspect-js/is-weakref/commit/13d8139dedf424239daf357261c39d3f8c33d662) +- npm init [`55a2bb7`](https://github.com/inspect-js/is-weakref/commit/55a2bb7c53b893396a51da969e352702cafe9a0e) +- Implementation [`1ec84e3`](https://github.com/inspect-js/is-weakref/commit/1ec84e36de4315d44c8da540faa27836832bb0f3) +- [meta] add auto-changelog [`ab9ce44`](https://github.com/inspect-js/is-weakref/commit/ab9ce44be717312c5221bf3d2f3f6d2dd8c6ac88) +- [actions] add automatic rebasing / merge commit blocking [`3d3f4d5`](https://github.com/inspect-js/is-weakref/commit/3d3f4d54bed6e455b2a0d0f20c87d454bf78af26) +- [meta] add "funding"; create `FUNDING.yml` [`f35ef3d`](https://github.com/inspect-js/is-weakref/commit/f35ef3de16eb06447acf3c39bdc164ba0e7bdf45) +- [Tests] add `npm run lint` [`af2123d`](https://github.com/inspect-js/is-weakref/commit/af2123d4754c14f7befa66ba01e1d72858723651) +- [Tests] use shared travis-ci configs [`042b4de`](https://github.com/inspect-js/is-weakref/commit/042b4dec08d882ae9137f4ad05ae24a1457da0f8) +- Only apps should have lockfiles [`fcae604`](https://github.com/inspect-js/is-weakref/commit/fcae604cb1422faae9311dd4219032895c0a9a2e) diff --git a/node_modules/is-weakref/LICENSE b/node_modules/is-weakref/LICENSE new file mode 100644 index 0000000..707437b --- /dev/null +++ b/node_modules/is-weakref/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/is-weakref/README.md b/node_modules/is-weakref/README.md new file mode 100644 index 0000000..abbb978 --- /dev/null +++ b/node_modules/is-weakref/README.md @@ -0,0 +1,52 @@ +# is-weakref [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this value a JS WeakRef? This module works cross-realm/iframe, and despite ES6 @@toStringTag. + +## Example + +```js +var isWeakRef = require('is-weakref'); +assert(!isWeakRef(function () {})); +assert(!isWeakRef(null)); +assert(!isWeakRef(function* () { yield 42; return Infinity; }); +assert(!isWeakRef(Symbol('foo'))); +assert(!isWeakRef(1n)); +assert(!isWeakRef(Object(1n))); + +assert(!isWeakRef(new Set())); +assert(!isWeakRef(new WeakSet())); +assert(!isWeakRef(new Map())); +assert(!isWeakRef(new WeakMap())); + +assert(isWeakRef(new WeakRef({}))); + +class MyWeakRef extends WeakRef {} +assert(isWeakRef(new MyWeakRef({}))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/is-weakref +[npm-version-svg]: https://versionbadg.es/inspect-js/is-weakref.svg +[deps-svg]: https://david-dm.org/inspect-js/is-weakref.svg +[deps-url]: https://david-dm.org/inspect-js/is-weakref +[dev-deps-svg]: https://david-dm.org/inspect-js/is-weakref/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/is-weakref#info=devDependencies +[license-image]: https://img.shields.io/npm/l/is-weakref.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-weakref.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-weakref +[codecov-image]: https://codecov.io/gh/inspect-js/is-weakref/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-weakref/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-weakref +[actions-url]: https://github.com/inspect-js/is-weakref/actions diff --git a/node_modules/is-weakref/index.js b/node_modules/is-weakref/index.js new file mode 100644 index 0000000..90769f8 --- /dev/null +++ b/node_modules/is-weakref/index.js @@ -0,0 +1,21 @@ +'use strict'; + +var callBound = require('call-bind/callBound'); + +var $deref = callBound('WeakRef.prototype.deref', true); + +module.exports = typeof WeakRef === 'undefined' + ? function isWeakRef(value) { // eslint-disable-line no-unused-vars + return false; + } + : function isWeakRef(value) { + if (!value || typeof value !== 'object') { + return false; + } + try { + $deref(value); + return true; + } catch (e) { + return false; + } + }; diff --git a/node_modules/is-weakref/package.json b/node_modules/is-weakref/package.json new file mode 100644 index 0000000..2d2a6e2 --- /dev/null +++ b/node_modules/is-weakref/package.json @@ -0,0 +1,63 @@ +{ + "name": "is-weakref", + "version": "1.0.2", + "description": "Is this value a JS WeakRef? This module works cross-realm/iframe, and despite ES6 @@toStringTag.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "scripts": { + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/is-weakref.git" + }, + "keywords": [ + "weakref", + "weak", + "ref", + "finalization", + "finalization registry" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/is-weakref/issues" + }, + "homepage": "https://github.com/inspect-js/is-weakref#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.0.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^8.4.1", + "for-each": "^0.3.3", + "nyc": "^10.3.2", + "object-inspect": "^1.11.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.3.2" + }, + "dependencies": { + "call-bind": "^1.0.2" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/is-weakref/test/index.js b/node_modules/is-weakref/test/index.js new file mode 100644 index 0000000..c1c5b6f --- /dev/null +++ b/node_modules/is-weakref/test/index.js @@ -0,0 +1,26 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var forEach = require('for-each'); + +var isWeakRef = require('..'); + +test('isWeakRef', function (t) { + t.equal(typeof isWeakRef, 'function', 'is a function'); + + var nonWeakRefs = [undefined, null, true, false, 42, 0, Infinity, NaN, /a/g, function () {}, {}, []]; + forEach(nonWeakRefs, function (nonWeakRef) { + t.equal(isWeakRef(nonWeakRef), false, inspect(nonWeakRef) + ' is not a WeakRef'); + }); + + t.test('actual WeakRefs', { skip: typeof WeakRef === 'undefined' }, function (st) { + var ref = new WeakRef({}); + + st.equal(isWeakRef(ref), true, inspect(ref) + ' is a WeakRef'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/is-wsl/index.d.ts b/node_modules/is-wsl/index.d.ts new file mode 100644 index 0000000..d54e4ba --- /dev/null +++ b/node_modules/is-wsl/index.d.ts @@ -0,0 +1,15 @@ +/** +Check if the process is running inside [Windows Subsystem for Linux](https://msdn.microsoft.com/commandline/wsl/about) (Bash on Windows). + +@example +``` +import isWsl = require('is-wsl'); + +// When running inside Windows Subsystem for Linux +console.log(isWsl); +//=> true +``` +*/ +declare const isWsl: boolean; + +export = isWsl; diff --git a/node_modules/is-wsl/index.js b/node_modules/is-wsl/index.js new file mode 100644 index 0000000..eb6313f --- /dev/null +++ b/node_modules/is-wsl/index.js @@ -0,0 +1,31 @@ +'use strict'; +const os = require('os'); +const fs = require('fs'); +const isDocker = require('is-docker'); + +const isWsl = () => { + if (process.platform !== 'linux') { + return false; + } + + if (os.release().toLowerCase().includes('microsoft')) { + if (isDocker()) { + return false; + } + + return true; + } + + try { + return fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? + !isDocker() : false; + } catch (_) { + return false; + } +}; + +if (process.env.__IS_WSL_TEST__) { + module.exports = isWsl; +} else { + module.exports = isWsl(); +} diff --git a/node_modules/is-wsl/license b/node_modules/is-wsl/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-wsl/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-wsl/package.json b/node_modules/is-wsl/package.json new file mode 100644 index 0000000..2fa7f75 --- /dev/null +++ b/node_modules/is-wsl/package.json @@ -0,0 +1,45 @@ +{ + "name": "is-wsl", + "version": "2.2.0", + "description": "Check if the process is running inside Windows Subsystem for Linux (Bash on Windows)", + "license": "MIT", + "repository": "sindresorhus/is-wsl", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "check", + "wsl", + "windows", + "subsystem", + "linux", + "detect", + "bash", + "process", + "console", + "terminal", + "is" + ], + "dependencies": { + "is-docker": "^2.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "clear-module": "^3.2.0", + "proxyquire": "^2.1.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-wsl/readme.md b/node_modules/is-wsl/readme.md new file mode 100644 index 0000000..5fe44fe --- /dev/null +++ b/node_modules/is-wsl/readme.md @@ -0,0 +1,36 @@ +# is-wsl [![Build Status](https://travis-ci.org/sindresorhus/is-wsl.svg?branch=master)](https://travis-ci.org/sindresorhus/is-wsl) + +> Check if the process is running inside [Windows Subsystem for Linux](https://msdn.microsoft.com/commandline/wsl/about) (Bash on Windows) + +Can be useful if you need to work around unimplemented or buggy features in WSL. Supports both WSL 1 and WSL 2. + + +## Install + +``` +$ npm install is-wsl +``` + + +## Usage + +```js +const isWsl = require('is-wsl'); + +// When running inside Windows Subsystem for Linux +console.log(isWsl); +//=> true +``` + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/isarray/LICENSE b/node_modules/isarray/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/isarray/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/isarray/README.md b/node_modules/isarray/README.md new file mode 100644 index 0000000..3e160b2 --- /dev/null +++ b/node_modules/isarray/README.md @@ -0,0 +1,38 @@ + +# isarray + +`Array#isArray` for older browsers and deprecated Node.js versions. + +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) + +[![browser support](https://ci.testling.com/juliangruber/isarray.png) +](https://ci.testling.com/juliangruber/isarray) + +__Just use Array.isArray directly__, unless you need to support those older versions. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](https://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/node-browserify). + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! diff --git a/node_modules/isarray/index.js b/node_modules/isarray/index.js new file mode 100644 index 0000000..a57f634 --- /dev/null +++ b/node_modules/isarray/index.js @@ -0,0 +1,5 @@ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/isarray/package.json b/node_modules/isarray/package.json new file mode 100644 index 0000000..fb0e89b --- /dev/null +++ b/node_modules/isarray/package.json @@ -0,0 +1,48 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "2.0.5", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "files": [ + "index.js" + ], + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.4" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "scripts": { + "test": "tape test.js" + } +} diff --git a/node_modules/isexe/.npmignore b/node_modules/isexe/.npmignore new file mode 100644 index 0000000..c1cb757 --- /dev/null +++ b/node_modules/isexe/.npmignore @@ -0,0 +1,2 @@ +.nyc_output/ +coverage/ diff --git a/node_modules/isexe/LICENSE b/node_modules/isexe/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/isexe/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/isexe/README.md b/node_modules/isexe/README.md new file mode 100644 index 0000000..35769e8 --- /dev/null +++ b/node_modules/isexe/README.md @@ -0,0 +1,51 @@ +# isexe + +Minimal module to check if a file is executable, and a normal file. + +Uses `fs.stat` and tests against the `PATHEXT` environment variable on +Windows. + +## USAGE + +```javascript +var isexe = require('isexe') +isexe('some-file-name', function (err, isExe) { + if (err) { + console.error('probably file does not exist or something', err) + } else if (isExe) { + console.error('this thing can be run') + } else { + console.error('cannot be run') + } +}) + +// same thing but synchronous, throws errors +var isExe = isexe.sync('some-file-name') + +// treat errors as just "not executable" +isexe('maybe-missing-file', { ignoreErrors: true }, callback) +var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) +``` + +## API + +### `isexe(path, [options], [callback])` + +Check if the path is executable. If no callback provided, and a +global `Promise` object is available, then a Promise will be returned. + +Will raise whatever errors may be raised by `fs.stat`, unless +`options.ignoreErrors` is set to true. + +### `isexe.sync(path, [options])` + +Same as `isexe` but returns the value and throws any errors raised. + +### Options + +* `ignoreErrors` Treat all errors as "no, this is not executable", but + don't raise them. +* `uid` Number to use as the user id +* `gid` Number to use as the group id +* `pathExt` List of path extensions to use instead of `PATHEXT` + environment variable on Windows. diff --git a/node_modules/isexe/index.js b/node_modules/isexe/index.js new file mode 100644 index 0000000..553fb32 --- /dev/null +++ b/node_modules/isexe/index.js @@ -0,0 +1,57 @@ +var fs = require('fs') +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = require('./windows.js') +} else { + core = require('./mode.js') +} + +module.exports = isexe +isexe.sync = sync + +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } + } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} diff --git a/node_modules/isexe/mode.js b/node_modules/isexe/mode.js new file mode 100644 index 0000000..1995ea4 --- /dev/null +++ b/node_modules/isexe/mode.js @@ -0,0 +1,41 @@ +module.exports = isexe +isexe.sync = sync + +var fs = require('fs') + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} + +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} + +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 + + return ret +} diff --git a/node_modules/isexe/package.json b/node_modules/isexe/package.json new file mode 100644 index 0000000..e452689 --- /dev/null +++ b/node_modules/isexe/package.json @@ -0,0 +1,31 @@ +{ + "name": "isexe", + "version": "2.0.0", + "description": "Minimal module to check if a file is executable.", + "main": "index.js", + "directories": { + "test": "test" + }, + "devDependencies": { + "mkdirp": "^0.5.1", + "rimraf": "^2.5.0", + "tap": "^10.3.0" + }, + "scripts": { + "test": "tap test/*.js --100", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/isexe.git" + }, + "keywords": [], + "bugs": { + "url": "https://github.com/isaacs/isexe/issues" + }, + "homepage": "https://github.com/isaacs/isexe#readme" +} diff --git a/node_modules/isexe/test/basic.js b/node_modules/isexe/test/basic.js new file mode 100644 index 0000000..d926df6 --- /dev/null +++ b/node_modules/isexe/test/basic.js @@ -0,0 +1,221 @@ +var t = require('tap') +var fs = require('fs') +var path = require('path') +var fixture = path.resolve(__dirname, 'fixtures') +var meow = fixture + '/meow.cat' +var mine = fixture + '/mine.cat' +var ours = fixture + '/ours.cat' +var fail = fixture + '/fail.false' +var noent = fixture + '/enoent.exe' +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') + +var isWindows = process.platform === 'win32' +var hasAccess = typeof fs.access === 'function' +var winSkip = isWindows && 'windows' +var accessSkip = !hasAccess && 'no fs.access function' +var hasPromise = typeof Promise === 'function' +var promiseSkip = !hasPromise && 'no global Promise' + +function reset () { + delete require.cache[require.resolve('../')] + return require('../') +} + +t.test('setup fixtures', function (t) { + rimraf.sync(fixture) + mkdirp.sync(fixture) + fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n') + fs.chmodSync(meow, parseInt('0755', 8)) + fs.writeFileSync(fail, '#!/usr/bin/env false\n') + fs.chmodSync(fail, parseInt('0644', 8)) + fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n') + fs.chmodSync(mine, parseInt('0744', 8)) + fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n') + fs.chmodSync(ours, parseInt('0754', 8)) + t.end() +}) + +t.test('promise', { skip: promiseSkip }, function (t) { + var isexe = reset() + t.test('meow async', function (t) { + isexe(meow).then(function (is) { + t.ok(is) + t.end() + }) + }) + t.test('fail async', function (t) { + isexe(fail).then(function (is) { + t.notOk(is) + t.end() + }) + }) + t.test('noent async', function (t) { + isexe(noent).catch(function (er) { + t.ok(er) + t.end() + }) + }) + t.test('noent ignore async', function (t) { + isexe(noent, { ignoreErrors: true }).then(function (is) { + t.notOk(is) + t.end() + }) + }) + t.end() +}) + +t.test('no promise', function (t) { + global.Promise = null + var isexe = reset() + t.throws('try to meow a promise', function () { + isexe(meow) + }) + t.end() +}) + +t.test('access', { skip: accessSkip || winSkip }, function (t) { + runTest(t) +}) + +t.test('mode', { skip: winSkip }, function (t) { + delete fs.access + delete fs.accessSync + var isexe = reset() + t.ok(isexe.sync(ours, { uid: 0, gid: 0 })) + t.ok(isexe.sync(mine, { uid: 0, gid: 0 })) + runTest(t) +}) + +t.test('windows', function (t) { + global.TESTING_WINDOWS = true + var pathExt = '.EXE;.CAT;.CMD;.COM' + t.test('pathExt option', function (t) { + runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' }) + }) + t.test('pathExt env', function (t) { + process.env.PATHEXT = pathExt + runTest(t) + }) + t.test('no pathExt', function (t) { + // with a pathExt of '', any filename is fine. + // so the "fail" one would still pass. + runTest(t, { pathExt: '', skipFail: true }) + }) + t.test('pathext with empty entry', function (t) { + // with a pathExt of '', any filename is fine. + // so the "fail" one would still pass. + runTest(t, { pathExt: ';' + pathExt, skipFail: true }) + }) + t.end() +}) + +t.test('cleanup', function (t) { + rimraf.sync(fixture) + t.end() +}) + +function runTest (t, options) { + var isexe = reset() + + var optionsIgnore = Object.create(options || {}) + optionsIgnore.ignoreErrors = true + + if (!options || !options.skipFail) { + t.notOk(isexe.sync(fail, options)) + } + t.notOk(isexe.sync(noent, optionsIgnore)) + if (!options) { + t.ok(isexe.sync(meow)) + } else { + t.ok(isexe.sync(meow, options)) + } + + t.ok(isexe.sync(mine, options)) + t.ok(isexe.sync(ours, options)) + t.throws(function () { + isexe.sync(noent, options) + }) + + t.test('meow async', function (t) { + if (!options) { + isexe(meow, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + } else { + isexe(meow, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + } + }) + + t.test('mine async', function (t) { + isexe(mine, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + }) + + t.test('ours async', function (t) { + isexe(ours, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + }) + + if (!options || !options.skipFail) { + t.test('fail async', function (t) { + isexe(fail, options, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + } + + t.test('noent async', function (t) { + isexe(noent, options, function (er, is) { + t.ok(er) + t.notOk(is) + t.end() + }) + }) + + t.test('noent ignore async', function (t) { + isexe(noent, optionsIgnore, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + + t.test('directory is not executable', function (t) { + isexe(__dirname, options, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + + t.end() +} diff --git a/node_modules/isexe/windows.js b/node_modules/isexe/windows.js new file mode 100644 index 0000000..3499673 --- /dev/null +++ b/node_modules/isexe/windows.js @@ -0,0 +1,42 @@ +module.exports = isexe +isexe.sync = sync + +var fs = require('fs') + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} diff --git a/node_modules/istanbul-lib-coverage/CHANGELOG.md b/node_modules/istanbul-lib-coverage/CHANGELOG.md new file mode 100644 index 0000000..172546b --- /dev/null +++ b/node_modules/istanbul-lib-coverage/CHANGELOG.md @@ -0,0 +1,193 @@ +# Change Log + +All notable changes to this project will be documented in this file. +See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. + +# [3.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@3.0.0-alpha.2...istanbul-lib-coverage@3.0.0) (2019-12-20) + +**Note:** Version bump only for package istanbul-lib-coverage + + + + + +# [3.0.0-alpha.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@3.0.0-alpha.1...istanbul-lib-coverage@3.0.0-alpha.2) (2019-12-07) + +**Note:** Version bump only for package istanbul-lib-coverage + + + + + +# [3.0.0-alpha.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@3.0.0-alpha.0...istanbul-lib-coverage@3.0.0-alpha.1) (2019-10-06) + + +### Bug Fixes + +* Drop unneeded coverage data from `nyc --all` ([#456](https://github.com/istanbuljs/istanbuljs/issues/456)) ([f6bb0b4](https://github.com/istanbuljs/istanbuljs/commit/f6bb0b4)), closes [#123](https://github.com/istanbuljs/istanbuljs/issues/123) [#224](https://github.com/istanbuljs/istanbuljs/issues/224) [#260](https://github.com/istanbuljs/istanbuljs/issues/260) [#322](https://github.com/istanbuljs/istanbuljs/issues/322) [#413](https://github.com/istanbuljs/istanbuljs/issues/413) + + + + + +# [3.0.0-alpha.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@2.0.5...istanbul-lib-coverage@3.0.0-alpha.0) (2019-06-19) + + +### Features + +* Update dependencies, require Node.js 8 ([#401](https://github.com/istanbuljs/istanbuljs/issues/401)) ([bf3a539](https://github.com/istanbuljs/istanbuljs/commit/bf3a539)) + + +### BREAKING CHANGES + +* Node.js 8 is now required + + + + + +## [3.2.0](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage-v3.1.0...istanbul-lib-coverage-v3.2.0) (2021-10-17) + + +### Features + +* allow FileCoverage to be initialized with logical tracking ([#644](https://www.github.com/istanbuljs/istanbuljs/issues/644)) ([4cb5af1](https://www.github.com/istanbuljs/istanbuljs/commit/4cb5af1daaf33c3e9a5f3ee44f6bb7f958e5ba04)) + +## [3.1.0](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage-v3.0.2...istanbul-lib-coverage-v3.1.0) (2021-10-17) + + +### Features + +* support tracking Logic Truthiness as additional metric in coverage API ([#639](https://www.github.com/istanbuljs/istanbuljs/issues/639)) ([0967c80](https://www.github.com/istanbuljs/istanbuljs/commit/0967c80b905c3c17675ff2185b2325784e8dc0a2)) + +### [3.0.2](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage-v3.0.1...istanbul-lib-coverage-v3.0.2) (2021-10-11) + + +### Bug Fixes + +* handle merging '0' indexed coverage with '1' indexed coverage ([5dac2bc](https://www.github.com/istanbuljs/istanbuljs/commit/5dac2bcf28d6f27dbb720be72c2b692153418ab5)), closes [#632](https://www.github.com/istanbuljs/istanbuljs/issues/632) + +### [3.0.1](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage-v3.0.0...istanbul-lib-coverage-v3.0.1) (2021-09-23) + + +### Bug Fixes + +* merge branch/statement/functionMap's together when merging two coverage reports ([#617](https://www.github.com/istanbuljs/istanbuljs/issues/617)) ([ff1b5e9](https://www.github.com/istanbuljs/istanbuljs/commit/ff1b5e915201e4ff8f737010509bab98d8238118)) + +## [2.0.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@2.0.4...istanbul-lib-coverage@2.0.5) (2019-04-24) + +**Note:** Version bump only for package istanbul-lib-coverage + + + + + +## [2.0.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@2.0.3...istanbul-lib-coverage@2.0.4) (2019-03-12) + +**Note:** Version bump only for package istanbul-lib-coverage + + + + + +## [2.0.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@2.0.2...istanbul-lib-coverage@2.0.3) (2019-01-26) + +**Note:** Version bump only for package istanbul-lib-coverage + + + + + + +## [2.0.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@2.0.1...istanbul-lib-coverage@2.0.2) (2018-12-25) + + + + +**Note:** Version bump only for package istanbul-lib-coverage + + +## [2.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@2.0.0...istanbul-lib-coverage@2.0.1) (2018-07-07) + + + + +**Note:** Version bump only for package istanbul-lib-coverage + + +# [2.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@1.2.0...istanbul-lib-coverage@2.0.0) (2018-06-06) + + +### Bug Fixes + +* use null prototype for map objects ([#177](https://github.com/istanbuljs/istanbuljs/issues/177)) ([9a5a30c](https://github.com/istanbuljs/istanbuljs/commit/9a5a30c)) + + +### BREAKING CHANGES + +* a null prototype is now used in several places rather than the default `{}` assignment. + + + + + +# [1.2.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@1.1.2...istanbul-lib-coverage@1.2.0) (2018-03-04) + + +### Features + +* add skip-empty option for html & text reports ([#140](https://github.com/istanbuljs/istanbuljs/issues/140)) ([d2a4262](https://github.com/istanbuljs/istanbuljs/commit/d2a4262)) + + + + + +## [1.1.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@1.1.1...istanbul-lib-coverage@1.1.2) (2018-02-13) + + + + +**Note:** Version bump only for package istanbul-lib-coverage + + +## [1.1.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-coverage@1.1.0...istanbul-lib-coverage@1.1.1) (2017-05-27) + + + + + +# [1.1.0](https://github.com/istanbuljs/istanbul-lib-coverage/compare/istanbul-lib-coverage@1.0.2...istanbul-lib-coverage@1.1.0) (2017-04-29) + + +### Bug Fixes + +* getBranchCoverageByLine() was looking for line coverage using wrong object structure ([bf36658](https://github.com/istanbuljs/istanbul-lib-coverage/commit/bf36658)) + + +### Features + +* add possibility to filter coverage maps when running reports post-hoc ([#24](https://github.com/istanbuljs/istanbuljs/issues/24)) ([e1c99d6](https://github.com/istanbuljs/istanbul-lib-coverage/commit/e1c99d6)) + + + + + +## [1.0.2](https://github.com/istanbuljs/istanbul-lib-coverage/compare/istanbul-lib-coverage@1.0.1...istanbul-lib-coverage@1.0.2) (2017-03-27) + + +## [1.0.1](https://github.com/istanbuljs/istanbul-lib-coverage/compare/v1.0.0...v1.0.1) (2017-01-18) + + +### Bug Fixes + +* handle edge-case surrounding merging two file coverage reports ([22e154c](https://github.com/istanbuljs/istanbul-lib-coverage/commit/22e154c)) + + + + +# [1.0.0](https://github.com/istanbuljs/istanbul-lib-coverage/compare/v1.0.0-alpha.3...v1.0.0) (2016-08-12) + + +### Bug Fixes + +* guard against missing statement ([76aad99](https://github.com/istanbuljs/istanbul-lib-coverage/commit/76aad99)) diff --git a/node_modules/istanbul-lib-coverage/LICENSE b/node_modules/istanbul-lib-coverage/LICENSE new file mode 100644 index 0000000..d55d291 --- /dev/null +++ b/node_modules/istanbul-lib-coverage/LICENSE @@ -0,0 +1,24 @@ +Copyright 2012-2015 Yahoo! Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * 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. + * Neither the name of the Yahoo! Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. 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. diff --git a/node_modules/istanbul-lib-coverage/README.md b/node_modules/istanbul-lib-coverage/README.md new file mode 100644 index 0000000..2c24a56 --- /dev/null +++ b/node_modules/istanbul-lib-coverage/README.md @@ -0,0 +1,29 @@ +## istanbul-lib-coverage + +[![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-lib-coverage.svg)](https://greenkeeper.io/) +[![Build Status](https://travis-ci.org/istanbuljs/istanbul-lib-coverage.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-lib-coverage) + +An API that provides a read-only view of coverage information with the ability +to merge and summarize coverage info. + +Supersedes `object-utils` and `collector` from the v0 istanbul API. + +See the docs for the full API. + +```js +var libCoverage = require('istanbul-lib-coverage'); +var map = libCoverage.createCoverageMap(globalCoverageVar); +var summary = libCoverage.createCoverageSummary(); + +// merge another coverage map into the one we created +map.merge(otherCoverageMap); + +// inspect and summarize all file coverage objects in the map +map.files().forEach(function(f) { + var fc = map.fileCoverageFor(f), + s = fc.toSummary(); + summary.merge(s); +}); + +console.log('Global summary', summary); +``` diff --git a/node_modules/istanbul-lib-coverage/index.js b/node_modules/istanbul-lib-coverage/index.js new file mode 100644 index 0000000..bdc5a18 --- /dev/null +++ b/node_modules/istanbul-lib-coverage/index.js @@ -0,0 +1,64 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +/** + * istanbul-lib-coverage exports an API that allows you to create and manipulate + * file coverage, coverage maps (a set of file coverage objects) and summary + * coverage objects. File coverage for the same file can be merged as can + * entire coverage maps. + * + * @module Exports + */ +const { FileCoverage } = require('./lib/file-coverage'); +const { CoverageMap } = require('./lib/coverage-map'); +const { CoverageSummary } = require('./lib/coverage-summary'); + +module.exports = { + /** + * creates a coverage summary object + * @param {Object} obj an argument with the same semantics + * as the one passed to the `CoverageSummary` constructor + * @returns {CoverageSummary} + */ + createCoverageSummary(obj) { + if (obj && obj instanceof CoverageSummary) { + return obj; + } + return new CoverageSummary(obj); + }, + /** + * creates a CoverageMap object + * @param {Object} obj optional - an argument with the same semantics + * as the one passed to the CoverageMap constructor. + * @returns {CoverageMap} + */ + createCoverageMap(obj) { + if (obj && obj instanceof CoverageMap) { + return obj; + } + return new CoverageMap(obj); + }, + /** + * creates a FileCoverage object + * @param {Object} obj optional - an argument with the same semantics + * as the one passed to the FileCoverage constructor. + * @returns {FileCoverage} + */ + createFileCoverage(obj) { + if (obj && obj instanceof FileCoverage) { + return obj; + } + return new FileCoverage(obj); + } +}; + +/** classes exported for reuse */ +module.exports.classes = { + /** + * the file coverage constructor + */ + FileCoverage +}; diff --git a/node_modules/istanbul-lib-coverage/lib/coverage-map.js b/node_modules/istanbul-lib-coverage/lib/coverage-map.js new file mode 100644 index 0000000..0a1ebd0 --- /dev/null +++ b/node_modules/istanbul-lib-coverage/lib/coverage-map.js @@ -0,0 +1,134 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const { FileCoverage } = require('./file-coverage'); +const { CoverageSummary } = require('./coverage-summary'); + +function maybeConstruct(obj, klass) { + if (obj instanceof klass) { + return obj; + } + + return new klass(obj); +} + +function loadMap(source) { + const data = Object.create(null); + if (!source) { + return data; + } + + Object.entries(source).forEach(([k, cov]) => { + data[k] = maybeConstruct(cov, FileCoverage); + }); + + return data; +} + +/** CoverageMap is a map of `FileCoverage` objects keyed by file paths. */ +class CoverageMap { + /** + * @constructor + * @param {Object} [obj=undefined] obj A coverage map from which to initialize this + * map's contents. This can be the raw global coverage object. + */ + constructor(obj) { + if (obj instanceof CoverageMap) { + this.data = obj.data; + } else { + this.data = loadMap(obj); + } + } + + /** + * merges a second coverage map into this one + * @param {CoverageMap} obj - a CoverageMap or its raw data. Coverage is merged + * correctly for the same files and additional file coverage keys are created + * as needed. + */ + merge(obj) { + const other = maybeConstruct(obj, CoverageMap); + Object.values(other.data).forEach(fc => { + this.addFileCoverage(fc); + }); + } + + /** + * filter the coveragemap based on the callback provided + * @param {Function (filename)} callback - Returns true if the path + * should be included in the coveragemap. False if it should be + * removed. + */ + filter(callback) { + Object.keys(this.data).forEach(k => { + if (!callback(k)) { + delete this.data[k]; + } + }); + } + + /** + * returns a JSON-serializable POJO for this coverage map + * @returns {Object} + */ + toJSON() { + return this.data; + } + + /** + * returns an array for file paths for which this map has coverage + * @returns {Array{string}} - array of files + */ + files() { + return Object.keys(this.data); + } + + /** + * returns the file coverage for the specified file. + * @param {String} file + * @returns {FileCoverage} + */ + fileCoverageFor(file) { + const fc = this.data[file]; + if (!fc) { + throw new Error(`No file coverage available for: ${file}`); + } + return fc; + } + + /** + * adds a file coverage object to this map. If the path for the object, + * already exists in the map, it is merged with the existing coverage + * otherwise a new key is added to the map. + * @param {FileCoverage} fc the file coverage to add + */ + addFileCoverage(fc) { + const cov = new FileCoverage(fc); + const { path } = cov; + if (this.data[path]) { + this.data[path].merge(cov); + } else { + this.data[path] = cov; + } + } + + /** + * returns the coverage summary for all the file coverage objects in this map. + * @returns {CoverageSummary} + */ + getCoverageSummary() { + const ret = new CoverageSummary(); + Object.values(this.data).forEach(fc => { + ret.merge(fc.toSummary()); + }); + + return ret; + } +} + +module.exports = { + CoverageMap +}; diff --git a/node_modules/istanbul-lib-coverage/lib/coverage-summary.js b/node_modules/istanbul-lib-coverage/lib/coverage-summary.js new file mode 100644 index 0000000..9b769c6 --- /dev/null +++ b/node_modules/istanbul-lib-coverage/lib/coverage-summary.js @@ -0,0 +1,112 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const percent = require('./percent'); +const dataProperties = require('./data-properties'); + +function blankSummary() { + const empty = () => ({ + total: 0, + covered: 0, + skipped: 0, + pct: 'Unknown' + }); + + return { + lines: empty(), + statements: empty(), + functions: empty(), + branches: empty(), + branchesTrue: empty() + }; +} + +// asserts that a data object "looks like" a summary coverage object +function assertValidSummary(obj) { + const valid = + obj && obj.lines && obj.statements && obj.functions && obj.branches; + if (!valid) { + throw new Error( + 'Invalid summary coverage object, missing keys, found:' + + Object.keys(obj).join(',') + ); + } +} + +/** + * CoverageSummary provides a summary of code coverage . It exposes 4 properties, + * `lines`, `statements`, `branches`, and `functions`. Each of these properties + * is an object that has 4 keys `total`, `covered`, `skipped` and `pct`. + * `pct` is a percentage number (0-100). + */ +class CoverageSummary { + /** + * @constructor + * @param {Object|CoverageSummary} [obj=undefined] an optional data object or + * another coverage summary to initialize this object with. + */ + constructor(obj) { + if (!obj) { + this.data = blankSummary(); + } else if (obj instanceof CoverageSummary) { + this.data = obj.data; + } else { + this.data = obj; + } + assertValidSummary(this.data); + } + + /** + * merges a second summary coverage object into this one + * @param {CoverageSummary} obj - another coverage summary object + */ + merge(obj) { + const keys = [ + 'lines', + 'statements', + 'branches', + 'functions', + 'branchesTrue' + ]; + keys.forEach(key => { + if (obj[key]) { + this[key].total += obj[key].total; + this[key].covered += obj[key].covered; + this[key].skipped += obj[key].skipped; + this[key].pct = percent(this[key].covered, this[key].total); + } + }); + + return this; + } + + /** + * returns a POJO that is JSON serializable. May be used to get the raw + * summary object. + */ + toJSON() { + return this.data; + } + + /** + * return true if summary has no lines of code + */ + isEmpty() { + return this.lines.total === 0; + } +} + +dataProperties(CoverageSummary, [ + 'lines', + 'statements', + 'functions', + 'branches', + 'branchesTrue' +]); + +module.exports = { + CoverageSummary +}; diff --git a/node_modules/istanbul-lib-coverage/lib/data-properties.js b/node_modules/istanbul-lib-coverage/lib/data-properties.js new file mode 100644 index 0000000..3a12d40 --- /dev/null +++ b/node_modules/istanbul-lib-coverage/lib/data-properties.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function dataProperties(klass, properties) { + properties.forEach(p => { + Object.defineProperty(klass.prototype, p, { + enumerable: true, + get() { + return this.data[p]; + } + }); + }); +}; diff --git a/node_modules/istanbul-lib-coverage/lib/file-coverage.js b/node_modules/istanbul-lib-coverage/lib/file-coverage.js new file mode 100644 index 0000000..80a36ab --- /dev/null +++ b/node_modules/istanbul-lib-coverage/lib/file-coverage.js @@ -0,0 +1,345 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const percent = require('./percent'); +const dataProperties = require('./data-properties'); +const { CoverageSummary } = require('./coverage-summary'); + +// returns a data object that represents empty coverage +function emptyCoverage(filePath, reportLogic) { + const cov = { + path: filePath, + statementMap: {}, + fnMap: {}, + branchMap: {}, + s: {}, + f: {}, + b: {} + }; + if (reportLogic) cov.bT = {}; + return cov; +} + +// asserts that a data object "looks like" a coverage object +function assertValidObject(obj) { + const valid = + obj && + obj.path && + obj.statementMap && + obj.fnMap && + obj.branchMap && + obj.s && + obj.f && + obj.b; + if (!valid) { + throw new Error( + 'Invalid file coverage object, missing keys, found:' + + Object.keys(obj).join(',') + ); + } +} + +const keyFromLoc = ({ start, end }) => + `${start.line}|${start.column}|${end.line}|${end.column}`; + +const mergeProp = (aHits, aMap, bHits, bMap, itemKey = keyFromLoc) => { + const aItems = {}; + for (const [key, itemHits] of Object.entries(aHits)) { + const item = aMap[key]; + aItems[itemKey(item)] = [itemHits, item]; + } + for (const [key, bItemHits] of Object.entries(bHits)) { + const bItem = bMap[key]; + const k = itemKey(bItem); + + if (aItems[k]) { + const aPair = aItems[k]; + if (bItemHits.forEach) { + // should this throw an exception if aPair[0] is not an array? + bItemHits.forEach((hits, h) => { + if (aPair[0][h] !== undefined) aPair[0][h] += hits; + else aPair[0][h] = hits; + }); + } else { + aPair[0] += bItemHits; + } + } else { + aItems[k] = [bItemHits, bItem]; + } + } + const hits = {}; + const map = {}; + + Object.values(aItems).forEach(([itemHits, item], i) => { + hits[i] = itemHits; + map[i] = item; + }); + + return [hits, map]; +}; + +/** + * provides a read-only view of coverage for a single file. + * The deep structure of this object is documented elsewhere. It has the following + * properties: + * + * * `path` - the file path for which coverage is being tracked + * * `statementMap` - map of statement locations keyed by statement index + * * `fnMap` - map of function metadata keyed by function index + * * `branchMap` - map of branch metadata keyed by branch index + * * `s` - hit counts for statements + * * `f` - hit count for functions + * * `b` - hit count for branches + */ +class FileCoverage { + /** + * @constructor + * @param {Object|FileCoverage|String} pathOrObj is a string that initializes + * and empty coverage object with the specified file path or a data object that + * has all the required properties for a file coverage object. + */ + constructor(pathOrObj, reportLogic = false) { + if (!pathOrObj) { + throw new Error( + 'Coverage must be initialized with a path or an object' + ); + } + if (typeof pathOrObj === 'string') { + this.data = emptyCoverage(pathOrObj, reportLogic); + } else if (pathOrObj instanceof FileCoverage) { + this.data = pathOrObj.data; + } else if (typeof pathOrObj === 'object') { + this.data = pathOrObj; + } else { + throw new Error('Invalid argument to coverage constructor'); + } + assertValidObject(this.data); + } + + /** + * returns computed line coverage from statement coverage. + * This is a map of hits keyed by line number in the source. + */ + getLineCoverage() { + const statementMap = this.data.statementMap; + const statements = this.data.s; + const lineMap = Object.create(null); + + Object.entries(statements).forEach(([st, count]) => { + /* istanbul ignore if: is this even possible? */ + if (!statementMap[st]) { + return; + } + const { line } = statementMap[st].start; + const prevVal = lineMap[line]; + if (prevVal === undefined || prevVal < count) { + lineMap[line] = count; + } + }); + return lineMap; + } + + /** + * returns an array of uncovered line numbers. + * @returns {Array} an array of line numbers for which no hits have been + * collected. + */ + getUncoveredLines() { + const lc = this.getLineCoverage(); + const ret = []; + Object.entries(lc).forEach(([l, hits]) => { + if (hits === 0) { + ret.push(l); + } + }); + return ret; + } + + /** + * returns a map of branch coverage by source line number. + * @returns {Object} an object keyed by line number. Each object + * has a `covered`, `total` and `coverage` (percentage) property. + */ + getBranchCoverageByLine() { + const branchMap = this.branchMap; + const branches = this.b; + const ret = {}; + Object.entries(branchMap).forEach(([k, map]) => { + const line = map.line || map.loc.start.line; + const branchData = branches[k]; + ret[line] = ret[line] || []; + ret[line].push(...branchData); + }); + Object.entries(ret).forEach(([k, dataArray]) => { + const covered = dataArray.filter(item => item > 0); + const coverage = (covered.length / dataArray.length) * 100; + ret[k] = { + covered: covered.length, + total: dataArray.length, + coverage + }; + }); + return ret; + } + + /** + * return a JSON-serializable POJO for this file coverage object + */ + toJSON() { + return this.data; + } + + /** + * merges a second coverage object into this one, updating hit counts + * @param {FileCoverage} other - the coverage object to be merged into this one. + * Note that the other object should have the same structure as this one (same file). + */ + merge(other) { + if (other.all === true) { + return; + } + + if (this.all === true) { + this.data = other.data; + return; + } + + let [hits, map] = mergeProp( + this.s, + this.statementMap, + other.s, + other.statementMap + ); + this.data.s = hits; + this.data.statementMap = map; + + const keyFromLocProp = x => keyFromLoc(x.loc); + const keyFromLocationsProp = x => keyFromLoc(x.locations[0]); + + [hits, map] = mergeProp( + this.f, + this.fnMap, + other.f, + other.fnMap, + keyFromLocProp + ); + this.data.f = hits; + this.data.fnMap = map; + + [hits, map] = mergeProp( + this.b, + this.branchMap, + other.b, + other.branchMap, + keyFromLocationsProp + ); + this.data.b = hits; + this.data.branchMap = map; + + // Tracking additional information about branch truthiness + // can be optionally enabled: + if (this.bT && other.bT) { + [hits, map] = mergeProp( + this.bT, + this.branchMap, + other.bT, + other.branchMap, + keyFromLocationsProp + ); + this.data.bT = hits; + } + } + + computeSimpleTotals(property) { + let stats = this[property]; + + if (typeof stats === 'function') { + stats = stats.call(this); + } + + const ret = { + total: Object.keys(stats).length, + covered: Object.values(stats).filter(v => !!v).length, + skipped: 0 + }; + ret.pct = percent(ret.covered, ret.total); + return ret; + } + + computeBranchTotals(property) { + const stats = this[property]; + const ret = { total: 0, covered: 0, skipped: 0 }; + + Object.values(stats).forEach(branches => { + ret.covered += branches.filter(hits => hits > 0).length; + ret.total += branches.length; + }); + ret.pct = percent(ret.covered, ret.total); + return ret; + } + + /** + * resets hit counts for all statements, functions and branches + * in this coverage object resulting in zero coverage. + */ + resetHits() { + const statements = this.s; + const functions = this.f; + const branches = this.b; + const branchesTrue = this.bT; + Object.keys(statements).forEach(s => { + statements[s] = 0; + }); + Object.keys(functions).forEach(f => { + functions[f] = 0; + }); + Object.keys(branches).forEach(b => { + branches[b].fill(0); + }); + // Tracking additional information about branch truthiness + // can be optionally enabled: + if (branchesTrue) { + Object.keys(branchesTrue).forEach(bT => { + branchesTrue[bT].fill(0); + }); + } + } + + /** + * returns a CoverageSummary for this file coverage object + * @returns {CoverageSummary} + */ + toSummary() { + const ret = {}; + ret.lines = this.computeSimpleTotals('getLineCoverage'); + ret.functions = this.computeSimpleTotals('f', 'fnMap'); + ret.statements = this.computeSimpleTotals('s', 'statementMap'); + ret.branches = this.computeBranchTotals('b'); + // Tracking additional information about branch truthiness + // can be optionally enabled: + if (this['bt']) { + ret.branchesTrue = this.computeBranchTotals('bT'); + } + return new CoverageSummary(ret); + } +} + +// expose coverage data attributes +dataProperties(FileCoverage, [ + 'path', + 'statementMap', + 'fnMap', + 'branchMap', + 's', + 'f', + 'b', + 'bT', + 'all' +]); + +module.exports = { + FileCoverage +}; diff --git a/node_modules/istanbul-lib-coverage/lib/percent.js b/node_modules/istanbul-lib-coverage/lib/percent.js new file mode 100644 index 0000000..c7b7aaf --- /dev/null +++ b/node_modules/istanbul-lib-coverage/lib/percent.js @@ -0,0 +1,15 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +module.exports = function percent(covered, total) { + let tmp; + if (total > 0) { + tmp = (1000 * 100 * covered) / total; + return Math.floor(tmp / 10) / 100; + } else { + return 100.0; + } +}; diff --git a/node_modules/istanbul-lib-coverage/package.json b/node_modules/istanbul-lib-coverage/package.json new file mode 100644 index 0000000..628584f --- /dev/null +++ b/node_modules/istanbul-lib-coverage/package.json @@ -0,0 +1,47 @@ +{ + "name": "istanbul-lib-coverage", + "version": "3.2.0", + "description": "Data library for istanbul coverage objects", + "author": "Krishnan Anantheswaran ", + "main": "index.js", + "files": [ + "lib", + "index.js" + ], + "scripts": { + "test": "nyc mocha" + }, + "devDependencies": { + "chai": "^4.2.0", + "mocha": "^6.2.2", + "nyc": "^15.0.0-beta.2" + }, + "karmaDeps": { + "browserify-istanbul": "^0.2.1", + "karma": "^0.13.10", + "karma-browserify": "^4.2.1", + "karma-chrome-launcher": "^0.2.0", + "karma-coverage": "^0.4.2", + "karma-mocha": "^0.2.0", + "karma-phantomjs-launcher": "^0.2.0", + "phantomjs": "^1.9.17" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/istanbuljs/istanbuljs.git", + "directory": "packages/istanbul-lib-coverage" + }, + "keywords": [ + "istanbul", + "coverage", + "data" + ], + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/istanbuljs/istanbuljs/issues" + }, + "homepage": "https://istanbul.js.org/", + "engines": { + "node": ">=8" + } +} diff --git a/node_modules/istanbul-lib-instrument/CHANGELOG.md b/node_modules/istanbul-lib-instrument/CHANGELOG.md new file mode 100644 index 0000000..8bd7e53 --- /dev/null +++ b/node_modules/istanbul-lib-instrument/CHANGELOG.md @@ -0,0 +1,642 @@ +# Change Log + +All notable changes to this project will be documented in this file. +See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. + +## [6.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v5.2.1...istanbul-lib-instrument-v6.0.0) (2023-07-25) + + +### ⚠ BREAKING CHANGES + +* **deps:** minimum Node version bumped to 10. + +### Bug Fixes + +* **deps:** upgrade semver CVE-2022-25883 ([#731](https://github.com/istanbuljs/istanbuljs/issues/731)) ([d8399f3](https://github.com/istanbuljs/istanbuljs/commit/d8399f39eab6767a6fca5ef3b1b458a14d48775a)) + +## [5.2.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v5.2.0...istanbul-lib-instrument-v5.2.1) (2022-10-05) + + +### Bug Fixes + +* handle error when inputSourceMap is not a plain object ([#662](https://github.com/istanbuljs/istanbuljs/issues/662)) ([3e3611f](https://github.com/istanbuljs/istanbuljs/commit/3e3611f0efffefd5f87e6cbccd840e9f33aaf43e)) + +## [5.2.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v5.1.0...istanbul-lib-instrument-v5.2.0) (2022-02-21) + + +### Features + +* exclude Empty Object and Arrays in Truthy Detection ([#666](https://github.com/istanbuljs/istanbuljs/issues/666)) ([e279684](https://github.com/istanbuljs/istanbuljs/commit/e279684e735f4b7dbe2b632cde2515f6862099de)) + +## [5.1.0](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v5.0.4...istanbul-lib-instrument-v5.1.0) (2021-10-27) + + +### Features + +* option to evaluate logical truthiness, for applications such as fuzzing ([#629](https://www.github.com/istanbuljs/istanbuljs/issues/629)) ([a743b84](https://www.github.com/istanbuljs/istanbuljs/commit/a743b8442e977f0c77ffa282eed7ac84ca200d1f)) + +### [5.0.4](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v5.0.3...istanbul-lib-instrument-v5.0.4) (2021-10-16) + + +### Bug Fixes + +* **magic-value:** make incrementing magic value a manual step ([#641](https://www.github.com/istanbuljs/istanbuljs/issues/641)) ([823010b](https://www.github.com/istanbuljs/istanbuljs/commit/823010b821cf81bd91377d75fc83f0875925db66)) + +### [5.0.3](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v5.0.2...istanbul-lib-instrument-v5.0.3) (2021-10-06) + + +### Bug Fixes + +* coverage.branchMap else location. ([#633](https://www.github.com/istanbuljs/istanbuljs/issues/633)) ([eb4b4ec](https://www.github.com/istanbuljs/istanbuljs/commit/eb4b4ec8f4b858655a66b0033fcc662f44ef4cc9)) + +### [5.0.2](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v5.0.1...istanbul-lib-instrument-v5.0.2) (2021-09-13) + + +### Bug Fixes + +* **build:** verfiy automated publication ([b232690](https://www.github.com/istanbuljs/istanbuljs/commit/b232690193f4b524332046c96dd1cdc6e881c6c7)) + +### [5.0.1](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v5.0.0...istanbul-lib-instrument-v5.0.1) (2021-09-13) + + +### Bug Fixes + +* **build:** verfiy automated publication ([74c96bd](https://www.github.com/istanbuljs/istanbuljs/commit/74c96bdc4224a06e2e1166ebd9adf8faf28438b1)) + +## [5.0.0](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument-v4.0.3...istanbul-lib-instrument-v5.0.0) (2021-09-13) + + +### ⚠ BREAKING CHANGES + +* istanbul-lib-instrument no longer uses babel + +### Code Refactoring + +* istanbul-lib-instrument no longer uses babel ([8d3badb](https://www.github.com/istanbuljs/istanbuljs/commit/8d3badb8f6c9a4bed9af8e19c3ac6459ebd7267b)) + +## [4.0.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@4.0.2...istanbul-lib-instrument@4.0.3) (2020-05-09) + + +### Bug Fixes + +* Prevent readInitialCoverage from reading babel config ([#562](https://github.com/istanbuljs/istanbuljs/issues/562)) ([49b4745](https://github.com/istanbuljs/istanbuljs/commit/49b474525c15e703642916011bd86f663aca0c3d)) + + + + + +## [4.0.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@4.0.1...istanbul-lib-instrument@4.0.2) (2020-05-06) + + +### Bug Fixes + +* Add ts-ignore to reassignment of generated function ([#557](https://github.com/istanbuljs/istanbuljs/issues/557)) ([817efb0](https://github.com/istanbuljs/istanbuljs/commit/817efb04fc161efae426b2231a0221606b09f559)) +* Use @babel/core for all babel imports. ([#555](https://github.com/istanbuljs/istanbuljs/issues/555)) ([a99a13e](https://github.com/istanbuljs/istanbuljs/commit/a99a13ee6931fc124a2a723c3f511cdbcb0aa81d)) + + + + + +## [4.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@4.0.0...istanbul-lib-instrument@4.0.1) (2020-02-03) + + +### Bug Fixes + +* Always call coverage initialization function ([#524](https://github.com/istanbuljs/istanbuljs/issues/524)) ([c6536c1](https://github.com/istanbuljs/istanbuljs/commit/c6536c14bf0663ca7e0493dd40ea132b05352594)) + + + + + +# [4.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@4.0.0-alpha.3...istanbul-lib-instrument@4.0.0) (2019-12-20) + +**Note:** Version bump only for package istanbul-lib-instrument + + + + + +# [4.0.0-alpha.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@4.0.0-alpha.2...istanbul-lib-instrument@4.0.0-alpha.3) (2019-12-07) + +**Note:** Version bump only for package istanbul-lib-instrument + + + + + +# [4.0.0-alpha.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@4.0.0-alpha.1...istanbul-lib-instrument@4.0.0-alpha.2) (2019-11-01) + + +### Bug Fixes + +* Produce properly merged source-maps when inputSourceMap is provided ([#487](https://github.com/istanbuljs/istanbuljs/issues/487)) ([8f8c88e](https://github.com/istanbuljs/istanbuljs/commit/8f8c88e3a2add4c08729e41e356aa7981dc69d4d)) + + + + + +# [4.0.0-alpha.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@4.0.0-alpha.0...istanbul-lib-instrument@4.0.0-alpha.1) (2019-10-06) + + +### Bug Fixes + +* Eliminate babel hoisting of the coverage variable ([#481](https://github.com/istanbuljs/istanbuljs/issues/481)) ([8dfbcba](https://github.com/istanbuljs/istanbuljs/commit/8dfbcba)), closes [#92](https://github.com/istanbuljs/istanbuljs/issues/92) +* Honor ignore hints in chained if statements ([#469](https://github.com/istanbuljs/istanbuljs/issues/469)) ([a629770](https://github.com/istanbuljs/istanbuljs/commit/a629770)), closes [#468](https://github.com/istanbuljs/istanbuljs/issues/468) +* Populate lastFileCoverage for already instrumented files ([#470](https://github.com/istanbuljs/istanbuljs/issues/470)) ([ea6d779](https://github.com/istanbuljs/istanbuljs/commit/ea6d779)), closes [istanbuljs/nyc#594](https://github.com/istanbuljs/nyc/issues/594) + + +### Features + +* Use @istanbuljs/schema to pull defaults ([#485](https://github.com/istanbuljs/istanbuljs/issues/485)) ([87e27f3](https://github.com/istanbuljs/istanbuljs/commit/87e27f3)), closes [#460](https://github.com/istanbuljs/istanbuljs/issues/460) + + +### BREAKING CHANGES + +* The defaults for `autoWrap`, `preserveComments`, +`esModules` and `produceSourceMap` are now true. This applies only to +the stand-alone instrumenter, the visitor does not use these options. +* The `flow` and `jsx` parser plugins are no longer +enabled by default. This applies only to the stand-alone instrumenter, +the visitor does not use this option. +* The `plugins` option of the stand-alone instrumenter +has been renamed to `parserPlugins` to match nyc. + + + + + +# [4.0.0-alpha.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@3.3.0...istanbul-lib-instrument@4.0.0-alpha.0) (2019-06-19) + + +### Features + +* Update dependencies, require Node.js 8 ([#401](https://github.com/istanbuljs/istanbuljs/issues/401)) ([bf3a539](https://github.com/istanbuljs/istanbuljs/commit/bf3a539)) + + +### BREAKING CHANGES + +* Node.js 8 is now required + + + + + +# [3.3.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@3.2.0...istanbul-lib-instrument@3.3.0) (2019-04-24) + + +### Features + +* Enable classProperties and classPrivateProperties parsers and coverage. ([#379](https://github.com/istanbuljs/istanbuljs/issues/379)) ([c09dc38](https://github.com/istanbuljs/istanbuljs/commit/c09dc38)) + + + + + +# [3.2.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@3.1.2...istanbul-lib-instrument@3.2.0) (2019-04-09) + + +### Features + +* Add bigInt and importMeta to default parser plugins. ([#356](https://github.com/istanbuljs/istanbuljs/issues/356)) ([fb4d6ed](https://github.com/istanbuljs/istanbuljs/commit/fb4d6ed)), closes [#338](https://github.com/istanbuljs/istanbuljs/issues/338) + + + + + +## [3.1.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@3.1.1...istanbul-lib-instrument@3.1.2) (2019-04-03) + + +### Bug Fixes + +* Be more friendly to ts-node. ([#352](https://github.com/istanbuljs/istanbuljs/issues/352)) ([40d15f5](https://github.com/istanbuljs/istanbuljs/commit/40d15f5)), closes [#336](https://github.com/istanbuljs/istanbuljs/issues/336) + + + + + +## [3.1.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@3.1.0...istanbul-lib-instrument@3.1.1) (2019-03-12) + + +### Bug Fixes + +* Honor istanbul ignore next hints placed before export statement. ([#298](https://github.com/istanbuljs/istanbuljs/issues/298)) ([f24795d](https://github.com/istanbuljs/istanbuljs/commit/f24795d)), closes [#297](https://github.com/istanbuljs/istanbuljs/issues/297) + + + + + +# [3.1.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@3.0.1...istanbul-lib-instrument@3.1.0) (2019-01-26) + + +### Features + +* dont skip for loop initialization instrumentation ([#188](https://github.com/istanbuljs/istanbuljs/issues/188)) ([2e0258e](https://github.com/istanbuljs/istanbuljs/commit/2e0258e)) +* New options coverageGlobalScope and coverageGlobalScopeFunc. ([#200](https://github.com/istanbuljs/istanbuljs/issues/200)) ([25509c7](https://github.com/istanbuljs/istanbuljs/commit/25509c7)), closes [#199](https://github.com/istanbuljs/istanbuljs/issues/199) + + + + + + +## [3.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@3.0.0...istanbul-lib-instrument@3.0.1) (2018-12-25) + + + + +**Note:** Version bump only for package istanbul-lib-instrument + + +# [3.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.3.2...istanbul-lib-instrument@3.0.0) (2018-09-06) + + +### Chores + +* Update test for babel 7. ([#218](https://github.com/istanbuljs/istanbuljs/issues/218)) ([9cf4d43](https://github.com/istanbuljs/istanbuljs/commit/9cf4d43)), closes [#205](https://github.com/istanbuljs/istanbuljs/issues/205) + + +### Features + +* Add option plugins ([#205](https://github.com/istanbuljs/istanbuljs/issues/205)) ([312f81f](https://github.com/istanbuljs/istanbuljs/commit/312f81f)) +* Update babel to 7.0.0. ([#215](https://github.com/istanbuljs/istanbuljs/issues/215)) ([8a96613](https://github.com/istanbuljs/istanbuljs/commit/8a96613)) + + +### BREAKING CHANGES + +* was added which requires an option for the `decorators` +plugin. Add it to get tests working again, commit updated api.md. + + + + + +## [2.3.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.3.1...istanbul-lib-instrument@2.3.2) (2018-07-24) + + + + +**Note:** Version bump only for package istanbul-lib-instrument + + +## [2.3.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.3.0...istanbul-lib-instrument@2.3.1) (2018-07-07) + + +### Bug Fixes + +* Don't ignore src/visitor.js for self test. ([#194](https://github.com/istanbuljs/istanbuljs/issues/194)) ([71b815d](https://github.com/istanbuljs/istanbuljs/commit/71b815d)) + + + + + +# [2.3.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.2.1...istanbul-lib-instrument@2.3.0) (2018-06-27) + + +### Features + +* update pinned babel version to latest release. ([#189](https://github.com/istanbuljs/istanbuljs/issues/189)) ([ac8ec07](https://github.com/istanbuljs/istanbuljs/commit/ac8ec07)) + + + + + +## [2.2.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.2.0...istanbul-lib-instrument@2.2.1) (2018-06-26) + + +### Bug Fixes + +* Instrument ObjectMethod's. ([#182](https://github.com/istanbuljs/istanbuljs/issues/182)) ([126f09d](https://github.com/istanbuljs/istanbuljs/commit/126f09d)) +* update default args test guard to work on supported versions. ([#185](https://github.com/istanbuljs/istanbuljs/issues/185)) ([955511a](https://github.com/istanbuljs/istanbuljs/commit/955511a)) + + + + + +# [2.2.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.0.2...istanbul-lib-instrument@2.2.0) (2018-06-06) + + +### Features + +* add support for optional catch binding ([#175](https://github.com/istanbuljs/istanbuljs/issues/175)) ([088dd9f](https://github.com/istanbuljs/istanbuljs/commit/088dd9f)) + + + + + +# [2.1.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.0.2...istanbul-lib-instrument@2.1.0) (2018-05-31) + + +### Features + +* add support for optional catch binding ([#175](https://github.com/istanbuljs/istanbuljs/issues/175)) ([088dd9f](https://github.com/istanbuljs/istanbuljs/commit/088dd9f)) + + + + + +## [2.0.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.0.1...istanbul-lib-instrument@2.0.2) (2018-05-31) + + + + +**Note:** Version bump only for package istanbul-lib-instrument + + +## [2.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.0.0...istanbul-lib-instrument@2.0.1) (2018-05-31) + + +### Bug Fixes + +* should import [@babel](https://github.com/babel)/template ([85a0d1a](https://github.com/istanbuljs/istanbuljs/commit/85a0d1a)) + + + + + +# [2.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.10.1...istanbul-lib-instrument@2.0.0) (2018-05-31) + + +### Bug Fixes + +* parenthesize superClass on non-idetifier case ([#158](https://github.com/istanbuljs/istanbuljs/issues/158)) ([6202c88](https://github.com/istanbuljs/istanbuljs/commit/6202c88)) + + +### Chores + +* upgrade babel in instrumenter ([#174](https://github.com/istanbuljs/istanbuljs/issues/174)) ([ce23e91](https://github.com/istanbuljs/istanbuljs/commit/ce23e91)) + + +### BREAKING CHANGES + +* babel@7 drops Node@4 support + + + + + +## [1.10.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.10.0...istanbul-lib-instrument@1.10.1) (2018-03-09) + + +### Bug Fixes + +* default value for ignorelassMethods ([#151](https://github.com/istanbuljs/istanbuljs/issues/151)) ([5dd88e8](https://github.com/istanbuljs/istanbuljs/commit/5dd88e8)) + + + + + +# [1.10.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.9.2...istanbul-lib-instrument@1.10.0) (2018-03-04) + + +### Features + +* allows an array of ignored method names to be provided ([#127](https://github.com/istanbuljs/istanbuljs/issues/127)) ([67918e2](https://github.com/istanbuljs/istanbuljs/commit/67918e2)) + + + + + +## [1.9.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.9.1...istanbul-lib-instrument@1.9.2) (2018-02-13) + + +### Bug Fixes + +* compatibility with babel 7 ([#135](https://github.com/istanbuljs/istanbuljs/issues/135)) ([6cac849](https://github.com/istanbuljs/istanbuljs/commit/6cac849)) +* handle instrumentation when a function is called Function ([#131](https://github.com/istanbuljs/istanbuljs/issues/131)) ([b12a07e](https://github.com/istanbuljs/istanbuljs/commit/b12a07e)) +* proper passing of the preserveComments option to babel ([#122](https://github.com/istanbuljs/istanbuljs/issues/122)) ([470bb0e](https://github.com/istanbuljs/istanbuljs/commit/470bb0e)) +* update instrument, account for lack of arrow expression ([#119](https://github.com/istanbuljs/istanbuljs/issues/119)) ([#125](https://github.com/istanbuljs/istanbuljs/issues/125)) ([0968206](https://github.com/istanbuljs/istanbuljs/commit/0968206)) + + + + + +## [1.9.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.9.0...istanbul-lib-instrument@1.9.1) (2017-10-22) + + +### Bug Fixes + +* address issue with class instrumentation ([#111](https://github.com/istanbuljs/istanbuljs/issues/111)) ([cbd1c14](https://github.com/istanbuljs/istanbuljs/commit/cbd1c14)) + + + + + +# [1.9.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.8.0...istanbul-lib-instrument@1.9.0) (2017-10-21) + + +### Bug Fixes + +* support conditional expression for superClass ([#106](https://github.com/istanbuljs/istanbuljs/issues/106)) ([aae256f](https://github.com/istanbuljs/istanbuljs/commit/aae256f)) + + +### Features + +* add support for ignoring entire files ([#108](https://github.com/istanbuljs/istanbuljs/issues/108)) ([f12da65](https://github.com/istanbuljs/istanbuljs/commit/f12da65)) + + + + + +# [1.8.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.7.5...istanbul-lib-instrument@1.8.0) (2017-09-05) + + +### Features + +* add support for object-spread syntax ([#82](https://github.com/istanbuljs/istanbuljs/issues/82)) ([28d5566](https://github.com/istanbuljs/istanbuljs/commit/28d5566)) + + + + + +## [1.7.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.7.4...istanbul-lib-instrument@1.7.5) (2017-08-23) + + +### Bug Fixes + +* name of function is now preserved or named exports ([#79](https://github.com/istanbuljs/istanbuljs/issues/79)) ([2ce8974](https://github.com/istanbuljs/istanbuljs/commit/2ce8974)) + + + + + +## [1.7.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.7.3...istanbul-lib-instrument@1.7.4) (2017-07-16) + + +### Bug Fixes + +* update increment operator to appropriate expression type ([#74](https://github.com/istanbuljs/istanbuljs/issues/74)) ([dc69e66](https://github.com/istanbuljs/istanbuljs/commit/dc69e66)) + + + + + +## [1.7.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.7.2...istanbul-lib-instrument@1.7.3) (2017-06-25) + + + + + +## [1.7.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@1.7.1...istanbul-lib-instrument@1.7.2) (2017-05-27) + + +### Bug Fixes + +* hoist statement counter for class variables, so that name is preserved ([#60](https://github.com/istanbuljs/istanbuljs/issues/60)) ([120d221](https://github.com/istanbuljs/istanbuljs/commit/120d221)) + + + + + +## [1.7.1](https://github.com/istanbuljs/istanbul-lib-instrument/compare/istanbul-lib-instrument@1.7.0...istanbul-lib-instrument@1.7.1) (2017-04-29) + + +### Bug Fixes + +* don't instrument a file if it has already been instrumented ([#38](https://github.com/istanbuljs/istanbuljs/issues/38)) ([9c38e4e](https://github.com/istanbuljs/istanbul-lib-instrument/commit/9c38e4e)) + + + + + +# [1.7.0](https://github.com/istanbuljs/istanbul-lib-instrument/compare/istanbul-lib-instrument@1.6.2...istanbul-lib-instrument@1.7.0) (2017-03-27) + + +### Features + +* use extended babylon support; adding features such as jsx ([#22](https://github.com/istanbuljs/istanbuljs/issues/22)) ([11c2438](https://github.com/istanbuljs/istanbul-lib-instrument/commit/11c2438)) + + +## [1.6.2](https://github.com/istanbuljs/istanbul-lib-instrument/compare/istanbul-lib-instrument@1.6.1...istanbul-lib-instrument@1.6.2) (2017-03-22) + + +### Bug Fixes + +* loc is sometimes not defined, so loc.start fails see [#99](https://github.com/istanbuljs/istanbuljs/issues/99) ([#18](https://github.com/istanbuljs/istanbuljs/issues/18)) ([df85ba6](https://github.com/istanbuljs/istanbul-lib-instrument/commit/df85ba6)) + + +## [1.6.1](https://github.com/istanbuljs/istanbul-lib-instrument/compare/istanbul-lib-instrument@1.6.0...istanbul-lib-instrument@1.6.1) (2017-03-21) + + +# [1.6.0](https://github.com/istanbuljs/istanbul-lib-instrument/compare/istanbul-lib-instrument@1.4.2...istanbul-lib-instrument@1.6.0) (2017-03-21) + + +### Features + +* adds line number property back to coverage.json ([b03b927](https://github.com/istanbuljs/istanbul-lib-instrument/commit/b03b927)) + + +## [1.4.2](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.4.1...v1.4.2) (2017-01-04) + + +### Bug Fixes + +* only hoist counter for a smaller subset of function declarations ([9f8931e](https://github.com/istanbuljs/istanbul-lib-instrument/commit/9f8931e)) + + + + +## [1.4.1](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.4.0...v1.4.1) (2017-01-04) + + +### Bug Fixes + +* address regression discussed in https://github.com/istanbuljs/babel-plugin-istanbul/issues/78 ([#40](https://github.com/istanbuljs/istanbul-lib-instrument/issues/40)) ([7f458a3](https://github.com/istanbuljs/istanbul-lib-instrument/commit/7f458a3)) + + + + +# [1.4.0](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.3.1...v1.4.0) (2017-01-02) + + +### Features + +* preserve inferred function names ([#38](https://github.com/istanbuljs/istanbul-lib-instrument/issues/38)) ([312666e](https://github.com/istanbuljs/istanbul-lib-instrument/commit/312666e)) + + + + +## [1.3.1](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.3.0...v1.3.1) (2016-12-27) + + +### Bug Fixes + +* function declaration assignment now retains function name ([#33](https://github.com/istanbuljs/istanbul-lib-instrument/issues/33)) ([2d781da](https://github.com/istanbuljs/istanbul-lib-instrument/commit/2d781da)) + + + + +# [1.3.0](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.2.0...v1.3.0) (2016-11-10) + + +### Features + +* allow an input source-map to be passed to instrumentSync() ([#23](https://github.com/istanbuljs/istanbul-lib-instrument/issues/23)) ([b08e4f5](https://github.com/istanbuljs/istanbul-lib-instrument/commit/b08e4f5)) + + + + +# [1.2.0](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.1.4...v1.2.0) (2016-10-25) + + +### Features + +* implement function to extract empty coverage data from an instrumented file ([#28](https://github.com/istanbuljs/istanbul-lib-instrument/issues/28)) ([06d0ef6](https://github.com/istanbuljs/istanbul-lib-instrument/commit/06d0ef6)) + + + + +## [1.1.4](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.1.3...v1.1.4) (2016-10-17) + + +### Bug Fixes + +* hoist coverage variable to very top of file ([#26](https://github.com/istanbuljs/istanbul-lib-instrument/issues/26)) ([0225e8c](https://github.com/istanbuljs/istanbul-lib-instrument/commit/0225e8c)) + + + + +## [1.1.3](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.1.2...v1.1.3) (2016-09-13) + + +### Performance Improvements + +* simplify coverage variable naming https://github.com/istanbuljs/istanbul-lib-instrument/pull/24 ([7252aae](https://github.com/istanbuljs/istanbul-lib-instrument/commit/7252aae)) + + + + +## [1.1.2](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.1.1...v1.1.2) (2016-09-08) + + +### Performance Improvements + +* use zero-based numeric indices for much faster instrumented code ([#22](https://github.com/istanbuljs/istanbul-lib-instrument/issues/22)) ([5b401f5](https://github.com/istanbuljs/istanbul-lib-instrument/commit/5b401f5)) + + + + +## [1.1.1](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.1.0...v1.1.1) (2016-08-30) + + +### Bug Fixes + +* upgrade istanbul-lib-coverage ([eb9b1f6](https://github.com/istanbuljs/istanbul-lib-instrument/commit/eb9b1f6)) + + + + +# [1.1.0](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.1.0-alpha.4...v1.1.0) (2016-08-11) + + +### Bug Fixes + +* guard against invalid loc ([#16](https://github.com/istanbuljs/istanbul-lib-instrument/issues/16)) ([23ebfc3](https://github.com/istanbuljs/istanbul-lib-instrument/commit/23ebfc3)) + + + + +# [1.1.0-alpha.4](https://github.com/istanbuljs/istanbul-lib-instrument/compare/v1.0.0-alpha.5...v1.1.0-alpha.4) (2016-07-20) + + +### Bug Fixes + +* require more performant babel-generator ([#15](https://github.com/istanbuljs/istanbul-lib-instrument/issues/15)) ([21b2563](https://github.com/istanbuljs/istanbul-lib-instrument/commit/21b2563)) diff --git a/node_modules/istanbul-lib-instrument/LICENSE b/node_modules/istanbul-lib-instrument/LICENSE new file mode 100644 index 0000000..d55d291 --- /dev/null +++ b/node_modules/istanbul-lib-instrument/LICENSE @@ -0,0 +1,24 @@ +Copyright 2012-2015 Yahoo! Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * 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. + * Neither the name of the Yahoo! Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. 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. diff --git a/node_modules/istanbul-lib-instrument/README.md b/node_modules/istanbul-lib-instrument/README.md new file mode 100644 index 0000000..902831c --- /dev/null +++ b/node_modules/istanbul-lib-instrument/README.md @@ -0,0 +1,22 @@ +## istanbul-lib-instrument + +[![Build Status](https://travis-ci.org/istanbuljs/istanbul-lib-instrument.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-lib-instrument) + +Istanbul instrumenter library. + +Version 1.1.x now implements instrumentation using `Babel`. The implementation is inspired +by prior art by @dtinth as demonstrated in the `__coverage__` babel plugin. + +It provides 2 "modes" of instrumentation. + +- The old API that is mostly unchanged (except for incompatibilities noted) and + performs the instrumentation using babel as a library. + +- A `programVisitor` function for the Babel AST that can be used by a Babel plugin + to emit instrumentation for ES6 code directly without any source map + processing. This is the preferred path for babel users. The Babel plugin is + called `babel-plugin-istanbul`. + +Incompatibilities and changes to instrumentation behavior can be found in +[v0-changes.md](v0-changes.md). + diff --git a/node_modules/istanbul-lib-instrument/package.json b/node_modules/istanbul-lib-instrument/package.json new file mode 100644 index 0000000..5305064 --- /dev/null +++ b/node_modules/istanbul-lib-instrument/package.json @@ -0,0 +1,50 @@ +{ + "name": "istanbul-lib-instrument", + "version": "6.0.0", + "description": "Core istanbul API for JS code coverage", + "author": "Krishnan Anantheswaran ", + "main": "src/index.js", + "files": [ + "src" + ], + "scripts": { + "test": "nyc mocha" + }, + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "devDependencies": { + "@babel/cli": "^7.7.5", + "chai": "^4.2.0", + "clone": "^2.1.2", + "debug": "^4.1.1", + "documentation": "^12.1.4", + "js-yaml": "^3.13.1", + "mocha": "^6.2.3", + "nopt": "^4.0.1", + "nyc": "^15.1.0" + }, + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/istanbuljs/istanbuljs/issues" + }, + "homepage": "https://istanbul.js.org/", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/istanbuljs/istanbuljs.git", + "directory": "packages/istanbul-lib-instrument" + }, + "keywords": [ + "coverage", + "istanbul", + "js", + "instrumentation" + ], + "engines": { + "node": ">=10" + } +} diff --git a/node_modules/istanbul-lib-instrument/src/constants.js b/node_modules/istanbul-lib-instrument/src/constants.js new file mode 100644 index 0000000..2cd402b --- /dev/null +++ b/node_modules/istanbul-lib-instrument/src/constants.js @@ -0,0 +1,14 @@ +const { createHash } = require('crypto'); +const { name } = require('../package.json'); +// TODO: increment this version if there are schema changes +// that are not backwards compatible: +const VERSION = '4'; + +const SHA = 'sha1'; +module.exports = { + SHA, + MAGIC_KEY: '_coverageSchema', + MAGIC_VALUE: createHash(SHA) + .update(name + '@' + VERSION) + .digest('hex') +}; diff --git a/node_modules/istanbul-lib-instrument/src/index.js b/node_modules/istanbul-lib-instrument/src/index.js new file mode 100644 index 0000000..33d2a4c --- /dev/null +++ b/node_modules/istanbul-lib-instrument/src/index.js @@ -0,0 +1,21 @@ +const { defaults } = require('@istanbuljs/schema'); +const Instrumenter = require('./instrumenter'); +const programVisitor = require('./visitor'); +const readInitialCoverage = require('./read-coverage'); + +/** + * createInstrumenter creates a new instrumenter with the + * supplied options. + * @param {Object} opts - instrumenter options. See the documentation + * for the Instrumenter class. + */ +function createInstrumenter(opts) { + return new Instrumenter(opts); +} + +module.exports = { + createInstrumenter, + programVisitor, + readInitialCoverage, + defaultOpts: defaults.instrumenter +}; diff --git a/node_modules/istanbul-lib-instrument/src/instrumenter.js b/node_modules/istanbul-lib-instrument/src/instrumenter.js new file mode 100644 index 0000000..3322e6e --- /dev/null +++ b/node_modules/istanbul-lib-instrument/src/instrumenter.js @@ -0,0 +1,162 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const { transformSync } = require('@babel/core'); +const { defaults } = require('@istanbuljs/schema'); +const programVisitor = require('./visitor'); +const readInitialCoverage = require('./read-coverage'); + +/** + * Instrumenter is the public API for the instrument library. + * It is typically used for ES5 code. For ES6 code that you + * are already running under `babel` use the coverage plugin + * instead. + * @param {Object} opts optional. + * @param {string} [opts.coverageVariable=__coverage__] name of global coverage variable. + * @param {boolean} [opts.reportLogic=false] report boolean value of logical expressions. + * @param {boolean} [opts.preserveComments=false] preserve comments in output. + * @param {boolean} [opts.compact=true] generate compact code. + * @param {boolean} [opts.esModules=false] set to true to instrument ES6 modules. + * @param {boolean} [opts.autoWrap=false] set to true to allow `return` statements outside of functions. + * @param {boolean} [opts.produceSourceMap=false] set to true to produce a source map for the instrumented code. + * @param {Array} [opts.ignoreClassMethods=[]] set to array of class method names to ignore for coverage. + * @param {Function} [opts.sourceMapUrlCallback=null] a callback function that is called when a source map URL + * is found in the original code. This function is called with the source file name and the source map URL. + * @param {boolean} [opts.debug=false] - turn debugging on. + * @param {array} [opts.parserPlugins] - set babel parser plugins, see @istanbuljs/schema for defaults. + * @param {string} [opts.coverageGlobalScope=this] the global coverage variable scope. + * @param {boolean} [opts.coverageGlobalScopeFunc=true] use an evaluated function to find coverageGlobalScope. + */ +class Instrumenter { + constructor(opts = {}) { + this.opts = { + ...defaults.instrumenter, + ...opts + }; + this.fileCoverage = null; + this.sourceMap = null; + } + /** + * instrument the supplied code and track coverage against the supplied + * filename. It throws if invalid code is passed to it. ES5 and ES6 syntax + * is supported. To instrument ES6 modules, make sure that you set the + * `esModules` property to `true` when creating the instrumenter. + * + * @param {string} code - the code to instrument + * @param {string} filename - the filename against which to track coverage. + * @param {object} [inputSourceMap] - the source map that maps the not instrumented code back to it's original form. + * Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the + * coverage to the untranspiled source. + * @returns {string} the instrumented code. + */ + instrumentSync(code, filename, inputSourceMap) { + if (typeof code !== 'string') { + throw new Error('Code must be a string'); + } + filename = filename || String(new Date().getTime()) + '.js'; + const { opts } = this; + let output = {}; + const babelOpts = { + configFile: false, + babelrc: false, + ast: true, + filename: filename || String(new Date().getTime()) + '.js', + inputSourceMap, + sourceMaps: opts.produceSourceMap, + compact: opts.compact, + comments: opts.preserveComments, + parserOpts: { + allowReturnOutsideFunction: opts.autoWrap, + sourceType: opts.esModules ? 'module' : 'script', + plugins: opts.parserPlugins + }, + plugins: [ + [ + ({ types }) => { + const ee = programVisitor(types, filename, { + coverageVariable: opts.coverageVariable, + reportLogic: opts.reportLogic, + coverageGlobalScope: opts.coverageGlobalScope, + coverageGlobalScopeFunc: + opts.coverageGlobalScopeFunc, + ignoreClassMethods: opts.ignoreClassMethods, + inputSourceMap + }); + + return { + visitor: { + Program: { + enter: ee.enter, + exit(path) { + output = ee.exit(path); + } + } + } + }; + } + ] + ] + }; + + const codeMap = transformSync(code, babelOpts); + + if (!output || !output.fileCoverage) { + const initialCoverage = + readInitialCoverage(codeMap.ast) || + /* istanbul ignore next: paranoid check */ {}; + this.fileCoverage = initialCoverage.coverageData; + this.sourceMap = inputSourceMap; + return code; + } + + this.fileCoverage = output.fileCoverage; + this.sourceMap = codeMap.map; + const cb = this.opts.sourceMapUrlCallback; + if (cb && output.sourceMappingURL) { + cb(filename, output.sourceMappingURL); + } + + return codeMap.code; + } + /** + * callback-style instrument method that calls back with an error + * as opposed to throwing one. Note that in the current implementation, + * the callback will be called in the same process tick and is not asynchronous. + * + * @param {string} code - the code to instrument + * @param {string} filename - the filename against which to track coverage. + * @param {Function} callback - the callback + * @param {Object} inputSourceMap - the source map that maps the not instrumented code back to it's original form. + * Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the + * coverage to the untranspiled source. + */ + instrument(code, filename, callback, inputSourceMap) { + if (!callback && typeof filename === 'function') { + callback = filename; + filename = null; + } + try { + const out = this.instrumentSync(code, filename, inputSourceMap); + callback(null, out); + } catch (ex) { + callback(ex); + } + } + /** + * returns the file coverage object for the last file instrumented. + * @returns {Object} the file coverage object. + */ + lastFileCoverage() { + return this.fileCoverage; + } + /** + * returns the source map produced for the last file instrumented. + * @returns {null|Object} the source map object. + */ + lastSourceMap() { + return this.sourceMap; + } +} + +module.exports = Instrumenter; diff --git a/node_modules/istanbul-lib-instrument/src/read-coverage.js b/node_modules/istanbul-lib-instrument/src/read-coverage.js new file mode 100644 index 0000000..5b76dbb --- /dev/null +++ b/node_modules/istanbul-lib-instrument/src/read-coverage.js @@ -0,0 +1,77 @@ +const { parseSync, traverse } = require('@babel/core'); +const { defaults } = require('@istanbuljs/schema'); +const { MAGIC_KEY, MAGIC_VALUE } = require('./constants'); + +function getAst(code) { + if (typeof code === 'object' && typeof code.type === 'string') { + // Assume code is already a babel ast. + return code; + } + + if (typeof code !== 'string') { + throw new Error('Code must be a string'); + } + + // Parse as leniently as possible + return parseSync(code, { + babelrc: false, + configFile: false, + parserOpts: { + allowAwaitOutsideFunction: true, + allowImportExportEverywhere: true, + allowReturnOutsideFunction: true, + allowSuperOutsideMethod: true, + sourceType: 'script', + plugins: defaults.instrumenter.parserPlugins + } + }); +} + +module.exports = function readInitialCoverage(code) { + const ast = getAst(code); + + let covScope; + traverse(ast, { + ObjectProperty(path) { + const { node } = path; + if ( + !node.computed && + path.get('key').isIdentifier() && + node.key.name === MAGIC_KEY + ) { + const magicValue = path.get('value').evaluate(); + if (!magicValue.confident || magicValue.value !== MAGIC_VALUE) { + return; + } + covScope = + path.scope.getFunctionParent() || + path.scope.getProgramParent(); + path.stop(); + } + } + }); + + if (!covScope) { + return null; + } + + const result = {}; + + for (const key of ['path', 'hash', 'gcv', 'coverageData']) { + const binding = covScope.getOwnBinding(key); + if (!binding) { + return null; + } + const valuePath = binding.path.get('init'); + const value = valuePath.evaluate(); + if (!value.confident) { + return null; + } + result[key] = value.value; + } + + delete result.coverageData[MAGIC_KEY]; + delete result.coverageData.hash; + + return result; +}; diff --git a/node_modules/istanbul-lib-instrument/src/source-coverage.js b/node_modules/istanbul-lib-instrument/src/source-coverage.js new file mode 100644 index 0000000..ec3f234 --- /dev/null +++ b/node_modules/istanbul-lib-instrument/src/source-coverage.js @@ -0,0 +1,135 @@ +const { classes } = require('istanbul-lib-coverage'); + +function cloneLocation(loc) { + return { + start: { + line: loc && loc.start.line, + column: loc && loc.start.column + }, + end: { + line: loc && loc.end.line, + column: loc && loc.end.column + } + }; +} +/** + * SourceCoverage provides mutation methods to manipulate the structure of + * a file coverage object. Used by the instrumenter to create a full coverage + * object for a file incrementally. + * + * @private + * @param pathOrObj {String|Object} - see the argument for {@link FileCoverage} + * @extends FileCoverage + * @constructor + */ +class SourceCoverage extends classes.FileCoverage { + constructor(pathOrObj) { + super(pathOrObj); + this.meta = { + last: { + s: 0, + f: 0, + b: 0 + } + }; + } + + newStatement(loc) { + const s = this.meta.last.s; + this.data.statementMap[s] = cloneLocation(loc); + this.data.s[s] = 0; + this.meta.last.s += 1; + return s; + } + + newFunction(name, decl, loc) { + const f = this.meta.last.f; + name = name || '(anonymous_' + f + ')'; + this.data.fnMap[f] = { + name, + decl: cloneLocation(decl), + loc: cloneLocation(loc), + // DEPRECATED: some legacy reports require this info. + line: loc && loc.start.line + }; + this.data.f[f] = 0; + this.meta.last.f += 1; + return f; + } + + newBranch(type, loc, isReportLogic = false) { + const b = this.meta.last.b; + this.data.b[b] = []; + this.data.branchMap[b] = { + loc: cloneLocation(loc), + type, + locations: [], + // DEPRECATED: some legacy reports require this info. + line: loc && loc.start.line + }; + this.meta.last.b += 1; + this.maybeNewBranchTrue(type, b, isReportLogic); + return b; + } + + maybeNewBranchTrue(type, name, isReportLogic) { + if (!isReportLogic) { + return; + } + if (type !== 'binary-expr') { + return; + } + this.data.bT = this.data.bT || {}; + this.data.bT[name] = []; + } + + addBranchPath(name, location) { + const bMeta = this.data.branchMap[name]; + const counts = this.data.b[name]; + + /* istanbul ignore if: paranoid check */ + if (!bMeta) { + throw new Error('Invalid branch ' + name); + } + bMeta.locations.push(cloneLocation(location)); + counts.push(0); + this.maybeAddBranchTrue(name); + return counts.length - 1; + } + + maybeAddBranchTrue(name) { + if (!this.data.bT) { + return; + } + const countsTrue = this.data.bT[name]; + if (!countsTrue) { + return; + } + countsTrue.push(0); + } + + /** + * Assigns an input source map to the coverage that can be used + * to remap the coverage output to the original source + * @param sourceMap {object} the source map + */ + inputSourceMap(sourceMap) { + this.data.inputSourceMap = sourceMap; + } + + freeze() { + // prune empty branches + const map = this.data.branchMap; + const branches = this.data.b; + const branchesT = this.data.bT || {}; + Object.keys(map).forEach(b => { + if (map[b].locations.length === 0) { + delete map[b]; + delete branches[b]; + delete branchesT[b]; + } + }); + } +} + +module.exports = { SourceCoverage }; diff --git a/node_modules/istanbul-lib-instrument/src/visitor.js b/node_modules/istanbul-lib-instrument/src/visitor.js new file mode 100644 index 0000000..46c7129 --- /dev/null +++ b/node_modules/istanbul-lib-instrument/src/visitor.js @@ -0,0 +1,843 @@ +const { createHash } = require('crypto'); +const { template } = require('@babel/core'); +const { defaults } = require('@istanbuljs/schema'); +const { SourceCoverage } = require('./source-coverage'); +const { SHA, MAGIC_KEY, MAGIC_VALUE } = require('./constants'); + +// pattern for istanbul to ignore a section +const COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/; +// pattern for istanbul to ignore the whole file +const COMMENT_FILE_RE = /^\s*istanbul\s+ignore\s+(file)(?=\W|$)/; +// source map URL pattern +const SOURCE_MAP_RE = /[#@]\s*sourceMappingURL=(.*)\s*$/m; + +// generate a variable name from hashing the supplied file path +function genVar(filename) { + const hash = createHash(SHA); + hash.update(filename); + return 'cov_' + parseInt(hash.digest('hex').substr(0, 12), 16).toString(36); +} + +// VisitState holds the state of the visitor, provides helper functions +// and is the `this` for the individual coverage visitors. +class VisitState { + constructor( + types, + sourceFilePath, + inputSourceMap, + ignoreClassMethods = [], + reportLogic = false + ) { + this.varName = genVar(sourceFilePath); + this.attrs = {}; + this.nextIgnore = null; + this.cov = new SourceCoverage(sourceFilePath); + + if (typeof inputSourceMap !== 'undefined') { + this.cov.inputSourceMap(inputSourceMap); + } + this.ignoreClassMethods = ignoreClassMethods; + this.types = types; + this.sourceMappingURL = null; + this.reportLogic = reportLogic; + } + + // should we ignore the node? Yes, if specifically ignoring + // or if the node is generated. + shouldIgnore(path) { + return this.nextIgnore || !path.node.loc; + } + + // extract the ignore comment hint (next|if|else) or null + hintFor(node) { + let hint = null; + if (node.leadingComments) { + node.leadingComments.forEach(c => { + const v = ( + c.value || /* istanbul ignore next: paranoid check */ '' + ).trim(); + const groups = v.match(COMMENT_RE); + if (groups) { + hint = groups[1]; + } + }); + } + return hint; + } + + // extract a source map URL from comments and keep track of it + maybeAssignSourceMapURL(node) { + const extractURL = comments => { + if (!comments) { + return; + } + comments.forEach(c => { + const v = ( + c.value || /* istanbul ignore next: paranoid check */ '' + ).trim(); + const groups = v.match(SOURCE_MAP_RE); + if (groups) { + this.sourceMappingURL = groups[1]; + } + }); + }; + extractURL(node.leadingComments); + extractURL(node.trailingComments); + } + + // for these expressions the statement counter needs to be hoisted, so + // function name inference can be preserved + counterNeedsHoisting(path) { + return ( + path.isFunctionExpression() || + path.isArrowFunctionExpression() || + path.isClassExpression() + ); + } + + // all the generic stuff that needs to be done on enter for every node + onEnter(path) { + const n = path.node; + + this.maybeAssignSourceMapURL(n); + + // if already ignoring, nothing more to do + if (this.nextIgnore !== null) { + return; + } + // check hint to see if ignore should be turned on + const hint = this.hintFor(n); + if (hint === 'next') { + this.nextIgnore = n; + return; + } + // else check custom node attribute set by a prior visitor + if (this.getAttr(path.node, 'skip-all') !== null) { + this.nextIgnore = n; + } + + // else check for ignored class methods + if ( + path.isFunctionExpression() && + this.ignoreClassMethods.some( + name => path.node.id && name === path.node.id.name + ) + ) { + this.nextIgnore = n; + return; + } + if ( + path.isClassMethod() && + this.ignoreClassMethods.some(name => name === path.node.key.name) + ) { + this.nextIgnore = n; + return; + } + } + + // all the generic stuff on exit of a node, + // including reseting ignores and custom node attrs + onExit(path) { + // restore ignore status, if needed + if (path.node === this.nextIgnore) { + this.nextIgnore = null; + } + // nuke all attributes for the node + delete path.node.__cov__; + } + + // set a node attribute for the supplied node + setAttr(node, name, value) { + node.__cov__ = node.__cov__ || {}; + node.__cov__[name] = value; + } + + // retrieve a node attribute for the supplied node or null + getAttr(node, name) { + const c = node.__cov__; + if (!c) { + return null; + } + return c[name]; + } + + // + increase(type, id, index) { + const T = this.types; + const wrap = + index !== null + ? // If `index` present, turn `x` into `x[index]`. + x => T.memberExpression(x, T.numericLiteral(index), true) + : x => x; + return T.updateExpression( + '++', + wrap( + T.memberExpression( + T.memberExpression( + T.callExpression(T.identifier(this.varName), []), + T.identifier(type) + ), + T.numericLiteral(id), + true + ) + ) + ); + } + + // Reads the logic expression conditions and conditionally increments truthy counter. + increaseTrue(type, id, index, node) { + const T = this.types; + const tempName = `${this.varName}_temp`; + + return T.sequenceExpression([ + T.assignmentExpression( + '=', + T.memberExpression( + T.callExpression(T.identifier(this.varName), []), + T.identifier(tempName) + ), + node // Only evaluates once. + ), + T.parenthesizedExpression( + T.conditionalExpression( + this.validateTrueNonTrivial(T, tempName), + this.increase(type, id, index), + T.nullLiteral() + ) + ), + T.memberExpression( + T.callExpression(T.identifier(this.varName), []), + T.identifier(tempName) + ) + ]); + } + + validateTrueNonTrivial(T, tempName) { + return T.logicalExpression( + '&&', + T.memberExpression( + T.callExpression(T.identifier(this.varName), []), + T.identifier(tempName) + ), + T.logicalExpression( + '&&', + T.parenthesizedExpression( + T.logicalExpression( + '||', + T.unaryExpression( + '!', + T.callExpression( + T.memberExpression( + T.identifier('Array'), + T.identifier('isArray') + ), + [ + T.memberExpression( + T.callExpression( + T.identifier(this.varName), + [] + ), + T.identifier(tempName) + ) + ] + ) + ), + T.memberExpression( + T.memberExpression( + T.callExpression( + T.identifier(this.varName), + [] + ), + T.identifier(tempName) + ), + T.identifier('length') + ) + ) + ), + T.parenthesizedExpression( + T.logicalExpression( + '||', + T.binaryExpression( + '!==', + T.callExpression( + T.memberExpression( + T.identifier('Object'), + T.identifier('getPrototypeOf') + ), + [ + T.memberExpression( + T.callExpression( + T.identifier(this.varName), + [] + ), + T.identifier(tempName) + ) + ] + ), + T.memberExpression( + T.identifier('Object'), + T.identifier('prototype') + ) + ), + T.memberExpression( + T.callExpression( + T.memberExpression( + T.identifier('Object'), + T.identifier('values') + ), + [ + T.memberExpression( + T.callExpression( + T.identifier(this.varName), + [] + ), + T.identifier(tempName) + ) + ] + ), + T.identifier('length') + ) + ) + ) + ) + ); + } + + insertCounter(path, increment) { + const T = this.types; + if (path.isBlockStatement()) { + path.node.body.unshift(T.expressionStatement(increment)); + } else if (path.isStatement()) { + path.insertBefore(T.expressionStatement(increment)); + } else if ( + this.counterNeedsHoisting(path) && + T.isVariableDeclarator(path.parentPath) + ) { + // make an attempt to hoist the statement counter, so that + // function names are maintained. + const parent = path.parentPath.parentPath; + if (parent && T.isExportNamedDeclaration(parent.parentPath)) { + parent.parentPath.insertBefore( + T.expressionStatement(increment) + ); + } else if ( + parent && + (T.isProgram(parent.parentPath) || + T.isBlockStatement(parent.parentPath)) + ) { + parent.insertBefore(T.expressionStatement(increment)); + } else { + path.replaceWith(T.sequenceExpression([increment, path.node])); + } + } /* istanbul ignore else: not expected */ else if ( + path.isExpression() + ) { + path.replaceWith(T.sequenceExpression([increment, path.node])); + } else { + console.error( + 'Unable to insert counter for node type:', + path.node.type + ); + } + } + + insertStatementCounter(path) { + /* istanbul ignore if: paranoid check */ + if (!(path.node && path.node.loc)) { + return; + } + const index = this.cov.newStatement(path.node.loc); + const increment = this.increase('s', index, null); + this.insertCounter(path, increment); + } + + insertFunctionCounter(path) { + const T = this.types; + /* istanbul ignore if: paranoid check */ + if (!(path.node && path.node.loc)) { + return; + } + const n = path.node; + + let dloc = null; + // get location for declaration + switch (n.type) { + case 'FunctionDeclaration': + case 'FunctionExpression': + /* istanbul ignore else: paranoid check */ + if (n.id) { + dloc = n.id.loc; + } + break; + } + if (!dloc) { + dloc = { + start: n.loc.start, + end: { line: n.loc.start.line, column: n.loc.start.column + 1 } + }; + } + + const name = path.node.id ? path.node.id.name : path.node.name; + const index = this.cov.newFunction(name, dloc, path.node.body.loc); + const increment = this.increase('f', index, null); + const body = path.get('body'); + /* istanbul ignore else: not expected */ + if (body.isBlockStatement()) { + body.node.body.unshift(T.expressionStatement(increment)); + } else { + console.error( + 'Unable to process function body node type:', + path.node.type + ); + } + } + + getBranchIncrement(branchName, loc) { + const index = this.cov.addBranchPath(branchName, loc); + return this.increase('b', branchName, index); + } + + getBranchLogicIncrement(path, branchName, loc) { + const index = this.cov.addBranchPath(branchName, loc); + return [ + this.increase('b', branchName, index), + this.increaseTrue('bT', branchName, index, path.node) + ]; + } + + insertBranchCounter(path, branchName, loc) { + const increment = this.getBranchIncrement( + branchName, + loc || path.node.loc + ); + this.insertCounter(path, increment); + } + + findLeaves(node, accumulator, parent, property) { + if (!node) { + return; + } + if (node.type === 'LogicalExpression') { + const hint = this.hintFor(node); + if (hint !== 'next') { + this.findLeaves(node.left, accumulator, node, 'left'); + this.findLeaves(node.right, accumulator, node, 'right'); + } + } else { + accumulator.push({ + node, + parent, + property + }); + } + } +} + +// generic function that takes a set of visitor methods and +// returns a visitor object with `enter` and `exit` properties, +// such that: +// +// * standard entry processing is done +// * the supplied visitors are called only when ignore is not in effect +// This relieves them from worrying about ignore states and generated nodes. +// * standard exit processing is done +// +function entries(...enter) { + // the enter function + const wrappedEntry = function(path, node) { + this.onEnter(path); + if (this.shouldIgnore(path)) { + return; + } + enter.forEach(e => { + e.call(this, path, node); + }); + }; + const exit = function(path, node) { + this.onExit(path, node); + }; + return { + enter: wrappedEntry, + exit + }; +} + +function coverStatement(path) { + this.insertStatementCounter(path); +} + +/* istanbul ignore next: no node.js support */ +function coverAssignmentPattern(path) { + const n = path.node; + const b = this.cov.newBranch('default-arg', n.loc); + this.insertBranchCounter(path.get('right'), b); +} + +function coverFunction(path) { + this.insertFunctionCounter(path); +} + +function coverVariableDeclarator(path) { + this.insertStatementCounter(path.get('init')); +} + +function coverClassPropDeclarator(path) { + this.insertStatementCounter(path.get('value')); +} + +function makeBlock(path) { + const T = this.types; + if (!path.node) { + path.replaceWith(T.blockStatement([])); + } + if (!path.isBlockStatement()) { + path.replaceWith(T.blockStatement([path.node])); + path.node.loc = path.node.body[0].loc; + path.node.body[0].leadingComments = path.node.leadingComments; + path.node.leadingComments = undefined; + } +} + +function blockProp(prop) { + return function(path) { + makeBlock.call(this, path.get(prop)); + }; +} + +function makeParenthesizedExpressionForNonIdentifier(path) { + const T = this.types; + if (path.node && !path.isIdentifier()) { + path.replaceWith(T.parenthesizedExpression(path.node)); + } +} + +function parenthesizedExpressionProp(prop) { + return function(path) { + makeParenthesizedExpressionForNonIdentifier.call(this, path.get(prop)); + }; +} + +function convertArrowExpression(path) { + const n = path.node; + const T = this.types; + if (!T.isBlockStatement(n.body)) { + const bloc = n.body.loc; + if (n.expression === true) { + n.expression = false; + } + n.body = T.blockStatement([T.returnStatement(n.body)]); + // restore body location + n.body.loc = bloc; + // set up the location for the return statement so it gets + // instrumented + n.body.body[0].loc = bloc; + } +} + +function coverIfBranches(path) { + const n = path.node; + const hint = this.hintFor(n); + const ignoreIf = hint === 'if'; + const ignoreElse = hint === 'else'; + const branch = this.cov.newBranch('if', n.loc); + + if (ignoreIf) { + this.setAttr(n.consequent, 'skip-all', true); + } else { + this.insertBranchCounter(path.get('consequent'), branch, n.loc); + } + if (ignoreElse) { + this.setAttr(n.alternate, 'skip-all', true); + } else { + this.insertBranchCounter(path.get('alternate'), branch); + } +} + +function createSwitchBranch(path) { + const b = this.cov.newBranch('switch', path.node.loc); + this.setAttr(path.node, 'branchName', b); +} + +function coverSwitchCase(path) { + const T = this.types; + const b = this.getAttr(path.parentPath.node, 'branchName'); + /* istanbul ignore if: paranoid check */ + if (b === null) { + throw new Error('Unable to get switch branch name'); + } + const increment = this.getBranchIncrement(b, path.node.loc); + path.node.consequent.unshift(T.expressionStatement(increment)); +} + +function coverTernary(path) { + const n = path.node; + const branch = this.cov.newBranch('cond-expr', path.node.loc); + const cHint = this.hintFor(n.consequent); + const aHint = this.hintFor(n.alternate); + + if (cHint !== 'next') { + this.insertBranchCounter(path.get('consequent'), branch); + } + if (aHint !== 'next') { + this.insertBranchCounter(path.get('alternate'), branch); + } +} + +function coverLogicalExpression(path) { + const T = this.types; + if (path.parentPath.node.type === 'LogicalExpression') { + return; // already processed + } + const leaves = []; + this.findLeaves(path.node, leaves); + const b = this.cov.newBranch( + 'binary-expr', + path.node.loc, + this.reportLogic + ); + for (let i = 0; i < leaves.length; i += 1) { + const leaf = leaves[i]; + const hint = this.hintFor(leaf.node); + if (hint === 'next') { + continue; + } + + if (this.reportLogic) { + const increment = this.getBranchLogicIncrement( + leaf, + b, + leaf.node.loc + ); + if (!increment[0]) { + continue; + } + leaf.parent[leaf.property] = T.sequenceExpression([ + increment[0], + increment[1] + ]); + continue; + } + + const increment = this.getBranchIncrement(b, leaf.node.loc); + if (!increment) { + continue; + } + leaf.parent[leaf.property] = T.sequenceExpression([ + increment, + leaf.node + ]); + } +} + +const codeVisitor = { + ArrowFunctionExpression: entries(convertArrowExpression, coverFunction), + AssignmentPattern: entries(coverAssignmentPattern), + BlockStatement: entries(), // ignore processing only + ExportDefaultDeclaration: entries(), // ignore processing only + ExportNamedDeclaration: entries(), // ignore processing only + ClassMethod: entries(coverFunction), + ClassDeclaration: entries(parenthesizedExpressionProp('superClass')), + ClassProperty: entries(coverClassPropDeclarator), + ClassPrivateProperty: entries(coverClassPropDeclarator), + ObjectMethod: entries(coverFunction), + ExpressionStatement: entries(coverStatement), + BreakStatement: entries(coverStatement), + ContinueStatement: entries(coverStatement), + DebuggerStatement: entries(coverStatement), + ReturnStatement: entries(coverStatement), + ThrowStatement: entries(coverStatement), + TryStatement: entries(coverStatement), + VariableDeclaration: entries(), // ignore processing only + VariableDeclarator: entries(coverVariableDeclarator), + IfStatement: entries( + blockProp('consequent'), + blockProp('alternate'), + coverStatement, + coverIfBranches + ), + ForStatement: entries(blockProp('body'), coverStatement), + ForInStatement: entries(blockProp('body'), coverStatement), + ForOfStatement: entries(blockProp('body'), coverStatement), + WhileStatement: entries(blockProp('body'), coverStatement), + DoWhileStatement: entries(blockProp('body'), coverStatement), + SwitchStatement: entries(createSwitchBranch, coverStatement), + SwitchCase: entries(coverSwitchCase), + WithStatement: entries(blockProp('body'), coverStatement), + FunctionDeclaration: entries(coverFunction), + FunctionExpression: entries(coverFunction), + LabeledStatement: entries(coverStatement), + ConditionalExpression: entries(coverTernary), + LogicalExpression: entries(coverLogicalExpression) +}; +const globalTemplateAlteredFunction = template(` + var Function = (function(){}).constructor; + var global = (new Function(GLOBAL_COVERAGE_SCOPE))(); +`); +const globalTemplateFunction = template(` + var global = (new Function(GLOBAL_COVERAGE_SCOPE))(); +`); +const globalTemplateVariable = template(` + var global = GLOBAL_COVERAGE_SCOPE; +`); +// the template to insert at the top of the program. +const coverageTemplate = template( + ` + function COVERAGE_FUNCTION () { + var path = PATH; + var hash = HASH; + GLOBAL_COVERAGE_TEMPLATE + var gcv = GLOBAL_COVERAGE_VAR; + var coverageData = INITIAL; + var coverage = global[gcv] || (global[gcv] = {}); + if (!coverage[path] || coverage[path].hash !== hash) { + coverage[path] = coverageData; + } + + var actualCoverage = coverage[path]; + { + // @ts-ignore + COVERAGE_FUNCTION = function () { + return actualCoverage; + } + } + + return actualCoverage; + } +`, + { preserveComments: true } +); +// the rewire plugin (and potentially other babel middleware) +// may cause files to be instrumented twice, see: +// https://github.com/istanbuljs/babel-plugin-istanbul/issues/94 +// we should only instrument code for coverage the first time +// it's run through istanbul-lib-instrument. +function alreadyInstrumented(path, visitState) { + return path.scope.hasBinding(visitState.varName); +} +function shouldIgnoreFile(programNode) { + return ( + programNode.parent && + programNode.parent.comments.some(c => COMMENT_FILE_RE.test(c.value)) + ); +} + +/** + * programVisitor is a `babel` adaptor for instrumentation. + * It returns an object with two methods `enter` and `exit`. + * These should be assigned to or called from `Program` entry and exit functions + * in a babel visitor. + * These functions do not make assumptions about the state set by Babel and thus + * can be used in a context other than a Babel plugin. + * + * The exit function returns an object that currently has the following keys: + * + * `fileCoverage` - the file coverage object created for the source file. + * `sourceMappingURL` - any source mapping URL found when processing the file. + * + * @param {Object} types - an instance of babel-types. + * @param {string} sourceFilePath - the path to source file. + * @param {Object} opts - additional options. + * @param {string} [opts.coverageVariable=__coverage__] the global coverage variable name. + * @param {boolean} [opts.reportLogic=false] report boolean value of logical expressions. + * @param {string} [opts.coverageGlobalScope=this] the global coverage variable scope. + * @param {boolean} [opts.coverageGlobalScopeFunc=true] use an evaluated function to find coverageGlobalScope. + * @param {Array} [opts.ignoreClassMethods=[]] names of methods to ignore by default on classes. + * @param {object} [opts.inputSourceMap=undefined] the input source map, that maps the uninstrumented code back to the + * original code. + */ +function programVisitor(types, sourceFilePath = 'unknown.js', opts = {}) { + const T = types; + opts = { + ...defaults.instrumentVisitor, + ...opts + }; + const visitState = new VisitState( + types, + sourceFilePath, + opts.inputSourceMap, + opts.ignoreClassMethods, + opts.reportLogic + ); + return { + enter(path) { + if (shouldIgnoreFile(path.find(p => p.isProgram()))) { + return; + } + if (alreadyInstrumented(path, visitState)) { + return; + } + path.traverse(codeVisitor, visitState); + }, + exit(path) { + if (alreadyInstrumented(path, visitState)) { + return; + } + visitState.cov.freeze(); + const coverageData = visitState.cov.toJSON(); + if (shouldIgnoreFile(path.find(p => p.isProgram()))) { + return { + fileCoverage: coverageData, + sourceMappingURL: visitState.sourceMappingURL + }; + } + coverageData[MAGIC_KEY] = MAGIC_VALUE; + const hash = createHash(SHA) + .update(JSON.stringify(coverageData)) + .digest('hex'); + coverageData.hash = hash; + if ( + coverageData.inputSourceMap && + Object.getPrototypeOf(coverageData.inputSourceMap) !== + Object.prototype + ) { + coverageData.inputSourceMap = { + ...coverageData.inputSourceMap + }; + } + const coverageNode = T.valueToNode(coverageData); + delete coverageData[MAGIC_KEY]; + delete coverageData.hash; + let gvTemplate; + if (opts.coverageGlobalScopeFunc) { + if (path.scope.getBinding('Function')) { + gvTemplate = globalTemplateAlteredFunction({ + GLOBAL_COVERAGE_SCOPE: T.stringLiteral( + 'return ' + opts.coverageGlobalScope + ) + }); + } else { + gvTemplate = globalTemplateFunction({ + GLOBAL_COVERAGE_SCOPE: T.stringLiteral( + 'return ' + opts.coverageGlobalScope + ) + }); + } + } else { + gvTemplate = globalTemplateVariable({ + GLOBAL_COVERAGE_SCOPE: opts.coverageGlobalScope + }); + } + const cv = coverageTemplate({ + GLOBAL_COVERAGE_VAR: T.stringLiteral(opts.coverageVariable), + GLOBAL_COVERAGE_TEMPLATE: gvTemplate, + COVERAGE_FUNCTION: T.identifier(visitState.varName), + PATH: T.stringLiteral(sourceFilePath), + INITIAL: coverageNode, + HASH: T.stringLiteral(hash) + }); + // explicitly call this.varName to ensure coverage is always initialized + path.node.body.unshift( + T.expressionStatement( + T.callExpression(T.identifier(visitState.varName), []) + ) + ); + path.node.body.unshift(cv); + return { + fileCoverage: coverageData, + sourceMappingURL: visitState.sourceMappingURL + }; + } + }; +} + +module.exports = programVisitor; diff --git a/node_modules/istanbul-lib-report/CHANGELOG.md b/node_modules/istanbul-lib-report/CHANGELOG.md new file mode 100644 index 0000000..36dc3d8 --- /dev/null +++ b/node_modules/istanbul-lib-report/CHANGELOG.md @@ -0,0 +1,192 @@ +# Change Log + +All notable changes to this project will be documented in this file. +See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. + +# [3.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@3.0.0-alpha.2...istanbul-lib-report@3.0.0) (2019-12-20) + +**Note:** Version bump only for package istanbul-lib-report + + + + + +# [3.0.0-alpha.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@3.0.0-alpha.1...istanbul-lib-report@3.0.0-alpha.2) (2019-12-07) + +**Note:** Version bump only for package istanbul-lib-report + + + + + +# [3.0.0-alpha.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@3.0.0-alpha.0...istanbul-lib-report@3.0.0-alpha.1) (2019-10-06) + +**Note:** Version bump only for package istanbul-lib-report + + + + + +# [3.0.0-alpha.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.8...istanbul-lib-report@3.0.0-alpha.0) (2019-06-19) + + +### Bug Fixes + +* **package:** update supports-color to version 7.0.0 ([#420](https://github.com/istanbuljs/istanbuljs/issues/420)) ([631029d](https://github.com/istanbuljs/istanbuljs/commit/631029d)) +* Properly combine directories in nested summarizer ([#380](https://github.com/istanbuljs/istanbuljs/issues/380)) ([50afdbb](https://github.com/istanbuljs/istanbuljs/commit/50afdbb)) + + +### Features + +* Refactor istanbul-lib-report so report can choose summarizer ([#408](https://github.com/istanbuljs/istanbuljs/issues/408)) ([0f328fd](https://github.com/istanbuljs/istanbuljs/commit/0f328fd)) +* Update dependencies, require Node.js 8 ([#401](https://github.com/istanbuljs/istanbuljs/issues/401)) ([bf3a539](https://github.com/istanbuljs/istanbuljs/commit/bf3a539)) + + +### BREAKING CHANGES + +* Existing istanbul-lib-report API's have been changed +* Node.js 8 is now required + + + + + +## [3.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report-v3.0.0...istanbul-lib-report-v3.0.1) (2023-07-25) + + +### Bug Fixes + +* **deps:** update make-dir CVE-2022-25883 ([eab82a9](https://github.com/istanbuljs/istanbuljs/commit/eab82a9aeff140a8fd2981c7f872830c985d479f)) + +## [2.0.8](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.7...istanbul-lib-report@2.0.8) (2019-04-24) + +**Note:** Version bump only for package istanbul-lib-report + + + + + +## [2.0.7](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.6...istanbul-lib-report@2.0.7) (2019-04-09) + +**Note:** Version bump only for package istanbul-lib-report + + + + + +## [2.0.6](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.5...istanbul-lib-report@2.0.6) (2019-04-03) + + +### Bug Fixes + +* Avoid corrupting HTML report's arrow png during copy ([#343](https://github.com/istanbuljs/istanbuljs/issues/343)) ([ce664c7](https://github.com/istanbuljs/istanbuljs/commit/ce664c7)) + + + + + +## [2.0.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.4...istanbul-lib-report@2.0.5) (2019-03-12) + +**Note:** Version bump only for package istanbul-lib-report + + + + + +## [2.0.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.3...istanbul-lib-report@2.0.4) (2019-01-26) + + +### Bug Fixes + +* nested summarizer error with no files ([#230](https://github.com/istanbuljs/istanbuljs/issues/230)) ([07724bf](https://github.com/istanbuljs/istanbuljs/commit/07724bf)) + + + + + + +## [2.0.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.2...istanbul-lib-report@2.0.3) (2018-12-25) + + + + +**Note:** Version bump only for package istanbul-lib-report + + +## [2.0.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.1...istanbul-lib-report@2.0.2) (2018-09-06) + + + + +**Note:** Version bump only for package istanbul-lib-report + + +## [2.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@2.0.0...istanbul-lib-report@2.0.1) (2018-07-07) + + + + +**Note:** Version bump only for package istanbul-lib-report + + +# [2.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@1.1.4...istanbul-lib-report@2.0.0) (2018-06-06) + + +### Bug Fixes + +* use null prototype for map objects ([#177](https://github.com/istanbuljs/istanbuljs/issues/177)) ([9a5a30c](https://github.com/istanbuljs/istanbuljs/commit/9a5a30c)) + + +### BREAKING CHANGES + +* a null prototype is now used in several places rather than the default `{}` assignment. + + + + + +## [1.1.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@1.1.3...istanbul-lib-report@1.1.4) (2018-03-04) + + + + +**Note:** Version bump only for package istanbul-lib-report + + +## [1.1.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@1.1.2...istanbul-lib-report@1.1.3) (2018-02-13) + + + + +**Note:** Version bump only for package istanbul-lib-report + + +## [1.1.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@1.1.1...istanbul-lib-report@1.1.2) (2017-10-21) + + +### Bug Fixes + +* remove call to mkdirp.sync() in constructor so when used for ConsoleWriter ([#104](https://github.com/istanbuljs/istanbuljs/issues/104)) ([58eb79d](https://github.com/istanbuljs/istanbuljs/commit/58eb79d)) + + + + + +## [1.1.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-report@1.1.0...istanbul-lib-report@1.1.1) (2017-05-27) + + + + + +# [1.1.0](https://github.com/istanbuljs/istanbul-lib-report/compare/istanbul-lib-report@1.0.0...istanbul-lib-report@1.1.0) (2017-04-29) + + +### Features + +* once 100% line coverage is achieved, missing branch coverage is now shown in text report ([#45](https://github.com/istanbuljs/istanbuljs/issues/45)) ([8a809f8](https://github.com/istanbuljs/istanbul-lib-report/commit/8a809f8)) + + + + + +# [1.0.0](https://github.com/istanbuljs/istanbul-lib-report/compare/istanbul-lib-report@1.0.0-alpha.3...istanbul-lib-report@1.0.0) (2017-03-27) diff --git a/node_modules/istanbul-lib-report/LICENSE b/node_modules/istanbul-lib-report/LICENSE new file mode 100644 index 0000000..d55d291 --- /dev/null +++ b/node_modules/istanbul-lib-report/LICENSE @@ -0,0 +1,24 @@ +Copyright 2012-2015 Yahoo! Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * 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. + * Neither the name of the Yahoo! Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. 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. diff --git a/node_modules/istanbul-lib-report/README.md b/node_modules/istanbul-lib-report/README.md new file mode 100644 index 0000000..f7ff56a --- /dev/null +++ b/node_modules/istanbul-lib-report/README.md @@ -0,0 +1,43 @@ +# istanbul-lib-report + +[![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-lib-report.svg)](https://greenkeeper.io/) +[![Build Status](https://travis-ci.org/istanbuljs/istanbul-lib-report.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-lib-report) + +Core reporting utilities for istanbul. + +## Example usage + +```js +const libReport = require('istanbul-lib-report'); +const reports = require('istanbul-reports'); + +// coverageMap, for instance, obtained from istanbul-lib-coverage +const coverageMap; + +const configWatermarks = { + statements: [50, 80], + functions: [50, 80], + branches: [50, 80], + lines: [50, 80] +}; + +// create a context for report generation +const context = libReport.createContext({ + dir: 'report/output/dir', + // The summarizer to default to (may be overridden by some reports) + // values can be nested/flat/pkg. Defaults to 'pkg' + defaultSummarizer: 'nested', + watermarks: configWatermarks, + coverageMap, +}) + +// create an instance of the relevant report class, passing the +// report name e.g. json/html/html-spa/text +const report = reports.create('json', { + skipEmpty: configSkipEmpty, + skipFull: configSkipFull +}) + +// call execute to synchronously create and write the report to disk +report.execute(context) +``` diff --git a/node_modules/istanbul-lib-report/index.js b/node_modules/istanbul-lib-report/index.js new file mode 100644 index 0000000..af1a1c8 --- /dev/null +++ b/node_modules/istanbul-lib-report/index.js @@ -0,0 +1,40 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +/** + * @module Exports + */ + +const Context = require('./lib/context'); +const watermarks = require('./lib/watermarks'); +const ReportBase = require('./lib/report-base'); + +module.exports = { + /** + * returns a reporting context for the supplied options + * @param {Object} [opts=null] opts + * @returns {Context} + */ + createContext(opts) { + return new Context(opts); + }, + + /** + * returns the default watermarks that would be used when not + * overridden + * @returns {Object} an object with `statements`, `functions`, `branches`, + * and `line` keys. Each value is a 2 element array that has the low and + * high watermark as percentages. + */ + getDefaultWatermarks() { + return watermarks.getDefault(); + }, + + /** + * Base class for all reports + */ + ReportBase +}; diff --git a/node_modules/istanbul-lib-report/lib/context.js b/node_modules/istanbul-lib-report/lib/context.js new file mode 100644 index 0000000..fbb30bc --- /dev/null +++ b/node_modules/istanbul-lib-report/lib/context.js @@ -0,0 +1,132 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const fs = require('fs'); +const FileWriter = require('./file-writer'); +const XMLWriter = require('./xml-writer'); +const tree = require('./tree'); +const watermarks = require('./watermarks'); +const SummarizerFactory = require('./summarizer-factory'); + +function defaultSourceLookup(path) { + try { + return fs.readFileSync(path, 'utf8'); + } catch (ex) { + throw new Error(`Unable to lookup source: ${path} (${ex.message})`); + } +} + +function normalizeWatermarks(specified = {}) { + Object.entries(watermarks.getDefault()).forEach(([k, value]) => { + const specValue = specified[k]; + if (!Array.isArray(specValue) || specValue.length !== 2) { + specified[k] = value; + } + }); + + return specified; +} + +/** + * A reporting context that is passed to report implementations + * @param {Object} [opts=null] opts options + * @param {String} [opts.dir='coverage'] opts.dir the reporting directory + * @param {Object} [opts.watermarks=null] opts.watermarks watermarks for + * statements, lines, branches and functions + * @param {Function} [opts.sourceFinder=fsLookup] opts.sourceFinder a + * function that returns source code given a file path. Defaults to + * filesystem lookups based on path. + * @constructor + */ +class Context { + constructor(opts) { + this.dir = opts.dir || 'coverage'; + this.watermarks = normalizeWatermarks(opts.watermarks); + this.sourceFinder = opts.sourceFinder || defaultSourceLookup; + this._summarizerFactory = new SummarizerFactory( + opts.coverageMap, + opts.defaultSummarizer + ); + this.data = {}; + } + + /** + * returns a FileWriter implementation for reporting use. Also available + * as the `writer` property on the context. + * @returns {Writer} + */ + getWriter() { + return this.writer; + } + + /** + * returns the source code for the specified file path or throws if + * the source could not be found. + * @param {String} filePath the file path as found in a file coverage object + * @returns {String} the source code + */ + getSource(filePath) { + return this.sourceFinder(filePath); + } + + /** + * returns the coverage class given a coverage + * types and a percentage value. + * @param {String} type - the coverage type, one of `statements`, `functions`, + * `branches`, or `lines` + * @param {Number} value - the percentage value + * @returns {String} one of `high`, `medium` or `low` + */ + classForPercent(type, value) { + const watermarks = this.watermarks[type]; + if (!watermarks) { + return 'unknown'; + } + if (value < watermarks[0]) { + return 'low'; + } + if (value >= watermarks[1]) { + return 'high'; + } + return 'medium'; + } + + /** + * returns an XML writer for the supplied content writer + * @param {ContentWriter} contentWriter the content writer to which the returned XML writer + * writes data + * @returns {XMLWriter} + */ + getXMLWriter(contentWriter) { + return new XMLWriter(contentWriter); + } + + /** + * returns a full visitor given a partial one. + * @param {Object} partialVisitor a partial visitor only having the functions of + * interest to the caller. These functions are called with a scope that is the + * supplied object. + * @returns {Visitor} + */ + getVisitor(partialVisitor) { + return new tree.Visitor(partialVisitor); + } + + getTree(name = 'defaultSummarizer') { + return this._summarizerFactory[name]; + } +} + +Object.defineProperty(Context.prototype, 'writer', { + enumerable: true, + get() { + if (!this.data.writer) { + this.data.writer = new FileWriter(this.dir); + } + return this.data.writer; + } +}); + +module.exports = Context; diff --git a/node_modules/istanbul-lib-report/lib/file-writer.js b/node_modules/istanbul-lib-report/lib/file-writer.js new file mode 100644 index 0000000..de1154b --- /dev/null +++ b/node_modules/istanbul-lib-report/lib/file-writer.js @@ -0,0 +1,189 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const path = require('path'); +const fs = require('fs'); +const mkdirp = require('make-dir'); +const supportsColor = require('supports-color'); + +/** + * Base class for writing content + * @class ContentWriter + * @constructor + */ +class ContentWriter { + /** + * returns the colorized version of a string. Typically, + * content writers that write to files will return the + * same string and ones writing to a tty will wrap it in + * appropriate escape sequences. + * @param {String} str the string to colorize + * @param {String} clazz one of `high`, `medium` or `low` + * @returns {String} the colorized form of the string + */ + colorize(str /*, clazz*/) { + return str; + } + + /** + * writes a string appended with a newline to the destination + * @param {String} str the string to write + */ + println(str) { + this.write(`${str}\n`); + } + + /** + * closes this content writer. Should be called after all writes are complete. + */ + close() {} +} + +/** + * a content writer that writes to a file + * @param {Number} fd - the file descriptor + * @extends ContentWriter + * @constructor + */ +class FileContentWriter extends ContentWriter { + constructor(fd) { + super(); + + this.fd = fd; + } + + write(str) { + fs.writeSync(this.fd, str); + } + + close() { + fs.closeSync(this.fd); + } +} + +// allow stdout to be captured for tests. +let capture = false; +let output = ''; + +/** + * a content writer that writes to the console + * @extends ContentWriter + * @constructor + */ +class ConsoleWriter extends ContentWriter { + write(str) { + if (capture) { + output += str; + } else { + process.stdout.write(str); + } + } + + colorize(str, clazz) { + const colors = { + low: '31;1', + medium: '33;1', + high: '32;1' + }; + + /* istanbul ignore next: different modes for CI and local */ + if (supportsColor.stdout && colors[clazz]) { + return `\u001b[${colors[clazz]}m${str}\u001b[0m`; + } + return str; + } +} + +/** + * utility for writing files under a specific directory + * @class FileWriter + * @param {String} baseDir the base directory under which files should be written + * @constructor + */ +class FileWriter { + constructor(baseDir) { + if (!baseDir) { + throw new Error('baseDir must be specified'); + } + this.baseDir = baseDir; + } + + /** + * static helpers for capturing stdout report output; + * super useful for tests! + */ + static startCapture() { + capture = true; + } + + static stopCapture() { + capture = false; + } + + static getOutput() { + return output; + } + + static resetOutput() { + output = ''; + } + + /** + * returns a FileWriter that is rooted at the supplied subdirectory + * @param {String} subdir the subdirectory under which to root the + * returned FileWriter + * @returns {FileWriter} + */ + writerForDir(subdir) { + if (path.isAbsolute(subdir)) { + throw new Error( + `Cannot create subdir writer for absolute path: ${subdir}` + ); + } + return new FileWriter(`${this.baseDir}/${subdir}`); + } + + /** + * copies a file from a source directory to a destination name + * @param {String} source path to source file + * @param {String} dest relative path to destination file + * @param {String} [header=undefined] optional text to prepend to destination + * (e.g., an "this file is autogenerated" comment, copyright notice, etc.) + */ + copyFile(source, dest, header) { + if (path.isAbsolute(dest)) { + throw new Error(`Cannot write to absolute path: ${dest}`); + } + dest = path.resolve(this.baseDir, dest); + mkdirp.sync(path.dirname(dest)); + let contents; + if (header) { + contents = header + fs.readFileSync(source, 'utf8'); + } else { + contents = fs.readFileSync(source); + } + fs.writeFileSync(dest, contents); + } + + /** + * returns a content writer for writing content to the supplied file. + * @param {String|null} file the relative path to the file or the special + * values `"-"` or `null` for writing to the console + * @returns {ContentWriter} + */ + writeFile(file) { + if (file === null || file === '-') { + return new ConsoleWriter(); + } + if (path.isAbsolute(file)) { + throw new Error(`Cannot write to absolute path: ${file}`); + } + file = path.resolve(this.baseDir, file); + mkdirp.sync(path.dirname(file)); + return new FileContentWriter(fs.openSync(file, 'w')); + } +} + +module.exports = FileWriter; diff --git a/node_modules/istanbul-lib-report/lib/path.js b/node_modules/istanbul-lib-report/lib/path.js new file mode 100644 index 0000000..c928b17 --- /dev/null +++ b/node_modules/istanbul-lib-report/lib/path.js @@ -0,0 +1,169 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const path = require('path'); +let parsePath = path.parse; +let SEP = path.sep; +const origParser = parsePath; +const origSep = SEP; + +function makeRelativeNormalizedPath(str, sep) { + const parsed = parsePath(str); + let root = parsed.root; + let dir; + let file = parsed.base; + let quoted; + let pos; + + // handle a weird windows case separately + if (sep === '\\') { + pos = root.indexOf(':\\'); + if (pos >= 0) { + root = root.substring(0, pos + 2); + } + } + dir = parsed.dir.substring(root.length); + + if (str === '') { + return []; + } + + if (sep !== '/') { + quoted = new RegExp(sep.replace(/\W/g, '\\$&'), 'g'); + dir = dir.replace(quoted, '/'); + file = file.replace(quoted, '/'); // excessively paranoid? + } + + if (dir !== '') { + dir = `${dir}/${file}`; + } else { + dir = file; + } + if (dir.substring(0, 1) === '/') { + dir = dir.substring(1); + } + dir = dir.split(/\/+/); + return dir; +} + +class Path { + constructor(strOrArray) { + if (Array.isArray(strOrArray)) { + this.v = strOrArray; + } else if (typeof strOrArray === 'string') { + this.v = makeRelativeNormalizedPath(strOrArray, SEP); + } else { + throw new Error( + `Invalid Path argument must be string or array:${strOrArray}` + ); + } + } + + toString() { + return this.v.join('/'); + } + + hasParent() { + return this.v.length > 0; + } + + parent() { + if (!this.hasParent()) { + throw new Error('Unable to get parent for 0 elem path'); + } + const p = this.v.slice(); + p.pop(); + return new Path(p); + } + + elements() { + return this.v.slice(); + } + + name() { + return this.v.slice(-1)[0]; + } + + contains(other) { + let i; + if (other.length > this.length) { + return false; + } + for (i = 0; i < other.length; i += 1) { + if (this.v[i] !== other.v[i]) { + return false; + } + } + return true; + } + + ancestorOf(other) { + return other.contains(this) && other.length !== this.length; + } + + descendantOf(other) { + return this.contains(other) && other.length !== this.length; + } + + commonPrefixPath(other) { + const len = this.length > other.length ? other.length : this.length; + let i; + const ret = []; + + for (i = 0; i < len; i += 1) { + if (this.v[i] === other.v[i]) { + ret.push(this.v[i]); + } else { + break; + } + } + return new Path(ret); + } + + static compare(a, b) { + const al = a.length; + const bl = b.length; + + if (al < bl) { + return -1; + } + + if (al > bl) { + return 1; + } + + const astr = a.toString(); + const bstr = b.toString(); + return astr < bstr ? -1 : astr > bstr ? 1 : 0; + } +} + +['push', 'pop', 'shift', 'unshift', 'splice'].forEach(fn => { + Object.defineProperty(Path.prototype, fn, { + value(...args) { + return this.v[fn](...args); + } + }); +}); + +Object.defineProperty(Path.prototype, 'length', { + enumerable: true, + get() { + return this.v.length; + } +}); + +module.exports = Path; +Path.tester = { + setParserAndSep(p, sep) { + parsePath = p; + SEP = sep; + }, + reset() { + parsePath = origParser; + SEP = origSep; + } +}; diff --git a/node_modules/istanbul-lib-report/lib/report-base.js b/node_modules/istanbul-lib-report/lib/report-base.js new file mode 100644 index 0000000..96de750 --- /dev/null +++ b/node_modules/istanbul-lib-report/lib/report-base.js @@ -0,0 +1,16 @@ +'use strict'; + +// TODO: switch to class private field when targetting node.js 12 +const _summarizer = Symbol('ReportBase.#summarizer'); + +class ReportBase { + constructor(opts = {}) { + this[_summarizer] = opts.summarizer; + } + + execute(context) { + context.getTree(this[_summarizer]).visit(this, context); + } +} + +module.exports = ReportBase; diff --git a/node_modules/istanbul-lib-report/lib/summarizer-factory.js b/node_modules/istanbul-lib-report/lib/summarizer-factory.js new file mode 100644 index 0000000..5e8acd9 --- /dev/null +++ b/node_modules/istanbul-lib-report/lib/summarizer-factory.js @@ -0,0 +1,284 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const coverage = require('istanbul-lib-coverage'); +const Path = require('./path'); +const { BaseNode, BaseTree } = require('./tree'); + +class ReportNode extends BaseNode { + constructor(path, fileCoverage) { + super(); + + this.path = path; + this.parent = null; + this.fileCoverage = fileCoverage; + this.children = []; + } + + static createRoot(children) { + const root = new ReportNode(new Path([])); + + children.forEach(child => { + root.addChild(child); + }); + + return root; + } + + addChild(child) { + child.parent = this; + this.children.push(child); + } + + asRelative(p) { + if (p.substring(0, 1) === '/') { + return p.substring(1); + } + return p; + } + + getQualifiedName() { + return this.asRelative(this.path.toString()); + } + + getRelativeName() { + const parent = this.getParent(); + const myPath = this.path; + let relPath; + let i; + const parentPath = parent ? parent.path : new Path([]); + if (parentPath.ancestorOf(myPath)) { + relPath = new Path(myPath.elements()); + for (i = 0; i < parentPath.length; i += 1) { + relPath.shift(); + } + return this.asRelative(relPath.toString()); + } + return this.asRelative(this.path.toString()); + } + + getParent() { + return this.parent; + } + + getChildren() { + return this.children; + } + + isSummary() { + return !this.fileCoverage; + } + + getFileCoverage() { + return this.fileCoverage; + } + + getCoverageSummary(filesOnly) { + const cacheProp = `c_${filesOnly ? 'files' : 'full'}`; + let summary; + + if (Object.prototype.hasOwnProperty.call(this, cacheProp)) { + return this[cacheProp]; + } + + if (!this.isSummary()) { + summary = this.getFileCoverage().toSummary(); + } else { + let count = 0; + summary = coverage.createCoverageSummary(); + this.getChildren().forEach(child => { + if (filesOnly && child.isSummary()) { + return; + } + count += 1; + summary.merge(child.getCoverageSummary(filesOnly)); + }); + if (count === 0 && filesOnly) { + summary = null; + } + } + this[cacheProp] = summary; + return summary; + } +} + +class ReportTree extends BaseTree { + constructor(root, childPrefix) { + super(root); + + const maybePrefix = node => { + if (childPrefix && !node.isRoot()) { + node.path.unshift(childPrefix); + } + }; + this.visit({ + onDetail: maybePrefix, + onSummary(node) { + maybePrefix(node); + node.children.sort((a, b) => { + const astr = a.path.toString(); + const bstr = b.path.toString(); + return astr < bstr + ? -1 + : astr > bstr + ? 1 + : /* istanbul ignore next */ 0; + }); + } + }); + } +} + +function findCommonParent(paths) { + return paths.reduce( + (common, path) => common.commonPrefixPath(path), + paths[0] || new Path([]) + ); +} + +function findOrCreateParent(parentPath, nodeMap, created = () => {}) { + let parent = nodeMap[parentPath.toString()]; + + if (!parent) { + parent = new ReportNode(parentPath); + nodeMap[parentPath.toString()] = parent; + created(parentPath, parent); + } + + return parent; +} + +function toDirParents(list) { + const nodeMap = Object.create(null); + list.forEach(o => { + const parent = findOrCreateParent(o.path.parent(), nodeMap); + parent.addChild(new ReportNode(o.path, o.fileCoverage)); + }); + + return Object.values(nodeMap); +} + +function addAllPaths(topPaths, nodeMap, path, node) { + const parent = findOrCreateParent( + path.parent(), + nodeMap, + (parentPath, parent) => { + if (parentPath.hasParent()) { + addAllPaths(topPaths, nodeMap, parentPath, parent); + } else { + topPaths.push(parent); + } + } + ); + + parent.addChild(node); +} + +function foldIntoOneDir(node, parent) { + const { children } = node; + if (children.length === 1 && !children[0].fileCoverage) { + children[0].parent = parent; + return foldIntoOneDir(children[0], parent); + } + node.children = children.map(child => foldIntoOneDir(child, node)); + return node; +} + +function pkgSummaryPrefix(dirParents, commonParent) { + if (!dirParents.some(dp => dp.path.length === 0)) { + return; + } + + if (commonParent.length === 0) { + return 'root'; + } + + return commonParent.name(); +} + +class SummarizerFactory { + constructor(coverageMap, defaultSummarizer = 'pkg') { + this._coverageMap = coverageMap; + this._defaultSummarizer = defaultSummarizer; + this._initialList = coverageMap.files().map(filePath => ({ + filePath, + path: new Path(filePath), + fileCoverage: coverageMap.fileCoverageFor(filePath) + })); + this._commonParent = findCommonParent( + this._initialList.map(o => o.path.parent()) + ); + if (this._commonParent.length > 0) { + this._initialList.forEach(o => { + o.path.splice(0, this._commonParent.length); + }); + } + } + + get defaultSummarizer() { + return this[this._defaultSummarizer]; + } + + get flat() { + if (!this._flat) { + this._flat = new ReportTree( + ReportNode.createRoot( + this._initialList.map( + node => new ReportNode(node.path, node.fileCoverage) + ) + ) + ); + } + + return this._flat; + } + + _createPkg() { + const dirParents = toDirParents(this._initialList); + if (dirParents.length === 1) { + return new ReportTree(dirParents[0]); + } + + return new ReportTree( + ReportNode.createRoot(dirParents), + pkgSummaryPrefix(dirParents, this._commonParent) + ); + } + + get pkg() { + if (!this._pkg) { + this._pkg = this._createPkg(); + } + + return this._pkg; + } + + _createNested() { + const nodeMap = Object.create(null); + const topPaths = []; + this._initialList.forEach(o => { + const node = new ReportNode(o.path, o.fileCoverage); + addAllPaths(topPaths, nodeMap, o.path, node); + }); + + const topNodes = topPaths.map(node => foldIntoOneDir(node)); + if (topNodes.length === 1) { + return new ReportTree(topNodes[0]); + } + + return new ReportTree(ReportNode.createRoot(topNodes)); + } + + get nested() { + if (!this._nested) { + this._nested = this._createNested(); + } + + return this._nested; + } +} + +module.exports = SummarizerFactory; diff --git a/node_modules/istanbul-lib-report/lib/tree.js b/node_modules/istanbul-lib-report/lib/tree.js new file mode 100644 index 0000000..7c18204 --- /dev/null +++ b/node_modules/istanbul-lib-report/lib/tree.js @@ -0,0 +1,137 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +/** + * An object with methods that are called during the traversal of the coverage tree. + * A visitor has the following methods that are called during tree traversal. + * + * * `onStart(root, state)` - called before traversal begins + * * `onSummary(node, state)` - called for every summary node + * * `onDetail(node, state)` - called for every detail node + * * `onSummaryEnd(node, state)` - called after all children have been visited for + * a summary node. + * * `onEnd(root, state)` - called after traversal ends + * + * @param delegate - a partial visitor that only implements the methods of interest + * The visitor object supplies the missing methods as noops. For example, reports + * that only need the final coverage summary need implement `onStart` and nothing + * else. Reports that use only detailed coverage information need implement `onDetail` + * and nothing else. + * @constructor + */ +class Visitor { + constructor(delegate) { + this.delegate = delegate; + } +} + +['Start', 'End', 'Summary', 'SummaryEnd', 'Detail'] + .map(k => `on${k}`) + .forEach(fn => { + Object.defineProperty(Visitor.prototype, fn, { + writable: true, + value(node, state) { + if (typeof this.delegate[fn] === 'function') { + this.delegate[fn](node, state); + } + } + }); + }); + +class CompositeVisitor extends Visitor { + constructor(visitors) { + super(); + + if (!Array.isArray(visitors)) { + visitors = [visitors]; + } + this.visitors = visitors.map(v => { + if (v instanceof Visitor) { + return v; + } + return new Visitor(v); + }); + } +} + +['Start', 'Summary', 'SummaryEnd', 'Detail', 'End'] + .map(k => `on${k}`) + .forEach(fn => { + Object.defineProperty(CompositeVisitor.prototype, fn, { + value(node, state) { + this.visitors.forEach(v => { + v[fn](node, state); + }); + } + }); + }); + +class BaseNode { + isRoot() { + return !this.getParent(); + } + + /** + * visit all nodes depth-first from this node down. Note that `onStart` + * and `onEnd` are never called on the visitor even if the current + * node is the root of the tree. + * @param visitor a full visitor that is called during tree traversal + * @param state optional state that is passed around + */ + visit(visitor, state) { + if (this.isSummary()) { + visitor.onSummary(this, state); + } else { + visitor.onDetail(this, state); + } + + this.getChildren().forEach(child => { + child.visit(visitor, state); + }); + + if (this.isSummary()) { + visitor.onSummaryEnd(this, state); + } + } +} + +/** + * abstract base class for a coverage tree. + * @constructor + */ +class BaseTree { + constructor(root) { + this.root = root; + } + + /** + * returns the root node of the tree + */ + getRoot() { + return this.root; + } + + /** + * visits the tree depth-first with the supplied partial visitor + * @param visitor - a potentially partial visitor + * @param state - the state to be passed around during tree traversal + */ + visit(visitor, state) { + if (!(visitor instanceof Visitor)) { + visitor = new Visitor(visitor); + } + visitor.onStart(this.getRoot(), state); + this.getRoot().visit(visitor, state); + visitor.onEnd(this.getRoot(), state); + } +} + +module.exports = { + BaseTree, + BaseNode, + Visitor, + CompositeVisitor +}; diff --git a/node_modules/istanbul-lib-report/lib/watermarks.js b/node_modules/istanbul-lib-report/lib/watermarks.js new file mode 100644 index 0000000..fb76082 --- /dev/null +++ b/node_modules/istanbul-lib-report/lib/watermarks.js @@ -0,0 +1,15 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +module.exports = { + getDefault() { + return { + statements: [50, 80], + functions: [50, 80], + branches: [50, 80], + lines: [50, 80] + }; + } +}; diff --git a/node_modules/istanbul-lib-report/lib/xml-writer.js b/node_modules/istanbul-lib-report/lib/xml-writer.js new file mode 100644 index 0000000..a32550e --- /dev/null +++ b/node_modules/istanbul-lib-report/lib/xml-writer.js @@ -0,0 +1,90 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const INDENT = ' '; + +function attrString(attrs) { + return Object.entries(attrs || {}) + .map(([k, v]) => ` ${k}="${v}"`) + .join(''); +} + +/** + * a utility class to produce well-formed, indented XML + * @param {ContentWriter} contentWriter the content writer that this utility wraps + * @constructor + */ +class XMLWriter { + constructor(contentWriter) { + this.cw = contentWriter; + this.stack = []; + } + + indent(str) { + return this.stack.map(() => INDENT).join('') + str; + } + + /** + * writes the opening XML tag with the supplied attributes + * @param {String} name tag name + * @param {Object} [attrs=null] attrs attributes for the tag + */ + openTag(name, attrs) { + const str = this.indent(`<${name + attrString(attrs)}>`); + this.cw.println(str); + this.stack.push(name); + } + + /** + * closes an open XML tag. + * @param {String} name - tag name to close. This must match the writer's + * notion of the tag that is currently open. + */ + closeTag(name) { + if (this.stack.length === 0) { + throw new Error(`Attempt to close tag ${name} when not opened`); + } + const stashed = this.stack.pop(); + const str = ``; + + if (stashed !== name) { + throw new Error( + `Attempt to close tag ${name} when ${stashed} was the one open` + ); + } + this.cw.println(this.indent(str)); + } + + /** + * writes a tag and its value opening and closing it at the same time + * @param {String} name tag name + * @param {Object} [attrs=null] attrs tag attributes + * @param {String} [content=null] content optional tag content + */ + inlineTag(name, attrs, content) { + let str = '<' + name + attrString(attrs); + if (content) { + str += `>${content}`; + } else { + str += '/>'; + } + str = this.indent(str); + this.cw.println(str); + } + + /** + * closes all open tags and ends the document + */ + closeAll() { + this.stack + .slice() + .reverse() + .forEach(name => { + this.closeTag(name); + }); + } +} + +module.exports = XMLWriter; diff --git a/node_modules/istanbul-lib-report/package.json b/node_modules/istanbul-lib-report/package.json new file mode 100644 index 0000000..f96713d --- /dev/null +++ b/node_modules/istanbul-lib-report/package.json @@ -0,0 +1,44 @@ +{ + "name": "istanbul-lib-report", + "version": "3.0.1", + "description": "Base reporting library for istanbul", + "author": "Krishnan Anantheswaran ", + "main": "index.js", + "files": [ + "lib", + "index.js" + ], + "scripts": { + "test": "nyc mocha" + }, + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "devDependencies": { + "chai": "^4.2.0", + "mocha": "^6.2.2", + "nyc": "^15.0.0-beta.2", + "rimraf": "^3.0.0" + }, + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/istanbuljs/istanbuljs/issues" + }, + "homepage": "https://istanbul.js.org/", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/istanbuljs/istanbuljs.git", + "directory": "packages/istanbul-lib-report" + }, + "keywords": [ + "istanbul", + "report", + "api", + "lib" + ], + "engines": { + "node": ">=10" + } +} diff --git a/node_modules/istanbul-lib-source-maps/CHANGELOG.md b/node_modules/istanbul-lib-source-maps/CHANGELOG.md new file mode 100644 index 0000000..a1c55c2 --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/CHANGELOG.md @@ -0,0 +1,295 @@ +# Change Log + +All notable changes to this project will be documented in this file. +See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. + +# [4.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@4.0.0-alpha.5...istanbul-lib-source-maps@4.0.0) (2019-12-20) + +**Note:** Version bump only for package istanbul-lib-source-maps + + + + + +# [4.0.0-alpha.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@4.0.0-alpha.4...istanbul-lib-source-maps@4.0.0-alpha.5) (2019-12-07) + +**Note:** Version bump only for package istanbul-lib-source-maps + + + + + +# [4.0.0-alpha.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@4.0.0-alpha.3...istanbul-lib-source-maps@4.0.0-alpha.4) (2019-11-16) + + +### Bug Fixes + +* sourceFinder cannot be async. ([#501](https://github.com/istanbuljs/istanbuljs/issues/501)) ([094f1b8](https://github.com/istanbuljs/istanbuljs/commit/094f1b83b4652c5ba492781620cb6358c685a849)) + + + + + +# [4.0.0-alpha.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@4.0.0-alpha.2...istanbul-lib-source-maps@4.0.0-alpha.3) (2019-11-15) + + +### Bug Fixes + +* mappedCoverage.addStatement is not a function ([#500](https://github.com/istanbuljs/istanbuljs/issues/500)) ([d77cc14](https://github.com/istanbuljs/istanbuljs/commit/d77cc147f7d791686af2975f7d906603335d0bfc)), closes [istanbuljs/nyc#940](https://github.com/istanbuljs/nyc/issues/940) + + + + + +# [4.0.0-alpha.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@4.0.0-alpha.1...istanbul-lib-source-maps@4.0.0-alpha.2) (2019-10-09) + + +### Features + +* Convert to async API ([#489](https://github.com/istanbuljs/istanbuljs/issues/489)) ([f8ebbc9](https://github.com/istanbuljs/istanbuljs/commit/f8ebbc9)) + + +### BREAKING CHANGES + +* MapStore#transformCoverage is now async and returns a +the coverage data only. The `sourceFinder` method is now async and +provided directly on the `MapStore` instance. + + + + + +# [4.0.0-alpha.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@4.0.0-alpha.0...istanbul-lib-source-maps@4.0.0-alpha.1) (2019-10-06) + + +### Bug Fixes + +* **package:** update rimraf to version 3.0.0 ([b6e7953](https://github.com/istanbuljs/istanbuljs/commit/b6e7953)) + + +### Features + +* Accept SourceStore and sourceStoreOpts options ([#482](https://github.com/istanbuljs/istanbuljs/issues/482)) ([0dc45a6](https://github.com/istanbuljs/istanbuljs/commit/0dc45a6)) +* Add addInputSourceMapsSync and getSourceMapSync methods ([#484](https://github.com/istanbuljs/istanbuljs/issues/484)) ([dd7048e](https://github.com/istanbuljs/istanbuljs/commit/dd7048e)) + + +### BREAKING CHANGES + +* sourceStore and tmpdir options are removed. + + + + + +# [4.0.0-alpha.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@3.0.6...istanbul-lib-source-maps@4.0.0-alpha.0) (2019-06-19) + + +### Features + +* Update dependencies, require Node.js 8 ([#401](https://github.com/istanbuljs/istanbuljs/issues/401)) ([bf3a539](https://github.com/istanbuljs/istanbuljs/commit/bf3a539)) + + +### BREAKING CHANGES + +* Node.js 8 is now required + + + + + +### [4.0.1](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps-v4.0.0...istanbul-lib-source-maps-v4.0.1) (2021-10-12) + + +### Bug Fixes + +* source mapping for branch statements ([#518](https://www.github.com/istanbuljs/istanbuljs/issues/518)) ([3833708](https://www.github.com/istanbuljs/istanbuljs/commit/38337081d97baa6295707d569dee9c4abc3f7da7)) + +## [3.0.6](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@3.0.5...istanbul-lib-source-maps@3.0.6) (2019-04-24) + + +### Bug Fixes + +* if LEAST_UPPER_BOUND returns null, try GREATEST_LOWER_BOUND ([#375](https://github.com/istanbuljs/istanbuljs/issues/375)) ([72b0f05](https://github.com/istanbuljs/istanbuljs/commit/72b0f05)) + + + + + +## [3.0.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@3.0.4...istanbul-lib-source-maps@3.0.5) (2019-04-09) + +**Note:** Version bump only for package istanbul-lib-source-maps + + + + + +## [3.0.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@3.0.3...istanbul-lib-source-maps@3.0.4) (2019-04-03) + +**Note:** Version bump only for package istanbul-lib-source-maps + + + + + +## [3.0.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@3.0.2...istanbul-lib-source-maps@3.0.3) (2019-03-12) + + +### Bug Fixes + +* Map unique files once, regardless of path separator ([#287](https://github.com/istanbuljs/istanbuljs/issues/287)) ([39a1e56](https://github.com/istanbuljs/istanbuljs/commit/39a1e56)) + + + + + +## [3.0.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@3.0.1...istanbul-lib-source-maps@3.0.2) (2019-01-26) + +**Note:** Version bump only for package istanbul-lib-source-maps + + + + + + +## [3.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@3.0.0...istanbul-lib-source-maps@3.0.1) (2018-12-25) + + +### Bug Fixes + +* correct variable name in source-map transform ([#257](https://github.com/istanbuljs/istanbuljs/issues/257)) ([de9c921](https://github.com/istanbuljs/istanbuljs/commit/de9c921)) + + + + + +# [3.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@2.0.1...istanbul-lib-source-maps@3.0.0) (2018-12-19) + + +### Bug Fixes + +* correctly calculate end position of sourcemap statement ([f97ffc7](https://github.com/istanbuljs/istanbuljs/commit/f97ffc7)) + + +### BREAKING CHANGES + +* coverage output can now contain Infinity, when a range extends past the source in a file. + + + + + +## [2.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@2.0.0...istanbul-lib-source-maps@2.0.1) (2018-07-07) + + + + +**Note:** Version bump only for package istanbul-lib-source-maps + + +# [2.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@1.2.5...istanbul-lib-source-maps@2.0.0) (2018-06-06) + + +### Bug Fixes + +* use null prototype for map objects ([#177](https://github.com/istanbuljs/istanbuljs/issues/177)) ([9a5a30c](https://github.com/istanbuljs/istanbuljs/commit/9a5a30c)) + + +### BREAKING CHANGES + +* a null prototype is now used in several places rather than the default `{}` assignment. + + + + + +## [1.2.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@1.2.4...istanbul-lib-source-maps@1.2.5) (2018-05-31) + + +### Bug Fixes + +* process.cwd is a function not a string ([#163](https://github.com/istanbuljs/istanbuljs/issues/163)). ([#171](https://github.com/istanbuljs/istanbuljs/issues/171)) ([9c7802c](https://github.com/istanbuljs/istanbuljs/commit/9c7802c)) + + + + + +## [1.2.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@1.2.3...istanbul-lib-source-maps@1.2.4) (2018-03-04) + + + + +**Note:** Version bump only for package istanbul-lib-source-maps + + +## [1.2.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@1.2.2...istanbul-lib-source-maps@1.2.3) (2018-02-13) + + + + +**Note:** Version bump only for package istanbul-lib-source-maps + + +## [1.2.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@1.2.1...istanbul-lib-source-maps@1.2.2) (2017-10-21) + + + + +**Note:** Version bump only for package istanbul-lib-source-maps + + +## [1.2.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-source-maps@1.2.0...istanbul-lib-source-maps@1.2.1) (2017-05-27) + + + + + +# [1.2.0](https://github.com/istanbuljs/istanbul-lib-source-maps/compare/istanbul-lib-source-maps@1.1.1...istanbul-lib-source-maps@1.2.0) (2017-04-29) + + +### Features + +* pull in debug module, to make debug messages optional ([#36](https://github.com/istanbuljs/istanbuljs/issues/36)) ([189519d](https://github.com/istanbuljs/istanbul-lib-source-maps/commit/189519d)) + + + + + +## [1.1.1](https://github.com/istanbuljs/istanbul-lib-source-maps/compare/istanbul-lib-source-maps@1.1.0...istanbul-lib-source-maps@1.1.1) (2017-03-27) + + +# [1.1.0](https://github.com/istanbuljs/istanbul-lib-source-maps/compare/v1.0.2...v1.1.0) (2016-11-10) + + +### Features + +* read and apply any input source maps stored with coverage data ([#4](https://github.com/istanbuljs/istanbul-lib-source-maps/issues/4)) ([aea405b](https://github.com/istanbuljs/istanbul-lib-source-maps/commit/aea405b)) + + + + +## [1.0.2](https://github.com/istanbuljs/istanbul-lib-source-maps/compare/v1.0.1...v1.0.2) (2016-10-03) + + +### Bug Fixes + +* broken mapped coverage report ([#6](https://github.com/istanbuljs/istanbul-lib-source-maps/issues/6)) ([d9dd738](https://github.com/istanbuljs/istanbul-lib-source-maps/commit/d9dd738)) + + + + +## [1.0.1](https://github.com/istanbuljs/istanbul-lib-source-maps/compare/v1.0.0...v1.0.1) (2016-09-13) + + +### Bug Fixes + +* position validation shouldn't throw away locations with 0 ([#5](https://github.com/istanbuljs/istanbul-lib-source-maps/issues/5)) ([ac4b72c](https://github.com/istanbuljs/istanbul-lib-source-maps/commit/ac4b72c)) + + + + +# [1.0.0](https://github.com/istanbuljs/istanbul-lib-source-maps/compare/v1.0.0-alpha.9...v1.0.0) (2016-08-31) + + +### Bug Fixes + +* discard more bad source map positions ([#3](https://github.com/istanbuljs/istanbul-lib-source-maps/issues/3)) ([ed7b27f](https://github.com/istanbuljs/istanbul-lib-source-maps/commit/ed7b27f)) diff --git a/node_modules/istanbul-lib-source-maps/LICENSE b/node_modules/istanbul-lib-source-maps/LICENSE new file mode 100644 index 0000000..c05aaaf --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/LICENSE @@ -0,0 +1,24 @@ +Copyright 2015 Yahoo! Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * 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. + * Neither the name of the Yahoo! Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. 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. diff --git a/node_modules/istanbul-lib-source-maps/README.md b/node_modules/istanbul-lib-source-maps/README.md new file mode 100644 index 0000000..f9a75f8 --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/README.md @@ -0,0 +1,11 @@ +# istanbul-lib-source-maps + +[![Build Status](https://travis-ci.org/istanbuljs/istanbuljs.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbuljs) + +Source map support for istanbuljs. + +## Debugging + +_istanbul-lib-source-maps_ uses the [debug](https://www.npmjs.com/package/debug) module. +Run your application with the environment variable `DEBUG=istanbuljs`, to receive debug +output. diff --git a/node_modules/istanbul-lib-source-maps/index.js b/node_modules/istanbul-lib-source-maps/index.js new file mode 100644 index 0000000..1bcb74c --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/index.js @@ -0,0 +1,15 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const { MapStore } = require('./lib/map-store'); +/** + * @module Exports + */ +module.exports = { + createSourceMapStore(opts) { + return new MapStore(opts); + } +}; diff --git a/node_modules/istanbul-lib-source-maps/lib/get-mapping.js b/node_modules/istanbul-lib-source-maps/lib/get-mapping.js new file mode 100644 index 0000000..c24f618 --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/lib/get-mapping.js @@ -0,0 +1,182 @@ +/* + Copyright 2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const pathutils = require('./pathutils'); +const { + GREATEST_LOWER_BOUND, + LEAST_UPPER_BOUND +} = require('source-map').SourceMapConsumer; + +/** + * AST ranges are inclusive for start positions and exclusive for end positions. + * Source maps are also logically ranges over text, though interacting with + * them is generally achieved by working with explicit positions. + * + * When finding the _end_ location of an AST item, the range behavior is + * important because what we're asking for is the _end_ of whatever range + * corresponds to the end location we seek. + * + * This boils down to the following steps, conceptually, though the source-map + * library doesn't expose primitives to do this nicely: + * + * 1. Find the range on the generated file that ends at, or exclusively + * contains the end position of the AST node. + * 2. Find the range on the original file that corresponds to + * that generated range. + * 3. Find the _end_ location of that original range. + */ +function originalEndPositionFor(sourceMap, generatedEnd) { + // Given the generated location, find the original location of the mapping + // that corresponds to a range on the generated file that overlaps the + // generated file end location. Note however that this position on its + // own is not useful because it is the position of the _start_ of the range + // on the original file, and we want the _end_ of the range. + const beforeEndMapping = originalPositionTryBoth( + sourceMap, + generatedEnd.line, + generatedEnd.column - 1 + ); + if (beforeEndMapping.source === null) { + return null; + } + + // Convert that original position back to a generated one, with a bump + // to the right, and a rightward bias. Since 'generatedPositionFor' searches + // for mappings in the original-order sorted list, this will find the + // mapping that corresponds to the one immediately after the + // beforeEndMapping mapping. + const afterEndMapping = sourceMap.generatedPositionFor({ + source: beforeEndMapping.source, + line: beforeEndMapping.line, + column: beforeEndMapping.column + 1, + bias: LEAST_UPPER_BOUND + }); + if ( + // If this is null, it means that we've hit the end of the file, + // so we can use Infinity as the end column. + afterEndMapping.line === null || + // If these don't match, it means that the call to + // 'generatedPositionFor' didn't find any other original mappings on + // the line we gave, so consider the binding to extend to infinity. + sourceMap.originalPositionFor(afterEndMapping).line !== + beforeEndMapping.line + ) { + return { + source: beforeEndMapping.source, + line: beforeEndMapping.line, + column: Infinity + }; + } + + // Convert the end mapping into the real original position. + return sourceMap.originalPositionFor(afterEndMapping); +} + +/** + * Attempts to determine the original source position, first + * returning the closest element to the left (GREATEST_LOWER_BOUND), + * and next returning the closest element to the right (LEAST_UPPER_BOUND). + */ +function originalPositionTryBoth(sourceMap, line, column) { + const mapping = sourceMap.originalPositionFor({ + line, + column, + bias: GREATEST_LOWER_BOUND + }); + if (mapping.source === null) { + return sourceMap.originalPositionFor({ + line, + column, + bias: LEAST_UPPER_BOUND + }); + } else { + return mapping; + } +} + +function isInvalidPosition(pos) { + return ( + !pos || + typeof pos.line !== 'number' || + typeof pos.column !== 'number' || + pos.line < 0 || + pos.column < 0 + ); +} + +/** + * determines the original position for a given location + * @param {SourceMapConsumer} sourceMap the source map + * @param {Object} generatedLocation the original location Object + * @returns {Object} the remapped location Object + */ +function getMapping(sourceMap, generatedLocation, origFile) { + if (!generatedLocation) { + return null; + } + + if ( + isInvalidPosition(generatedLocation.start) || + isInvalidPosition(generatedLocation.end) + ) { + return null; + } + + const start = originalPositionTryBoth( + sourceMap, + generatedLocation.start.line, + generatedLocation.start.column + ); + let end = originalEndPositionFor(sourceMap, generatedLocation.end); + + /* istanbul ignore if: edge case too hard to test for */ + if (!(start && end)) { + return null; + } + + if (!(start.source && end.source)) { + return null; + } + + if (start.source !== end.source) { + return null; + } + + /* istanbul ignore if: edge case too hard to test for */ + if (start.line === null || start.column === null) { + return null; + } + + /* istanbul ignore if: edge case too hard to test for */ + if (end.line === null || end.column === null) { + return null; + } + + if (start.line === end.line && start.column === end.column) { + end = sourceMap.originalPositionFor({ + line: generatedLocation.end.line, + column: generatedLocation.end.column, + bias: LEAST_UPPER_BOUND + }); + end.column -= 1; + } + + return { + source: pathutils.relativeTo(start.source, origFile), + loc: { + start: { + line: start.line, + column: start.column + }, + end: { + line: end.line, + column: end.column + } + } + }; +} + +module.exports = getMapping; diff --git a/node_modules/istanbul-lib-source-maps/lib/map-store.js b/node_modules/istanbul-lib-source-maps/lib/map-store.js new file mode 100644 index 0000000..a99b79a --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/lib/map-store.js @@ -0,0 +1,226 @@ +/* + Copyright 2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const path = require('path'); +const fs = require('fs'); +const debug = require('debug')('istanbuljs'); +const { SourceMapConsumer } = require('source-map'); +const pathutils = require('./pathutils'); +const { SourceMapTransformer } = require('./transformer'); + +/** + * Tracks source maps for registered files + */ +class MapStore { + /** + * @param {Object} opts [opts=undefined] options. + * @param {Boolean} opts.verbose [opts.verbose=false] verbose mode + * @param {String} opts.baseDir [opts.baseDir=null] alternate base directory + * to resolve sourcemap files + * @param {Class} opts.SourceStore [opts.SourceStore=Map] class to use for + * SourceStore. Must support `get`, `set` and `clear` methods. + * @param {Array} opts.sourceStoreOpts [opts.sourceStoreOpts=[]] arguments + * to use in the SourceStore constructor. + * @constructor + */ + constructor(opts) { + opts = { + baseDir: null, + verbose: false, + SourceStore: Map, + sourceStoreOpts: [], + ...opts + }; + this.baseDir = opts.baseDir; + this.verbose = opts.verbose; + this.sourceStore = new opts.SourceStore(...opts.sourceStoreOpts); + this.data = Object.create(null); + this.sourceFinder = this.sourceFinder.bind(this); + } + + /** + * Registers a source map URL with this store. It makes some input sanity checks + * and silently fails on malformed input. + * @param transformedFilePath - the file path for which the source map is valid. + * This must *exactly* match the path stashed for the coverage object to be + * useful. + * @param sourceMapUrl - the source map URL, **not** a comment + */ + registerURL(transformedFilePath, sourceMapUrl) { + const d = 'data:'; + + if ( + sourceMapUrl.length > d.length && + sourceMapUrl.substring(0, d.length) === d + ) { + const b64 = 'base64,'; + const pos = sourceMapUrl.indexOf(b64); + if (pos > 0) { + this.data[transformedFilePath] = { + type: 'encoded', + data: sourceMapUrl.substring(pos + b64.length) + }; + } else { + debug(`Unable to interpret source map URL: ${sourceMapUrl}`); + } + + return; + } + + const dir = path.dirname(path.resolve(transformedFilePath)); + const file = path.resolve(dir, sourceMapUrl); + this.data[transformedFilePath] = { type: 'file', data: file }; + } + + /** + * Registers a source map object with this store. Makes some basic sanity checks + * and silently fails on malformed input. + * @param transformedFilePath - the file path for which the source map is valid + * @param sourceMap - the source map object + */ + registerMap(transformedFilePath, sourceMap) { + if (sourceMap && sourceMap.version) { + this.data[transformedFilePath] = { + type: 'object', + data: sourceMap + }; + } else { + debug( + 'Invalid source map object: ' + + JSON.stringify(sourceMap, null, 2) + ); + } + } + + /** + * Retrieve a source map object from this store. + * @param filePath - the file path for which the source map is valid + * @returns {Object} a parsed source map object + */ + getSourceMapSync(filePath) { + try { + if (!this.data[filePath]) { + return; + } + + const d = this.data[filePath]; + if (d.type === 'file') { + return JSON.parse(fs.readFileSync(d.data, 'utf8')); + } + + if (d.type === 'encoded') { + return JSON.parse(Buffer.from(d.data, 'base64').toString()); + } + + /* The caller might delete properties */ + return { + ...d.data + }; + } catch (error) { + debug('Error returning source map for ' + filePath); + debug(error.stack); + + return; + } + } + + /** + * Add inputSourceMap property to coverage data + * @param coverageData - the __coverage__ object + * @returns {Object} a parsed source map object + */ + addInputSourceMapsSync(coverageData) { + Object.entries(coverageData).forEach(([filePath, data]) => { + if (data.inputSourceMap) { + return; + } + + const sourceMap = this.getSourceMapSync(filePath); + if (sourceMap) { + data.inputSourceMap = sourceMap; + /* This huge property is not needed. */ + delete data.inputSourceMap.sourcesContent; + } + }); + } + + sourceFinder(filePath) { + const content = this.sourceStore.get(filePath); + if (content !== undefined) { + return content; + } + + if (path.isAbsolute(filePath)) { + return fs.readFileSync(filePath, 'utf8'); + } + + return fs.readFileSync( + pathutils.asAbsolute(filePath, this.baseDir), + 'utf8' + ); + } + + /** + * Transforms the coverage map provided into one that refers to original + * sources when valid mappings have been registered with this store. + * @param {CoverageMap} coverageMap - the coverage map to transform + * @returns {Promise} the transformed coverage map + */ + async transformCoverage(coverageMap) { + const hasInputSourceMaps = coverageMap + .files() + .some( + file => coverageMap.fileCoverageFor(file).data.inputSourceMap + ); + + if (!hasInputSourceMaps && Object.keys(this.data).length === 0) { + return coverageMap; + } + + const transformer = new SourceMapTransformer( + async (filePath, coverage) => { + try { + const obj = + coverage.data.inputSourceMap || + this.getSourceMapSync(filePath); + if (!obj) { + return null; + } + + const smc = new SourceMapConsumer(obj); + smc.sources.forEach(s => { + const content = smc.sourceContentFor(s); + if (content) { + const sourceFilePath = pathutils.relativeTo( + s, + filePath + ); + this.sourceStore.set(sourceFilePath, content); + } + }); + + return smc; + } catch (error) { + debug('Error returning source map for ' + filePath); + debug(error.stack); + + return null; + } + } + ); + + return await transformer.transform(coverageMap); + } + + /** + * Disposes temporary resources allocated by this map store + */ + dispose() { + this.sourceStore.clear(); + } +} + +module.exports = { MapStore }; diff --git a/node_modules/istanbul-lib-source-maps/lib/mapped.js b/node_modules/istanbul-lib-source-maps/lib/mapped.js new file mode 100644 index 0000000..73f256c --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/lib/mapped.js @@ -0,0 +1,113 @@ +/* + Copyright 2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const { FileCoverage } = require('istanbul-lib-coverage').classes; + +function locString(loc) { + return [ + loc.start.line, + loc.start.column, + loc.end.line, + loc.end.column + ].join(':'); +} + +class MappedCoverage extends FileCoverage { + constructor(pathOrObj) { + super(pathOrObj); + + this.meta = { + last: { + s: 0, + f: 0, + b: 0 + }, + seen: {} + }; + } + + addStatement(loc, hits) { + const key = 's:' + locString(loc); + const { meta } = this; + let index = meta.seen[key]; + + if (index === undefined) { + index = meta.last.s; + meta.last.s += 1; + meta.seen[key] = index; + this.statementMap[index] = this.cloneLocation(loc); + } + + this.s[index] = this.s[index] || 0; + this.s[index] += hits; + return index; + } + + addFunction(name, decl, loc, hits) { + const key = 'f:' + locString(decl); + const { meta } = this; + let index = meta.seen[key]; + + if (index === undefined) { + index = meta.last.f; + meta.last.f += 1; + meta.seen[key] = index; + name = name || `(unknown_${index})`; + this.fnMap[index] = { + name, + decl: this.cloneLocation(decl), + loc: this.cloneLocation(loc) + }; + } + + this.f[index] = this.f[index] || 0; + this.f[index] += hits; + return index; + } + + addBranch(type, loc, branchLocations, hits) { + const key = ['b', ...branchLocations.map(l => locString(l))].join(':'); + const { meta } = this; + let index = meta.seen[key]; + if (index === undefined) { + index = meta.last.b; + meta.last.b += 1; + meta.seen[key] = index; + this.branchMap[index] = { + loc, + type, + locations: branchLocations.map(l => this.cloneLocation(l)) + }; + } + + if (!this.b[index]) { + this.b[index] = branchLocations.map(() => 0); + } + + hits.forEach((hit, i) => { + this.b[index][i] += hit; + }); + return index; + } + + /* Returns a clone of the location object with only the attributes of interest */ + cloneLocation(loc) { + return { + start: { + line: loc.start.line, + column: loc.start.column + }, + end: { + line: loc.end.line, + column: loc.end.column + } + }; + } +} + +module.exports = { + MappedCoverage +}; diff --git a/node_modules/istanbul-lib-source-maps/lib/pathutils.js b/node_modules/istanbul-lib-source-maps/lib/pathutils.js new file mode 100644 index 0000000..7dca05a --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/lib/pathutils.js @@ -0,0 +1,21 @@ +/* + Copyright 2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const path = require('path'); + +module.exports = { + isAbsolute: path.isAbsolute, + asAbsolute(file, baseDir) { + return path.isAbsolute(file) + ? file + : path.resolve(baseDir || process.cwd(), file); + }, + relativeTo(file, origFile) { + return path.isAbsolute(file) + ? file + : path.resolve(path.dirname(origFile), file); + } +}; diff --git a/node_modules/istanbul-lib-source-maps/lib/transform-utils.js b/node_modules/istanbul-lib-source-maps/lib/transform-utils.js new file mode 100644 index 0000000..0933093 --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/lib/transform-utils.js @@ -0,0 +1,21 @@ +/* + Copyright 2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +function getUniqueKey(pathname) { + return pathname.replace(/[\\/]/g, '_'); +} + +function getOutput(cache) { + return Object.values(cache).reduce( + (output, { file, mappedCoverage }) => ({ + ...output, + [file]: mappedCoverage + }), + {} + ); +} + +module.exports = { getUniqueKey, getOutput }; diff --git a/node_modules/istanbul-lib-source-maps/lib/transformer.js b/node_modules/istanbul-lib-source-maps/lib/transformer.js new file mode 100644 index 0000000..6f63538 --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/lib/transformer.js @@ -0,0 +1,147 @@ +/* + Copyright 2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; + +const debug = require('debug')('istanbuljs'); +const libCoverage = require('istanbul-lib-coverage'); +const { MappedCoverage } = require('./mapped'); +const getMapping = require('./get-mapping'); +const { getUniqueKey, getOutput } = require('./transform-utils'); + +class SourceMapTransformer { + constructor(finder, opts = {}) { + this.finder = finder; + this.baseDir = opts.baseDir || process.cwd(); + this.resolveMapping = opts.getMapping || getMapping; + } + + processFile(fc, sourceMap, coverageMapper) { + let changes = 0; + + Object.entries(fc.statementMap).forEach(([s, loc]) => { + const hits = fc.s[s]; + const mapping = this.resolveMapping(sourceMap, loc, fc.path); + + if (mapping) { + changes += 1; + const mappedCoverage = coverageMapper(mapping.source); + mappedCoverage.addStatement(mapping.loc, hits); + } + }); + + Object.entries(fc.fnMap).forEach(([f, fnMeta]) => { + const hits = fc.f[f]; + const mapping = this.resolveMapping( + sourceMap, + fnMeta.decl, + fc.path + ); + + const spanMapping = this.resolveMapping( + sourceMap, + fnMeta.loc, + fc.path + ); + + if ( + mapping && + spanMapping && + mapping.source === spanMapping.source + ) { + changes += 1; + const mappedCoverage = coverageMapper(mapping.source); + mappedCoverage.addFunction( + fnMeta.name, + mapping.loc, + spanMapping.loc, + hits + ); + } + }); + + Object.entries(fc.branchMap).forEach(([b, branchMeta]) => { + const hits = fc.b[b]; + const locs = []; + const mappedHits = []; + let source; + let skip; + + branchMeta.locations.forEach((loc, i) => { + const mapping = this.resolveMapping(sourceMap, loc, fc.path); + if (mapping) { + if (!source) { + source = mapping.source; + } + + if (mapping.source !== source) { + skip = true; + } + + locs.push(mapping.loc); + mappedHits.push(hits[i]); + } + }); + + const locMapping = branchMeta.loc + ? this.resolveMapping(sourceMap, branchMeta.loc, fc.path) + : null; + + if (!skip && locs.length > 0) { + changes += 1; + const mappedCoverage = coverageMapper(source); + mappedCoverage.addBranch( + branchMeta.type, + locMapping ? locMapping.loc : locs[0], + locs, + mappedHits + ); + } + }); + + return changes > 0; + } + + async transform(coverageMap) { + const uniqueFiles = {}; + const getMappedCoverage = file => { + const key = getUniqueKey(file); + if (!uniqueFiles[key]) { + uniqueFiles[key] = { + file, + mappedCoverage: new MappedCoverage(file) + }; + } + + return uniqueFiles[key].mappedCoverage; + }; + + for (const file of coverageMap.files()) { + const fc = coverageMap.fileCoverageFor(file); + const sourceMap = await this.finder(file, fc); + + if (sourceMap) { + const changed = this.processFile( + fc, + sourceMap, + getMappedCoverage + ); + if (!changed) { + debug(`File [${file}] ignored, nothing could be mapped`); + } + } else { + uniqueFiles[getUniqueKey(file)] = { + file, + mappedCoverage: new MappedCoverage(fc) + }; + } + } + + return libCoverage.createCoverageMap(getOutput(uniqueFiles)); + } +} + +module.exports = { + SourceMapTransformer +}; diff --git a/node_modules/istanbul-lib-source-maps/package.json b/node_modules/istanbul-lib-source-maps/package.json new file mode 100644 index 0000000..2798300 --- /dev/null +++ b/node_modules/istanbul-lib-source-maps/package.json @@ -0,0 +1,45 @@ +{ + "name": "istanbul-lib-source-maps", + "version": "4.0.1", + "description": "Source maps support for istanbul", + "author": "Krishnan Anantheswaran ", + "main": "index.js", + "files": [ + "lib", + "index.js" + ], + "scripts": { + "test": "nyc mocha" + }, + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "devDependencies": { + "chai": "^4.2.0", + "mocha": "^6.2.2", + "nyc": "^15.0.0-beta.2", + "ts-node": "^8.5.4" + }, + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/istanbuljs/istanbuljs/issues" + }, + "homepage": "https://istanbul.js.org/", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/istanbuljs/istanbuljs.git", + "directory": "packages/istanbul-lib-source-maps" + }, + "keywords": [ + "istanbul", + "sourcemaps", + "sourcemap", + "source", + "maps" + ], + "engines": { + "node": ">=10" + } +} diff --git a/node_modules/istanbul-reports/CHANGELOG.md b/node_modules/istanbul-reports/CHANGELOG.md new file mode 100644 index 0000000..71ad3d1 --- /dev/null +++ b/node_modules/istanbul-reports/CHANGELOG.md @@ -0,0 +1,457 @@ +# Change Log + +All notable changes to this project will be documented in this file. +See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. + +## [3.1.6](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.1.5...istanbul-reports-v3.1.6) (2023-07-25) + + +### Bug Fixes + +* **clover:** always close last open tag ([07c6ea6](https://github.com/istanbuljs/istanbuljs/commit/07c6ea6537261a19b117702b7362dee0bdc001ac)) + +## [3.1.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.1.4...istanbul-reports-v3.1.5) (2022-07-13) + + +### Bug Fixes + +* `new Date()` such that it works with MockDate library ([#688](https://github.com/istanbuljs/istanbuljs/issues/688)) ([85905f9](https://github.com/istanbuljs/istanbuljs/commit/85905f989c9480e63ad534c6ff8b1a12dae278eb)) +* add placeholder to fix Implicit Else ([#679](https://github.com/istanbuljs/istanbuljs/issues/679)) ([0516f51](https://github.com/istanbuljs/istanbuljs/commit/0516f519575ee28f77ebf1e9556ac294d78904ea)) + +### [3.1.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.1.3...istanbul-reports-v3.1.4) (2022-01-17) + + +### Bug Fixes + +* "E" is not showing in the HTML reporter for "implicit else" branches after pull 633 ([#663](https://github.com/istanbuljs/istanbuljs/issues/663)) ([7818922](https://github.com/istanbuljs/istanbuljs/commit/7818922fd7229c4eee12b1407b5a13020f5d34de)) + +### [3.1.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.1.2...istanbul-reports-v3.1.3) (2021-12-29) + + +### Bug Fixes + +* reverse tabnabbing vulnerability in URLs ([#591](https://github.com/istanbuljs/istanbuljs/issues/591)) ([4eceb9e](https://github.com/istanbuljs/istanbuljs/commit/4eceb9eb8b3169b882d74ecc526fb5837ebc6205)) + +### [3.1.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.1.1...istanbul-reports-v3.1.2) (2021-12-23) + + +### Bug Fixes + +* remove stray div tag from HTML report ([68d9c74](https://github.com/istanbuljs/istanbuljs/commit/68d9c7469927ddcf15346307eacea8fd7104086c)) + +### [3.1.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.1.0...istanbul-reports-v3.1.1) (2021-12-01) + + +### Bug Fixes + +* rel="noopener" to the link in the generated html reports ([f234bb3](https://github.com/istanbuljs/istanbuljs/commit/f234bb321421e7312a83595934a1abf81c7af70c)) + +## [3.1.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.0.5...istanbul-reports-v3.1.0) (2021-11-30) + + +### Features + +* add filter to HTML report ([#650](https://github.com/istanbuljs/istanbuljs/issues/650)) ([eab47f7](https://github.com/istanbuljs/istanbuljs/commit/eab47f76be90343f679ef0e5567a21447a4995dc)) + +### [3.0.5](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.0.4...istanbul-reports-v3.0.5) (2021-10-13) + + +### Bug Fixes + +* cobertura reports in root folder ([#571](https://www.github.com/istanbuljs/istanbuljs/issues/571)) ([596f6ff](https://www.github.com/istanbuljs/istanbuljs/commit/596f6ff1342ae4baa6688bf3ee7786c75d4df947)) + +### [3.0.4](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.0.3...istanbul-reports-v3.0.4) (2021-10-12) + + +### Bug Fixes + +* handle reports with "loc" but no "decl" ([#637](https://www.github.com/istanbuljs/istanbuljs/issues/637)) ([cdc28f3](https://www.github.com/istanbuljs/istanbuljs/commit/cdc28f3a1e80e786eaab3b7d3b8b9b558fc2d3c8)), closes [#322](https://www.github.com/istanbuljs/istanbuljs/issues/322) + +### [3.0.3](https://www.github.com/istanbuljs/istanbuljs/compare/istanbul-reports-v3.0.2...istanbul-reports-v3.0.3) (2021-10-06) + + +### Bug Fixes + +* lcov reporter crash when missing branches ([#613](https://www.github.com/istanbuljs/istanbuljs/issues/613)) ([d34981c](https://www.github.com/istanbuljs/istanbuljs/commit/d34981c8131e2ecbff6fc02ffd8702fd9808e241)) + +## [3.0.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.1...istanbul-reports@3.0.2) (2020-04-01) + + +### Bug Fixes + +* Ignore insignificant lines when coalesce ([#525](https://github.com/istanbuljs/istanbuljs/issues/525)) ([d7d7cfa](https://github.com/istanbuljs/istanbuljs/commit/d7d7cfa1301f0dde2ff19078c31235ffd55c01ef)) + + + + + +## [3.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.0...istanbul-reports@3.0.1) (2020-03-26) + + +### Bug Fixes + +* cobertura should escape invalid characters ([#534](https://github.com/istanbuljs/istanbuljs/issues/534)) ([4fd5114](https://github.com/istanbuljs/istanbuljs/commit/4fd5114a0926d20e4e1e3055323c44281f0af6cd)) + + + + + +# [3.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.0-alpha.6...istanbul-reports@3.0.0) (2019-12-20) + + +### Features + +* **text:** Coalesce ranges of missing lines ([#511](https://github.com/istanbuljs/istanbuljs/issues/511)) ([54636fc](https://github.com/istanbuljs/istanbuljs/commit/54636fc9acbb53e5724fe9018837d0d205413194)) + + + + + +# [3.0.0-alpha.6](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.0-alpha.5...istanbul-reports@3.0.0-alpha.6) (2019-12-07) + + +### Bug Fixes + +* Add favicon to html report ([#493](https://github.com/istanbuljs/istanbuljs/issues/493)) ([5afe203](https://github.com/istanbuljs/istanbuljs/commit/5afe20347dd3ae954b31707a67f381f87920797f)) + + + + + +# [3.0.0-alpha.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.0-alpha.4...istanbul-reports@3.0.0-alpha.5) (2019-11-22) + + +### Features + +* Add support for projectRoot option ([#492](https://github.com/istanbuljs/istanbuljs/issues/492)) ([177fd45](https://github.com/istanbuljs/istanbuljs/commit/177fd45ebd7e505e79120995d937d40f965bad79)) + + + + + +# [3.0.0-alpha.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.0-alpha.3...istanbul-reports@3.0.0-alpha.4) (2019-11-18) + + +### Bug Fixes + +* Remove handlebars ([#503](https://github.com/istanbuljs/istanbuljs/issues/503)) ([aa8ae7f](https://github.com/istanbuljs/istanbuljs/commit/aa8ae7fe42ef9c8aeaa193309bafb22ad725bc3d)), closes [#476](https://github.com/istanbuljs/istanbuljs/issues/476) + + + + + +# [3.0.0-alpha.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.0-alpha.2...istanbul-reports@3.0.0-alpha.3) (2019-10-19) + + +### Bug Fixes + +* Add missing dependency on istanbul-lib-report ([#490](https://github.com/istanbuljs/istanbuljs/issues/490)) ([95a2b2f](https://github.com/istanbuljs/istanbuljs/commit/95a2b2f)), closes [istanbuljs/nyc#1204](https://github.com/istanbuljs/nyc/issues/1204) + + + + + +# [3.0.0-alpha.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.0-alpha.1...istanbul-reports@3.0.0-alpha.2) (2019-10-06) + + +### Bug Fixes + +* Use path.posix.relative to generate URL's for html reports ([#472](https://github.com/istanbuljs/istanbuljs/issues/472)) ([05dc22c](https://github.com/istanbuljs/istanbuljs/commit/05dc22c)) +* **html-spa:** Filter only exact paths ([#431](https://github.com/istanbuljs/istanbuljs/issues/431)) ([bbc85f6](https://github.com/istanbuljs/istanbuljs/commit/bbc85f6)), closes [#426](https://github.com/istanbuljs/istanbuljs/issues/426) + + + + + +# [3.0.0-alpha.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@3.0.0-alpha.0...istanbul-reports@3.0.0-alpha.1) (2019-06-20) + + +### Bug Fixes + +* Set `opts.file = '-'` on text-lcov ([#424](https://github.com/istanbuljs/istanbuljs/issues/424)) ([4be56b2](https://github.com/istanbuljs/istanbuljs/commit/4be56b2)) + + + + + +# [3.0.0-alpha.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.2.5...istanbul-reports@3.0.0-alpha.0) (2019-06-19) + + +### Features + +* Refactor istanbul-lib-report so report can choose summarizer ([#408](https://github.com/istanbuljs/istanbuljs/issues/408)) ([0f328fd](https://github.com/istanbuljs/istanbuljs/commit/0f328fd)) +* **text report:** Optimize output to show more missing lines ([#341](https://github.com/istanbuljs/istanbuljs/issues/341)) ([c4e8b8e](https://github.com/istanbuljs/istanbuljs/commit/c4e8b8e)) +* Modern html report ([#345](https://github.com/istanbuljs/istanbuljs/issues/345)) ([95ebaf1](https://github.com/istanbuljs/istanbuljs/commit/95ebaf1)) +* Update dependencies, require Node.js 8 ([#401](https://github.com/istanbuljs/istanbuljs/issues/401)) ([bf3a539](https://github.com/istanbuljs/istanbuljs/commit/bf3a539)) + + +### BREAKING CHANGES + +* Existing istanbul-lib-report API's have been changed +* Node.js 8 is now required + + + + + +## [2.2.5](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.2.4...istanbul-reports@2.2.5) (2019-05-02) + + +### Bug Fixes + +* **istanbul-reports:** Remove isRoot check causing incorrect report formatting ([#66](https://github.com/istanbuljs/istanbuljs/issues/66)). ([#382](https://github.com/istanbuljs/istanbuljs/issues/382)) ([df6e994](https://github.com/istanbuljs/istanbuljs/commit/df6e994)) + + + + + +## [2.2.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.2.3...istanbul-reports@2.2.4) (2019-04-24) + +**Note:** Version bump only for package istanbul-reports + + + + + +## [2.2.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.2.2...istanbul-reports@2.2.3) (2019-04-17) + + +### Bug Fixes + +* Initialize cols for HTML report sorting ([#369](https://github.com/istanbuljs/istanbuljs/issues/369)) ([28f61de](https://github.com/istanbuljs/istanbuljs/commit/28f61de)) + + + + + +## [2.2.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.2.1...istanbul-reports@2.2.2) (2019-04-09) + +**Note:** Version bump only for package istanbul-reports + + + + + +## [2.2.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.2.0...istanbul-reports@2.2.1) (2019-04-03) + +**Note:** Version bump only for package istanbul-reports + + + + + +# [2.2.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.1.1...istanbul-reports@2.2.0) (2019-03-12) + + +### Features + +* set medium colour to yellow ([#306](https://github.com/istanbuljs/istanbuljs/issues/306)) ([ed40be7](https://github.com/istanbuljs/istanbuljs/commit/ed40be7)) + + + + + +## [2.1.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.1.0...istanbul-reports@2.1.1) (2019-02-14) + + +### Bug Fixes + +* update dependendencies due to vulnerabilities ([#294](https://github.com/istanbuljs/istanbuljs/issues/294)) ([4c14fed](https://github.com/istanbuljs/istanbuljs/commit/4c14fed)) + + + + + +# [2.1.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.0.3...istanbul-reports@2.1.0) (2019-01-26) + + +### Features + +* **istanbul-reports:** Enable keyboard shortcuts on HTML report file listing view ([#265](https://github.com/istanbuljs/istanbuljs/issues/265)) ([f49b355](https://github.com/istanbuljs/istanbuljs/commit/f49b355)) + + + + + + +## [2.0.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.0.2...istanbul-reports@2.0.3) (2018-12-25) + + +### Bug Fixes + +* functionMap is sometimes missing a key from functions ([#253](https://github.com/istanbuljs/istanbuljs/issues/253)) ([399f215](https://github.com/istanbuljs/istanbuljs/commit/399f215)) + + + + + +## [2.0.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.0.1...istanbul-reports@2.0.2) (2018-12-19) + + +### Bug Fixes + +* clover report metrics must be an inline xml element ([#226](https://github.com/istanbuljs/istanbuljs/issues/226)) ([e290c95](https://github.com/istanbuljs/istanbuljs/commit/e290c95)), closes [#13](https://github.com/istanbuljs/istanbuljs/issues/13) + + + + + +## [2.0.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@2.0.0...istanbul-reports@2.0.1) (2018-09-06) + + + + +**Note:** Version bump only for package istanbul-reports + + +# [2.0.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.5.0...istanbul-reports@2.0.0) (2018-07-07) + + +### Chores + +* Specify node >= 6 in istanbul-reports. ([#197](https://github.com/istanbuljs/istanbuljs/issues/197)) ([5810c38](https://github.com/istanbuljs/istanbuljs/commit/5810c38)) + + +### BREAKING CHANGES + +* Requires node >= 6. + + + + + +# [1.5.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.4.1...istanbul-reports@1.5.0) (2018-06-06) + + +### Features + +* ability to skip rows with full coverage ([#170](https://github.com/istanbuljs/istanbuljs/issues/170)) ([bbcdc07](https://github.com/istanbuljs/istanbuljs/commit/bbcdc07)) + + + + + +## [1.4.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.4.0...istanbul-reports@1.4.1) (2018-05-31) + + +### Bug Fixes + +* ensure using correct context ([#168](https://github.com/istanbuljs/istanbuljs/issues/168)) ([df102fd](https://github.com/istanbuljs/istanbuljs/commit/df102fd)) + + + + + +# [1.4.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.3.0...istanbul-reports@1.4.0) (2018-04-17) + + +### Features + +* allow custom reporters to be loaded ([#155](https://github.com/istanbuljs/istanbuljs/issues/155)) ([6d89cca](https://github.com/istanbuljs/istanbuljs/commit/6d89cca)) + + + + + +# [1.3.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.2.0...istanbul-reports@1.3.0) (2018-03-09) + + +### Features + +* added named anchors to code coverage line numbers. ([#149](https://github.com/istanbuljs/istanbuljs/issues/149)) ([98e1c50](https://github.com/istanbuljs/istanbuljs/commit/98e1c50)) + + + + + +# [1.2.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.1.4...istanbul-reports@1.2.0) (2018-03-04) + + +### Bug Fixes + +* update fixtures to reflect new heading ([36801d3](https://github.com/istanbuljs/istanbuljs/commit/36801d3)) + + +### Features + +* add skip-empty option for html & text reports ([#140](https://github.com/istanbuljs/istanbuljs/issues/140)) ([d2a4262](https://github.com/istanbuljs/istanbuljs/commit/d2a4262)) +* add uncovered block navigation ([#136](https://github.com/istanbuljs/istanbuljs/issues/136)) ([c798930](https://github.com/istanbuljs/istanbuljs/commit/c798930)) + + + + + +## [1.1.4](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.1.3...istanbul-reports@1.1.4) (2018-02-13) + + +### Bug Fixes + +* changed column header from "Uncovered Lines" to "Uncovered Line #s" ([#138](https://github.com/istanbuljs/istanbuljs/issues/138)) ([7ba7760](https://github.com/istanbuljs/istanbuljs/commit/7ba7760)) + + + + + +## [1.1.3](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.1.2...istanbul-reports@1.1.3) (2017-10-21) + + + + +**Note:** Version bump only for package istanbul-reports + + +## [1.1.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.1.1...istanbul-reports@1.1.2) (2017-08-26) + + +### Bug Fixes + +* prevent branch highlighting from extending pass the end of a line ([#80](https://github.com/istanbuljs/istanbuljs/issues/80)) ([f490377](https://github.com/istanbuljs/istanbuljs/commit/f490377)) + + + + + +## [1.1.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-reports@1.1.0...istanbul-reports@1.1.1) (2017-05-27) + + + + + +# [1.1.0](https://github.com/istanbuljs/istanbul-reports/compare/istanbul-reports@1.0.2...istanbul-reports@1.1.0) (2017-04-29) + + +### Features + +* once 100% line coverage is achieved, missing branch coverage is now shown in text report ([#45](https://github.com/istanbuljs/istanbuljs/issues/45)) ([8a809f8](https://github.com/istanbuljs/istanbul-reports/commit/8a809f8)) + + + + + +## [1.0.2](https://github.com/istanbuljs/istanbul-reports/compare/istanbul-reports@1.0.1...istanbul-reports@1.0.2) (2017-03-27) + + +### Bug Fixes + +* **windows:** preserve escape char of json-summary key path ([4d71d5e](https://github.com/istanbuljs/istanbul-reports/commit/4d71d5e)) + + +## [1.0.1](https://github.com/istanbuljs/istanbul-reports/compare/v1.0.0...v1.0.1) (2017-01-29) + + +### Bug Fixes + +* add files key to package.json ([#17](https://github.com/istanbuljs/istanbul-reports/issues/17)) ([141f801](https://github.com/istanbuljs/istanbul-reports/commit/141f801)) + + + + +# [1.0.0](https://github.com/istanbuljs/istanbul-reports/compare/v1.0.0-alpha.8...v1.0.0) (2016-10-17) + + +### Bug Fixes + +* fail gracefully if structuredText[startLine] is undefined ([#10](https://github.com/istanbuljs/istanbul-reports/issues/10)) ([bed1d13](https://github.com/istanbuljs/istanbul-reports/commit/bed1d13)) +* preserve escape char of json key path on Windows ([#12](https://github.com/istanbuljs/istanbul-reports/issues/12)) ([4e5266e](https://github.com/istanbuljs/istanbul-reports/commit/4e5266e)) +* skip branch if meta does not exist (fixes speedskater/babel-plugin-rewire[#165](https://github.com/istanbuljs/istanbul-reports/issues/165)) ([#11](https://github.com/istanbuljs/istanbul-reports/issues/11)) ([62bae2f](https://github.com/istanbuljs/istanbul-reports/commit/62bae2f)) +* Teamcity reporter modified to send proper coverage values ([#8](https://github.com/istanbuljs/istanbul-reports/issues/8)) ([4147f50](https://github.com/istanbuljs/istanbul-reports/commit/4147f50)) diff --git a/node_modules/istanbul-reports/LICENSE b/node_modules/istanbul-reports/LICENSE new file mode 100644 index 0000000..d55d291 --- /dev/null +++ b/node_modules/istanbul-reports/LICENSE @@ -0,0 +1,24 @@ +Copyright 2012-2015 Yahoo! Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * 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. + * Neither the name of the Yahoo! Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. 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. diff --git a/node_modules/istanbul-reports/README.md b/node_modules/istanbul-reports/README.md new file mode 100644 index 0000000..09b6428 --- /dev/null +++ b/node_modules/istanbul-reports/README.md @@ -0,0 +1,13 @@ +# istanbul-reports + +[![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-reports.svg)](https://greenkeeper.io/) +[![Build Status](https://travis-ci.org/istanbuljs/istanbul-reports.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-reports) + +- node.getRelativeName + +- context.getSource(filePath) +- context.classForPercent(type, percent) +- context.console.colorize(str, class) +- context.writer +- context.console.write +- context.console.println diff --git a/node_modules/istanbul-reports/index.js b/node_modules/istanbul-reports/index.js new file mode 100644 index 0000000..f0a7aa3 --- /dev/null +++ b/node_modules/istanbul-reports/index.js @@ -0,0 +1,24 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const path = require('path'); + +module.exports = { + create(name, cfg) { + cfg = cfg || {}; + let Cons; + try { + Cons = require(path.join(__dirname, 'lib', name)); + } catch (e) { + if (e.code !== 'MODULE_NOT_FOUND') { + throw e; + } + + Cons = require(name); + } + + return new Cons(cfg); + } +}; diff --git a/node_modules/istanbul-reports/lib/clover/index.js b/node_modules/istanbul-reports/lib/clover/index.js new file mode 100644 index 0000000..40d1606 --- /dev/null +++ b/node_modules/istanbul-reports/lib/clover/index.js @@ -0,0 +1,163 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const { ReportBase } = require('istanbul-lib-report'); + +class CloverReport extends ReportBase { + constructor(opts) { + super(); + + this.cw = null; + this.xml = null; + this.file = opts.file || 'clover.xml'; + } + + onStart(root, context) { + this.cw = context.writer.writeFile(this.file); + this.xml = context.getXMLWriter(this.cw); + this.writeRootStats(root, context); + } + + onEnd() { + this.xml.closeAll(); + this.cw.close(); + } + + getTreeStats(node, context) { + const state = { + packages: 0, + files: 0, + classes: 0 + }; + const visitor = { + onSummary(node, state) { + const metrics = node.getCoverageSummary(true); + if (metrics) { + state.packages += 1; + } + }, + onDetail(node, state) { + state.classes += 1; + state.files += 1; + } + }; + node.visit(context.getVisitor(visitor), state); + return state; + } + + writeRootStats(node, context) { + this.cw.println(''); + this.xml.openTag('coverage', { + generated: Date.now().toString(), + clover: '3.2.0' + }); + + this.xml.openTag('project', { + timestamp: Date.now().toString(), + name: 'All files' + }); + + const metrics = node.getCoverageSummary(); + this.xml.inlineTag('metrics', { + statements: metrics.lines.total, + coveredstatements: metrics.lines.covered, + conditionals: metrics.branches.total, + coveredconditionals: metrics.branches.covered, + methods: metrics.functions.total, + coveredmethods: metrics.functions.covered, + elements: + metrics.lines.total + + metrics.branches.total + + metrics.functions.total, + coveredelements: + metrics.lines.covered + + metrics.branches.covered + + metrics.functions.covered, + complexity: 0, + loc: metrics.lines.total, + ncloc: metrics.lines.total, // what? copied as-is from old report + ...this.getTreeStats(node, context) + }); + } + + writeMetrics(metrics) { + this.xml.inlineTag('metrics', { + statements: metrics.lines.total, + coveredstatements: metrics.lines.covered, + conditionals: metrics.branches.total, + coveredconditionals: metrics.branches.covered, + methods: metrics.functions.total, + coveredmethods: metrics.functions.covered + }); + } + + onSummary(node) { + if (node.isRoot()) { + return; + } + const metrics = node.getCoverageSummary(true); + if (!metrics) { + return; + } + + this.xml.openTag('package', { + name: asJavaPackage(node) + }); + this.writeMetrics(metrics); + } + + onSummaryEnd(node) { + if (node.isRoot()) { + return; + } + this.xml.closeTag(this.xml.stack[this.xml.stack.length - 1]); + } + + onDetail(node) { + const fileCoverage = node.getFileCoverage(); + const metrics = node.getCoverageSummary(); + const branchByLine = fileCoverage.getBranchCoverageByLine(); + + this.xml.openTag('file', { + name: asClassName(node), + path: fileCoverage.path + }); + + this.writeMetrics(metrics); + + const lines = fileCoverage.getLineCoverage(); + Object.entries(lines).forEach(([k, count]) => { + const attrs = { + num: k, + count, + type: 'stmt' + }; + const branchDetail = branchByLine[k]; + + if (branchDetail) { + attrs.type = 'cond'; + attrs.truecount = branchDetail.covered; + attrs.falsecount = branchDetail.total - branchDetail.covered; + } + this.xml.inlineTag('line', attrs); + }); + + this.xml.closeTag('file'); + } +} + +function asJavaPackage(node) { + return node + .getRelativeName() + .replace(/\//g, '.') + .replace(/\\/g, '.') + .replace(/\.$/, ''); +} + +function asClassName(node) { + return node.getRelativeName().replace(/.*[\\/]/, ''); +} + +module.exports = CloverReport; diff --git a/node_modules/istanbul-reports/lib/cobertura/index.js b/node_modules/istanbul-reports/lib/cobertura/index.js new file mode 100644 index 0000000..e5574fa --- /dev/null +++ b/node_modules/istanbul-reports/lib/cobertura/index.js @@ -0,0 +1,151 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const path = require('path'); +const { escape } = require('html-escaper'); +const { ReportBase } = require('istanbul-lib-report'); + +class CoberturaReport extends ReportBase { + constructor(opts) { + super(); + + opts = opts || {}; + + this.cw = null; + this.xml = null; + this.timestamp = opts.timestamp || Date.now().toString(); + this.projectRoot = opts.projectRoot || process.cwd(); + this.file = opts.file || 'cobertura-coverage.xml'; + } + + onStart(root, context) { + this.cw = context.writer.writeFile(this.file); + this.xml = context.getXMLWriter(this.cw); + this.writeRootStats(root); + } + + onEnd() { + this.xml.closeAll(); + this.cw.close(); + } + + writeRootStats(node) { + const metrics = node.getCoverageSummary(); + this.cw.println(''); + this.cw.println( + '' + ); + this.xml.openTag('coverage', { + 'lines-valid': metrics.lines.total, + 'lines-covered': metrics.lines.covered, + 'line-rate': metrics.lines.pct / 100.0, + 'branches-valid': metrics.branches.total, + 'branches-covered': metrics.branches.covered, + 'branch-rate': metrics.branches.pct / 100.0, + timestamp: this.timestamp, + complexity: '0', + version: '0.1' + }); + this.xml.openTag('sources'); + this.xml.inlineTag('source', null, this.projectRoot); + this.xml.closeTag('sources'); + this.xml.openTag('packages'); + } + + onSummary(node) { + const metrics = node.getCoverageSummary(true); + if (!metrics) { + return; + } + this.xml.openTag('package', { + name: node.isRoot() ? 'main' : escape(asJavaPackage(node)), + 'line-rate': metrics.lines.pct / 100.0, + 'branch-rate': metrics.branches.pct / 100.0 + }); + this.xml.openTag('classes'); + } + + onSummaryEnd(node) { + const metrics = node.getCoverageSummary(true); + if (!metrics) { + return; + } + this.xml.closeTag('classes'); + this.xml.closeTag('package'); + } + + onDetail(node) { + const fileCoverage = node.getFileCoverage(); + const metrics = node.getCoverageSummary(); + const branchByLine = fileCoverage.getBranchCoverageByLine(); + + this.xml.openTag('class', { + name: escape(asClassName(node)), + filename: path.relative(this.projectRoot, fileCoverage.path), + 'line-rate': metrics.lines.pct / 100.0, + 'branch-rate': metrics.branches.pct / 100.0 + }); + + this.xml.openTag('methods'); + const fnMap = fileCoverage.fnMap; + Object.entries(fnMap).forEach(([k, { name, decl }]) => { + const hits = fileCoverage.f[k]; + this.xml.openTag('method', { + name: escape(name), + hits, + signature: '()V' //fake out a no-args void return + }); + this.xml.openTag('lines'); + //Add the function definition line and hits so that jenkins cobertura plugin records method hits + this.xml.inlineTag('line', { + number: decl.start.line, + hits + }); + this.xml.closeTag('lines'); + this.xml.closeTag('method'); + }); + this.xml.closeTag('methods'); + + this.xml.openTag('lines'); + const lines = fileCoverage.getLineCoverage(); + Object.entries(lines).forEach(([k, hits]) => { + const attrs = { + number: k, + hits, + branch: 'false' + }; + const branchDetail = branchByLine[k]; + + if (branchDetail) { + attrs.branch = true; + attrs['condition-coverage'] = + branchDetail.coverage + + '% (' + + branchDetail.covered + + '/' + + branchDetail.total + + ')'; + } + this.xml.inlineTag('line', attrs); + }); + + this.xml.closeTag('lines'); + this.xml.closeTag('class'); + } +} + +function asJavaPackage(node) { + return node + .getRelativeName() + .replace(/\//g, '.') + .replace(/\\/g, '.') + .replace(/\.$/, ''); +} + +function asClassName(node) { + return node.getRelativeName().replace(/.*[\\/]/, ''); +} + +module.exports = CoberturaReport; diff --git a/node_modules/istanbul-reports/lib/html-spa/.babelrc b/node_modules/istanbul-reports/lib/html-spa/.babelrc new file mode 100644 index 0000000..f995d68 --- /dev/null +++ b/node_modules/istanbul-reports/lib/html-spa/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": [["@babel/preset-env", { "modules": "commonjs" }], "@babel/preset-react"] +} diff --git a/node_modules/istanbul-reports/lib/html-spa/assets/bundle.js b/node_modules/istanbul-reports/lib/html-spa/assets/bundle.js new file mode 100644 index 0000000..b0fdef2 --- /dev/null +++ b/node_modules/istanbul-reports/lib/html-spa/assets/bundle.js @@ -0,0 +1,30 @@ +!function(e){var t={};function n(r){if(t[r])return t[r].exports;var l=t[r]={i:r,l:!1,exports:{}};return e[r].call(l.exports,l,l.exports,n),l.l=!0,l.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var l in e)n.d(r,l,function(t){return e[t]}.bind(null,l));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){"use strict";e.exports=n(3)},function(e,t,n){"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/var r=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(e){r[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,o,u=a(e),c=1;ce.length)&&(t=e.length);for(var n=0,r=new Array(t);nO.length&&O.push(e)}function I(e,t,n){return null==e?0:function e(t,n,r,l){var o=typeof t;"undefined"!==o&&"boolean"!==o||(t=null);var u=!1;if(null===t)u=!0;else switch(o){case"string":case"number":u=!0;break;case"object":switch(t.$$typeof){case i:case a:u=!0}}if(u)return r(l,t,""===n?"."+M(t,0):n),1;if(u=0,n=""===n?".":n+":",Array.isArray(t))for(var c=0;c