From 7d74060caf3221dee8594845b8431dea4c2abf7a Mon Sep 17 00:00:00 2001 From: Anton Shchekota Date: Wed, 24 Jan 2018 13:45:32 +0300 Subject: [PATCH] Eslint add new rules - no-var and prefer-const --- .eslintrc | 2 + __tests__/bin-readme.js | 30 +++++----- __tests__/bin-watch-serve.js | 46 +++++++------- __tests__/bin.js | 51 ++++++++++------ __tests__/format_type.js | 12 ++-- __tests__/index.js | 20 +++---- __tests__/lib/filter_access.js | 2 +- __tests__/lib/flow_doctrine.js | 10 ++-- __tests__/lib/git/find_git.js | 8 +-- __tests__/lib/git/url_prefix.js | 10 ++-- __tests__/lib/github.js | 31 +++++----- __tests__/lib/hierarchy.js | 22 +++---- __tests__/lib/infer/access.js | 6 +- __tests__/lib/infer/augments.js | 4 +- __tests__/lib/infer/finders.js | 10 ++-- __tests__/lib/infer/kind.js | 6 +- __tests__/lib/infer/membership.js | 56 ++++++++--------- __tests__/lib/infer/name.js | 8 +-- __tests__/lib/infer/params.js | 14 ++--- __tests__/lib/infer/properties.js | 4 +- __tests__/lib/infer/return.js | 4 +- __tests__/lib/infer/type.js | 6 +- __tests__/lib/input/dependency.js | 22 +++---- __tests__/lib/input/shallow.js | 5 +- __tests__/lib/lint.js | 28 ++++----- __tests__/lib/merge_config.js | 10 ++-- __tests__/lib/module_filters.js | 2 +- __tests__/lib/nest.js | 23 ++++--- __tests__/lib/output/util/formatters.js | 2 +- __tests__/lib/parse.js | 46 +++++++------- __tests__/lib/parsers/javascript.js | 4 +- __tests__/lib/server.js | 20 +++---- __tests__/lib/sort.js | 66 ++++++++++---------- __tests__/lib/walk.js | 6 +- __tests__/linker.js | 6 +- __tests__/test.js | 77 ++++++++++++------------ __tests__/utils.js | 17 +++--- bin/documentation.js | 6 +- src/commands/build.js | 18 +++--- src/commands/lint.js | 6 +- src/commands/readme.js | 20 +++---- src/commands/serve.js | 22 +++---- src/extractors/comments.js | 4 +- src/extractors/exported.js | 80 ++++++++++++------------- src/filter_access.js | 2 +- src/flow_doctrine.js | 8 +-- src/git/find_git.js | 12 ++-- src/git/url_prefix.js | 20 +++---- src/github.js | 17 +++--- src/hierarchy.js | 53 ++++++++-------- src/index.js | 76 +++++++++++------------ src/infer/access.js | 2 +- src/infer/augments.js | 4 +- src/infer/finders.js | 2 +- src/infer/kind.js | 2 +- src/infer/membership.js | 49 ++++++++------- src/infer/name.js | 5 +- src/infer/params.js | 24 ++++---- src/infer/properties.js | 12 ++-- src/infer/return.js | 12 ++-- src/infer/type.js | 14 ++--- src/inline_tokenizer.js | 12 ++-- src/input/dependency.js | 14 ++--- src/input/shallow.js | 8 +-- src/is_jsdoc_comment.js | 2 +- src/lint.js | 8 +-- src/merge_config.js | 48 ++++++++------- src/module_filters.js | 14 ++--- src/nest.js | 10 ++-- src/output/highlighter.js | 4 +- src/output/html.js | 6 +- src/output/markdown.js | 4 +- src/output/markdown_ast.js | 51 ++++++++-------- src/output/util/format_type.js | 12 ++-- src/output/util/formatters.js | 24 ++++---- src/output/util/linker_stack.js | 8 +-- src/output/util/reroute_links.js | 2 +- src/parse.js | 22 +++---- src/parse_markdown.js | 8 ++- src/parsers/javascript.js | 28 ++++----- src/parsers/parse_to_ast.js | 4 +- src/serve/error_page.js | 8 +-- src/serve/server.js | 20 +++---- src/smart_glob.js | 32 +++++----- src/sort.js | 10 ++-- src/walk.js | 2 +- 86 files changed, 784 insertions(+), 743 deletions(-) diff --git a/.eslintrc b/.eslintrc index 9eff1ecc7..163f9cb2b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -8,6 +8,8 @@ "flowtype" ], "rules": { + "no-var": 2, + "prefer-const": 2, "no-use-before-define": [2, "nofunc"], "camelcase": 2, "no-lonely-if": 2, diff --git a/__tests__/bin-readme.js b/__tests__/bin-readme.js index 052f4e393..19c26cde1 100644 --- a/__tests__/bin-readme.js +++ b/__tests__/bin-readme.js @@ -1,8 +1,8 @@ -var path = require('path'), - os = require('os'), - exec = require('child_process').exec, - tmp = require('tmp'), - fs = require('fs-extra'); +const path = require('path'); +const os = require('os'); +const exec = require('child_process').exec; +const tmp = require('tmp'); +const fs = require('fs-extra'); function documentation(args, options, parseJSON) { return new Promise((resolve, reject) => { @@ -23,13 +23,13 @@ function documentation(args, options, parseJSON) { } describe('readme command', function() { - var fixtures = path.join(__dirname, 'fixture/readme'); - var sourceFile = path.join(fixtures, 'index.js'); - var d; - var removeCallback; + const fixtures = path.join(__dirname, 'fixture/readme'); + const sourceFile = path.join(fixtures, 'index.js'); + let d; + let removeCallback; beforeEach(() => { - var dirEntry = tmp.dirSync({ unsafeCleanup: true }); + const dirEntry = tmp.dirSync({ unsafeCleanup: true }); d = dirEntry.name; fs.copySync( path.join(fixtures, 'README.input.md'), @@ -41,13 +41,13 @@ describe('readme command', function() { // run tests after setting up temp dir test('--diff-only: changes needed', async function() { - var before = fs.readFileSync(path.join(d, 'README.md'), 'utf-8'); + const before = fs.readFileSync(path.join(d, 'README.md'), 'utf-8'); try { await documentation(['readme index.js --diff-only -s API'], { cwd: d }); } catch (err) { - var after = fs.readFileSync(path.join(d, 'README.md'), 'utf-8'); + const after = fs.readFileSync(path.join(d, 'README.md'), 'utf-8'); expect(err).toBeTruthy(); expect(err.code).not.toBe(0); expect(after).toEqual(before); @@ -56,7 +56,7 @@ describe('readme command', function() { test('updates README.md', async function() { await documentation(['readme index.js -s API'], { cwd: d }); - var outputPath = path.join(d, 'README.md'); + const outputPath = path.join(d, 'README.md'); expect(fs.readFileSync(outputPath, 'utf-8')).toMatchSnapshot(); }); @@ -68,7 +68,7 @@ describe('readme command', function() { await documentation(['readme index.js -s API --readme-file other.md'], { cwd: d }); - var actual = fs.readFileSync(path.join(d, 'other.md'), 'utf8'); + const actual = fs.readFileSync(path.join(d, 'other.md'), 'utf8'); expect(actual).toMatchSnapshot(); }); @@ -110,7 +110,7 @@ describe('readme command', function() { } }); - var badFixturePath = path.join(__dirname, 'fixture/bad/syntax.input'); + const badFixturePath = path.join(__dirname, 'fixture/bad/syntax.input'); test('errors on invalid syntax', async function() { try { await documentation( diff --git a/__tests__/bin-watch-serve.js b/__tests__/bin-watch-serve.js index 33c2e401f..ff72f620c 100644 --- a/__tests__/bin-watch-serve.js +++ b/__tests__/bin-watch-serve.js @@ -1,9 +1,9 @@ -var path = require('path'); -var os = require('os'); -var get = require('./utils').get; -var spawn = require('child_process').spawn; -var fs = require('fs'); -var pEvent = require('p-event'); +const path = require('path'); +const os = require('os'); +const get = require('./utils').get; +const spawn = require('child_process').spawn; +const fs = require('fs'); +const pEvent = require('p-event'); function documentation(args, options) { if (!options) { @@ -29,7 +29,7 @@ function normalize(result) { const timeout = 20000; test('harness', function() { - var docProcess = documentation(['serve', 'fixture/simple.input.js']); + const docProcess = documentation(['serve', 'fixture/simple.input.js']); expect(docProcess).toBeTruthy(); docProcess.kill(); }); @@ -37,9 +37,9 @@ test('harness', function() { test( 'provides index.html', function() { - var docProcess = documentation(['serve', 'fixture/simple.input.js']); + const docProcess = documentation(['serve', 'fixture/simple.input.js']); return pEvent(docProcess.stdout, 'data').then(function(data) { - var portNumber = data + const portNumber = data .toString() .match(/documentation.js serving on port (\d+)/); expect(portNumber).toBeTruthy(); @@ -55,13 +55,13 @@ test( test( 'accepts port argument', function() { - var docProcess = documentation([ + const docProcess = documentation([ 'serve', 'fixture/simple.input.js', '--port=4004' ]); return pEvent(docProcess.stdout, 'data').then(function(data) { - var portNumber = data + const portNumber = data .toString() .match(/documentation.js serving on port (\d+)/); expect(portNumber).toBeTruthy(); @@ -77,11 +77,11 @@ test( test( '--watch', function(done) { - var tmpFile = path.join(os.tmpdir(), '/simple.js'); + const tmpFile = path.join(os.tmpdir(), '/simple.js'); fs.writeFileSync(tmpFile, '/** a function */function apples() {}'); - var docProcess = documentation(['serve', tmpFile, '--watch']); + const docProcess = documentation(['serve', tmpFile, '--watch']); pEvent(docProcess.stdout, 'data').then(function(data) { - var portNumber = data + const portNumber = data .toString() .match(/documentation.js serving on port (\d+)/); expect(portNumber).toBeTruthy(); @@ -108,14 +108,14 @@ test( test( '--watch', function(done) { - var tmpDir = os.tmpdir(); - var a = path.join(tmpDir, '/simple.js'); - var b = path.join(tmpDir, '/required.js'); + const tmpDir = os.tmpdir(); + const a = path.join(tmpDir, '/simple.js'); + const b = path.join(tmpDir, '/required.js'); fs.writeFileSync(a, 'require("./required")'); fs.writeFileSync(b, '/** soup */function soup() {}'); - var docProcess = documentation(['serve', a, '--watch']); + const docProcess = documentation(['serve', a, '--watch']); docProcess.stdout.once('data', function(data) { - var portNumber = data + const portNumber = data .toString() .match(/documentation.js serving on port (\d+)/); expect(portNumber).toBeTruthy(); @@ -142,12 +142,12 @@ test( test( 'error page', function() { - var tmpDir = os.tmpdir(); - var a = path.join(tmpDir, '/simple.js'); + const tmpDir = os.tmpdir(); + const a = path.join(tmpDir, '/simple.js'); fs.writeFileSync(a, '**'); - var docProcess = documentation(['serve', a, '--watch']); + const docProcess = documentation(['serve', a, '--watch']); return pEvent(docProcess.stdout, 'data').then(function(data) { - var portNumber = data + const portNumber = data .toString() .match(/documentation.js serving on port (\d+)/); expect(portNumber).toBeTruthy(); diff --git a/__tests__/bin.js b/__tests__/bin.js index 277365442..fca6d019e 100644 --- a/__tests__/bin.js +++ b/__tests__/bin.js @@ -1,10 +1,10 @@ /* global jasmine */ -var path = require('path'), - os = require('os'), - exec = require('child_process').exec, - tmp = require('tmp'), - fs = require('fs-extra'); +const path = require('path'); +const os = require('os'); +const exec = require('child_process').exec; +const tmp = require('tmp'); +const fs = require('fs-extra'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; @@ -160,9 +160,9 @@ describe('invalid arguments', function() { }); test('--config', async function() { - var dst = path.join(os.tmpdir(), (Date.now() + Math.random()).toString()); + const dst = path.join(os.tmpdir(), (Date.now() + Math.random()).toString()); fs.mkdirSync(dst); - var outputIndex = path.join(dst, 'index.html'); + const outputIndex = path.join(dst, 'index.html'); const data = await documentation( [ 'build -c fixture/html/documentation.yml -f html fixture/html/nested.input.js -o ' + @@ -171,7 +171,7 @@ test('--config', async function() { {}, false ); - var output = fs.readFileSync(outputIndex, 'utf8'); + const output = fs.readFileSync(outputIndex, 'utf8'); expect(output).toMatchSnapshot(); }); @@ -185,7 +185,11 @@ describe('lint command', function() { try { await documentation(['lint fixture/lint/lint.input.js'], {}, false); } catch (err) { - var data = err.stderr.toString().split('\n').slice(2).join('\n'); + const data = err.stderr + .toString() + .split('\n') + .slice(2) + .join('\n'); expect(data).toMatchSnapshot(); } }); @@ -284,7 +288,7 @@ test('--infer-private flag', async function() { }); test('write to file', async function() { - var dst = path.join(os.tmpdir(), (Date.now() + Math.random()).toString()); + const dst = path.join(os.tmpdir(), (Date.now() + Math.random()).toString()); const data = await documentation( ['build --shallow fixture/internal.input.js -o ' + dst], @@ -296,7 +300,10 @@ test('write to file', async function() { }); test('write to html', async function() { - var dstDir = path.join(os.tmpdir(), (Date.now() + Math.random()).toString()); + const dstDir = path.join( + os.tmpdir(), + (Date.now() + Math.random()).toString() + ); fs.mkdirSync(dstDir); const data = await documentation( @@ -309,7 +316,10 @@ test('write to html', async function() { }); test('write to html with custom theme', async function() { - var dstDir = path.join(os.tmpdir(), (Date.now() + Math.random()).toString()); + const dstDir = path.join( + os.tmpdir(), + (Date.now() + Math.random()).toString() + ); fs.mkdirSync(dstDir); const data = await documentation( @@ -325,9 +335,12 @@ test('write to html with custom theme', async function() { }); test('write to html, highlightAuto', function() { - var fixture = 'fixture/auto_lang_hljs/multilanguage.input.js', - config = 'fixture/auto_lang_hljs/config.yml', - dstDir = path.join(os.tmpdir(), (Date.now() + Math.random()).toString()); + const fixture = 'fixture/auto_lang_hljs/multilanguage.input.js'; + const config = 'fixture/auto_lang_hljs/config.yml'; + const dstDir = path.join( + os.tmpdir(), + (Date.now() + Math.random()).toString() + ); fs.mkdirSync(dstDir); @@ -336,7 +349,7 @@ test('write to html, highlightAuto', function() { {}, false ).then(() => { - var result = fs.readFileSync(path.join(dstDir, 'index.html'), 'utf8'); + const result = fs.readFileSync(path.join(dstDir, 'index.html'), 'utf8'); expect( result.indexOf('42') > 0 ).toBeTruthy(); @@ -371,10 +384,10 @@ test('build --document-exported', async function() { }); test('build large file without error (no deoptimized styling error)', function() { - var dstFile = + const dstFile = path.join(os.tmpdir(), (Date.now() + Math.random()).toString()) + '.js'; - var contents = ''; - for (var i = 0; i < 4e4; i++) { + let contents = ''; + for (let i = 0; i < 4e4; i++) { contents += '/* - */\n'; } fs.writeFileSync(dstFile, contents, 'utf8'); diff --git a/__tests__/format_type.js b/__tests__/format_type.js index bf6091bbb..0f09b69ec 100644 --- a/__tests__/format_type.js +++ b/__tests__/format_type.js @@ -1,9 +1,9 @@ /*eslint max-len: 0 */ -var _formatType = require('../src/output/util/format_type'), - LinkerStack = require('../src/output/util/linker_stack'), - remark = require('remark'), - parse = require('doctrine-temporary-fork').parse; +const _formatType = require('../src/output/util/format_type'); +const LinkerStack = require('../src/output/util/linker_stack'); +const remark = require('remark'); +const parse = require('doctrine-temporary-fork').parse; function stringify(children) { return remark().stringify({ @@ -13,8 +13,8 @@ function stringify(children) { } test('formatType', function() { - var linkerStack = new LinkerStack({}); - var formatType = _formatType.bind(undefined, linkerStack.link); + const linkerStack = new LinkerStack({}); + const formatType = _formatType.bind(undefined, linkerStack.link); [ ['Foo', 'Foo'], ['null', 'null'], diff --git a/__tests__/index.js b/__tests__/index.js index ceeb374c4..ed945e56e 100644 --- a/__tests__/index.js +++ b/__tests__/index.js @@ -1,12 +1,12 @@ -var documentation = require('../src/'); -var os = require('os'); -var path = require('path'); -var fs = require('fs'); +const documentation = require('../src/'); +const os = require('os'); +const path = require('path'); +const fs = require('fs'); function inputs(contents) { - var dirEntry = os.tmpdir(); - var paths = {}; - for (var filename in contents) { + const dirEntry = os.tmpdir(); + const paths = {}; + for (const filename in contents) { paths[filename] = path.join(dirEntry, '/', filename); fs.writeFileSync(paths[filename], contents[filename]); } @@ -22,7 +22,7 @@ function cleanup(comments) { } test('lint', async function() { - var { paths } = inputs({ + const { paths } = inputs({ 'index.js': '/** hi */var name = 1;' }); @@ -31,7 +31,7 @@ test('lint', async function() { }); test('build', async function() { - var { paths } = inputs({ + const { paths } = inputs({ 'index.js': '/** hi */var name = 1;' }); @@ -47,7 +47,7 @@ test('build', async function() { }); test('expandInputs', async function() { - var { paths } = inputs({ + const { paths } = inputs({ 'index.js': '/** hi */var name = 1;' }); diff --git a/__tests__/lib/filter_access.js b/__tests__/lib/filter_access.js index 85ab0bea8..06176343d 100644 --- a/__tests__/lib/filter_access.js +++ b/__tests__/lib/filter_access.js @@ -1,4 +1,4 @@ -var filterAccess = require('../../src/filter_access'); +const filterAccess = require('../../src/filter_access'); test('filterAccess ignore', function() { expect( diff --git a/__tests__/lib/flow_doctrine.js b/__tests__/lib/flow_doctrine.js index 871acbd31..aa65d62c7 100644 --- a/__tests__/lib/flow_doctrine.js +++ b/__tests__/lib/flow_doctrine.js @@ -1,6 +1,6 @@ -var flowDoctrine = require('../../src/flow_doctrine.js'), - parse = require('../../src/parsers/javascript'), - FLOW_TYPES = require('babel-types').FLOW_TYPES; +const flowDoctrine = require('../../src/flow_doctrine.js'); +const parse = require('../../src/parsers/javascript'); +const FLOW_TYPES = require('babel-types').FLOW_TYPES; function toComment(fn, filename) { return parse( @@ -13,12 +13,12 @@ function toComment(fn, filename) { } test('flowDoctrine', function() { - var types = FLOW_TYPES.filter(function(type) { + const types = FLOW_TYPES.filter(function(type) { return type.match(/\wTypeAnnotation$/); }); function toDoctrineType(flowType) { - var annotation = toComment( + const annotation = toComment( '/** add */function add(a: ' + flowType + ' ) { }' ).context.ast.node.params[0].typeAnnotation.typeAnnotation; if (types.indexOf(annotation.type) !== -1) { diff --git a/__tests__/lib/git/find_git.js b/__tests__/lib/git/find_git.js index aed510251..8619ac986 100644 --- a/__tests__/lib/git/find_git.js +++ b/__tests__/lib/git/find_git.js @@ -1,7 +1,7 @@ -var mock = require('mock-fs'); -var mockRepo = require('../../utils').mockRepo; -var path = require('path'); -var findGit = require('../../../src/git/find_git'); +const mock = require('mock-fs'); +const mockRepo = require('../../utils').mockRepo; +const path = require('path'); +const findGit = require('../../../src/git/find_git'); test('findGit', function() { mock(mockRepo.master); diff --git a/__tests__/lib/git/url_prefix.js b/__tests__/lib/git/url_prefix.js index 3c1ace557..0a917352f 100644 --- a/__tests__/lib/git/url_prefix.js +++ b/__tests__/lib/git/url_prefix.js @@ -1,7 +1,7 @@ -var mock = require('mock-fs'); -var mockRepo = require('../../utils').mockRepo; -var getGithubURLPrefix = require('../../../src/git/url_prefix'); -var parsePackedRefs = getGithubURLPrefix.parsePackedRefs; +const mock = require('mock-fs'); +const mockRepo = require('../../utils').mockRepo; +const getGithubURLPrefix = require('../../../src/git/url_prefix'); +const parsePackedRefs = getGithubURLPrefix.parsePackedRefs; test('getGithubURLPrefix', function() { mock(mockRepo.master); @@ -22,7 +22,7 @@ test('getGithubURLPrefix', function() { }); test('parsePackedRefs', function() { - var input = + const input = '# pack-refs with: peeled fully-peeled\n' + '4acd658617928bd17ae7364ef2512630d97c007a refs/heads/babel-6\n' + '11826ad98c6c08d00f4af77f64d3e2687e0f7dba refs/remotes/origin/flow-types'; diff --git a/__tests__/lib/github.js b/__tests__/lib/github.js index 76e7d7a67..ce15eccde 100644 --- a/__tests__/lib/github.js +++ b/__tests__/lib/github.js @@ -1,10 +1,10 @@ /* eslint no-unused-vars: 0 */ -var mock = require('mock-fs'), - path = require('path'), - mockRepo = require('../utils').mockRepo, - parse = require('../../src/parsers/javascript'), - github = require('../../src/github'); +const mock = require('mock-fs'); +const path = require('path'); +const mockRepo = require('../utils').mockRepo; +const parse = require('../../src/parsers/javascript'); +const github = require('../../src/github'); function toComment(fn, filename) { return parse( @@ -31,9 +31,9 @@ test('github', function() { expect( evaluate(function() { /** - * get one - * @returns {number} one - */ + * get one + * @returns {number} one + */ function getOne() { return 1; } @@ -52,9 +52,9 @@ test('malformed repository', function() { expect( evaluate(function() { /** - * get one - * @returns {number} one - */ + * get one + * @returns {number} one + */ function getOne() { return 1; } @@ -70,16 +70,17 @@ test('enterprise repository', function() { expect( evaluate(function() { /** - * get one - * @returns {number} one - */ + * get one + * @returns {number} one + */ function getOne() { return 1; } })[0].context.github ).toEqual({ path: 'index.js', - url: 'https://github.enterprise.com/foo/bar/blob/this_is_the_sha/index.js#L6-L8' + url: + 'https://github.enterprise.com/foo/bar/blob/this_is_the_sha/index.js#L6-L8' }); mock.restore(); diff --git a/__tests__/lib/hierarchy.js b/__tests__/lib/hierarchy.js index a30e7e3f8..de763e929 100644 --- a/__tests__/lib/hierarchy.js +++ b/__tests__/lib/hierarchy.js @@ -1,5 +1,5 @@ -var parse = require('../../src/parsers/javascript'), - hierarchy = require('../../src/hierarchy'); +const parse = require('../../src/parsers/javascript'); +const hierarchy = require('../../src/hierarchy'); function toComments(fn, filename) { return parse( @@ -22,7 +22,7 @@ function map(arr, prop) { } test('hierarchy', function() { - var comments = evaluate(function() { + const comments = evaluate(function() { /** * @name Class * @class @@ -50,7 +50,7 @@ test('hierarchy', function() { expect(map(comments, 'name')).toEqual(['Class']); - var classMembers = comments[0].members; + const classMembers = comments[0].members; expect(map(classMembers.static, 'name')).toEqual(['isClass', 'MAGIC_NUMBER']); expect(map(classMembers.instance, 'name')).toEqual(['getFoo']); @@ -67,7 +67,7 @@ test('hierarchy', function() { }); test('hierarchy - nesting', function() { - var comments = evaluate(function() { + const comments = evaluate(function() { /** * @name Parent * @class @@ -88,10 +88,10 @@ test('hierarchy - nesting', function() { expect(map(comments, 'name')).toEqual(['Parent']); - var classMembers = comments[0].members; + const classMembers = comments[0].members; expect(map(classMembers.static, 'name')).toEqual(['enum']); - var enumMembers = classMembers.static[0].members; + const enumMembers = classMembers.static[0].members; expect(map(enumMembers.static, 'name')).toEqual(['Parent', 'Child']); expect(map(enumMembers.static[0].path, 'name')).toEqual([ 'Parent', @@ -106,7 +106,7 @@ test('hierarchy - nesting', function() { }); test('hierarchy - multisignature', function() { - var comments = evaluate(function() { + const comments = evaluate(function() { /** * @name Parent * @class @@ -127,7 +127,7 @@ test('hierarchy - multisignature', function() { }); test('hierarchy - missing memberof', function() { - var test = evaluate(function() { + const test = evaluate(function() { /** * @name test * @memberof DoesNotExist @@ -143,7 +143,7 @@ test('hierarchy - missing memberof', function() { }); test('hierarchy - anonymous', function() { - var result = evaluate(function() { + const result = evaluate(function() { /** Test */ })[0]; @@ -155,7 +155,7 @@ test('hierarchy - anonymous', function() { }); test('hierarchy - object prototype member names', function() { - var comments = evaluate(function() { + const comments = evaluate(function() { /** * @name should * @function diff --git a/__tests__/lib/infer/access.js b/__tests__/lib/infer/access.js index 59d3bbf64..200d52b4d 100644 --- a/__tests__/lib/infer/access.js +++ b/__tests__/lib/infer/access.js @@ -1,6 +1,6 @@ -var parse = require('../../../src/parsers/javascript'), - inferName = require('../../../src/infer/name'), - inferAccess = require('../../../src/infer/access'); +const parse = require('../../../src/parsers/javascript'); +const inferName = require('../../../src/infer/name'); +const inferAccess = require('../../../src/infer/access'); function toComment(fn) { return parse( diff --git a/__tests__/lib/infer/augments.js b/__tests__/lib/infer/augments.js index 38801d81d..f409d27e1 100644 --- a/__tests__/lib/infer/augments.js +++ b/__tests__/lib/infer/augments.js @@ -1,6 +1,6 @@ /*eslint-disable no-unused-vars*/ -var inferAugments = require('../../../src/infer/augments'), - parse = require('../../../src/parsers/javascript'); +const inferAugments = require('../../../src/infer/augments'); +const parse = require('../../../src/parsers/javascript'); function toComment(fn, filename) { return parse( diff --git a/__tests__/lib/infer/finders.js b/__tests__/lib/infer/finders.js index 3c86b0473..a421893fd 100644 --- a/__tests__/lib/infer/finders.js +++ b/__tests__/lib/infer/finders.js @@ -1,5 +1,5 @@ -var parse = require('../../../src/parsers/javascript'), - findTarget = require('../../../src/infer/finders').findTarget; +const parse = require('../../../src/parsers/javascript'); +const findTarget = require('../../../src/infer/finders').findTarget; function toComment(fn) { if (typeof fn == 'function') { @@ -23,7 +23,7 @@ test('findTarget', function() { findTarget( toComment(function() { /** Test */ - var x = 10; + const x = 10; }).context.ast ).type ).toBe('VariableDeclarator'); @@ -31,7 +31,7 @@ test('findTarget', function() { expect( findTarget( toComment(function() { - var z = {}; + const z = {}; /** Test */ z.y = 10; @@ -42,7 +42,7 @@ test('findTarget', function() { expect( findTarget( toComment(function() { - var z = { + const z = { /** Test */ y: 10 }; diff --git a/__tests__/lib/infer/kind.js b/__tests__/lib/infer/kind.js index 3c015b94c..da7707dce 100644 --- a/__tests__/lib/infer/kind.js +++ b/__tests__/lib/infer/kind.js @@ -1,6 +1,6 @@ /*eslint-disable no-unused-vars*/ -var inferKind = require('../../../src/infer/kind'), - parse = require('../../../src/parsers/javascript'); +const inferKind = require('../../../src/infer/kind'); +const parse = require('../../../src/parsers/javascript'); function toComment(fn, filename) { return parse( @@ -52,7 +52,7 @@ test('inferKind', function() { inferKind( toComment(function() { /** function */ - var foo = function() {}; + const foo = function() {}; foo(); }) ).kind diff --git a/__tests__/lib/infer/membership.js b/__tests__/lib/infer/membership.js index 20bf78d60..22849a0a4 100644 --- a/__tests__/lib/infer/membership.js +++ b/__tests__/lib/infer/membership.js @@ -1,5 +1,5 @@ -var parse = require('../../../src/parsers/javascript'), - inferMembership = require('../../../src/infer/membership')(); +const parse = require('../../../src/parsers/javascript'); +const inferMembership = require('../../../src/infer/membership')(); function toComment(fn, file) { return parse( @@ -32,10 +32,10 @@ test('inferMembership - explicit', function() { pick( evaluate(function() { /** - * Test - * @memberof Bar - * @static - */ + * Test + * @memberof Bar + * @static + */ Foo.bar = 0; })[0], ['memberof', 'scope'] @@ -49,9 +49,9 @@ test('inferMembership - explicit', function() { pick( evaluate(function() { /** - * Test - * @memberof Bar# - */ + * Test + * @memberof Bar# + */ Foo.bar = 0; })[0], ['memberof', 'scope'] @@ -65,9 +65,9 @@ test('inferMembership - explicit', function() { pick( evaluate(function() { /** - * Test - * @memberof Bar.prototype - */ + * Test + * @memberof Bar.prototype + */ Foo.bar = 0; })[0], ['memberof', 'scope'] @@ -162,8 +162,8 @@ test('inferMembership - explicit', function() { evaluate(function() { Foo.prototype = { /** - * Test - */ + * Test + */ bar: function() {} }; })[0], @@ -179,8 +179,8 @@ test('inferMembership - explicit', function() { evaluate(function() { Foo.prototype = { /** - * Test - */ + * Test + */ bar() {} }; })[0], @@ -194,7 +194,7 @@ test('inferMembership - explicit', function() { expect( pick( evaluate(function() { - var Foo = { + const Foo = { /** Test */ baz: 0 }; @@ -210,7 +210,7 @@ test('inferMembership - explicit', function() { expect( pick( evaluate(function() { - var Foo = { + const Foo = { /** Test */ baz: function() {} }; @@ -243,7 +243,7 @@ test('inferMembership - explicit', function() { expect( pick( evaluate(function() { - var Foo = function Bar() { + const Foo = function Bar() { { /** */ this.baz = 0; @@ -509,9 +509,9 @@ test('inferMembership - module.exports', function() { expect( evaluate(function() { /** - * @module mod - * @name exports - */ + * @module mod + * @name exports + */ module.exports = 1; })[0].memberof ).toBe(undefined); @@ -519,9 +519,9 @@ test('inferMembership - module.exports', function() { expect( evaluate(function() { /** - * @module mod - * @name exports - */ + * @module mod + * @name exports + */ module.exports = function() {}; })[0].memberof ).toBe(undefined); @@ -538,7 +538,7 @@ test('inferMembership - module.exports', function() { }); test('inferMembership - not module exports', function() { - var result = evaluate(function() { + const result = evaluate(function() { /** * @module mod */ @@ -551,7 +551,7 @@ test('inferMembership - not module exports', function() { }); test('inferMembership - anonymous @module', function() { - var result = evaluate(function() { + const result = evaluate(function() { /** * @module */ @@ -564,7 +564,7 @@ test('inferMembership - anonymous @module', function() { }); test('inferMembership - no @module', function() { - var result = evaluate(function() { + const result = evaluate(function() { /** Test */ exports.foo = 1; }, '/path/mod.js'); diff --git a/__tests__/lib/infer/name.js b/__tests__/lib/infer/name.js index 2fe7a3915..0c91f4442 100644 --- a/__tests__/lib/infer/name.js +++ b/__tests__/lib/infer/name.js @@ -1,5 +1,5 @@ -var parse = require('../../../src/parsers/javascript'), - inferName = require('../../../src/infer/name'); +const parse = require('../../../src/parsers/javascript'); +const inferName = require('../../../src/infer/name'); function toComment(fn, file) { return parse( @@ -84,14 +84,14 @@ test('inferName', function() { expect( evaluate(function() { /** Test */ - var name = function() {}; + const name = function() {}; }).name ).toBe('name'); expect( evaluate(function() { /** Test */ - var name = function name2() {}; + const name = function name2() {}; }).name ).toBe('name'); diff --git a/__tests__/lib/infer/params.js b/__tests__/lib/infer/params.js index 2dbf7e61d..8d0e29824 100644 --- a/__tests__/lib/infer/params.js +++ b/__tests__/lib/infer/params.js @@ -1,5 +1,5 @@ -var parse = require('../../../src/parsers/javascript'), - inferParams = require('../../../src/infer/params'); +const parse = require('../../../src/parsers/javascript'); +const inferParams = require('../../../src/infer/params'); function toComment(fn, file) { return parse( @@ -85,7 +85,7 @@ test('inferParams', function() { expect( evaluate(function() { /** Test */ - var f = function(x) {}; + const f = function(x) {}; }).params ).toEqual([{ lineNumber: 3, name: 'x', title: 'param' }]); @@ -115,10 +115,10 @@ test('inferParams', function() { expect( evaluate(function() { - var x = 1, - g = function(y) {}, - /** Test */ - f = function(x) {}; + const x = 1; + const g = function(y) {}; + /** Test */ + const f = function(x) {}; }).params ).toEqual([{ lineNumber: 5, name: 'x', title: 'param' }]); diff --git a/__tests__/lib/infer/properties.js b/__tests__/lib/infer/properties.js index a8a5e0404..0c468767c 100644 --- a/__tests__/lib/infer/properties.js +++ b/__tests__/lib/infer/properties.js @@ -1,6 +1,6 @@ /*eslint-disable no-unused-vars*/ -var inferProperties = require('../../../src/infer/properties'), - parse = require('../../../src/parsers/javascript'); +const inferProperties = require('../../../src/infer/properties'); +const parse = require('../../../src/parsers/javascript'); function toComment(fn, filename) { return parse( diff --git a/__tests__/lib/infer/return.js b/__tests__/lib/infer/return.js index 0f04dd12f..979d640b0 100644 --- a/__tests__/lib/infer/return.js +++ b/__tests__/lib/infer/return.js @@ -1,6 +1,6 @@ /*eslint-disable no-unused-vars*/ -var inferReturn = require('../../../src/infer/return'), - parse = require('../../../src/parsers/javascript'); +const inferReturn = require('../../../src/infer/return'); +const parse = require('../../../src/parsers/javascript'); function toComment(fn, filename) { return parse( diff --git a/__tests__/lib/infer/type.js b/__tests__/lib/infer/type.js index c7da9b312..f95ad8af9 100644 --- a/__tests__/lib/infer/type.js +++ b/__tests__/lib/infer/type.js @@ -1,6 +1,6 @@ -var parse = require('../../../src/parsers/javascript'), - inferKind = require('../../../src/infer/kind'), - inferType = require('../../../src/infer/type'); +const parse = require('../../../src/parsers/javascript'); +const inferKind = require('../../../src/infer/kind'); +const inferType = require('../../../src/infer/type'); function toComment(code) { return parse( diff --git a/__tests__/lib/input/dependency.js b/__tests__/lib/input/dependency.js index 8f32e2737..271caffae 100644 --- a/__tests__/lib/input/dependency.js +++ b/__tests__/lib/input/dependency.js @@ -1,13 +1,13 @@ -var os = require('os'); -var shell = require('shelljs'); -var path = require('path'); -var fs = require('fs'); -var dependency = require('../../../src/input/dependency'); +const os = require('os'); +const shell = require('shelljs'); +const path = require('path'); +const fs = require('fs'); +const dependency = require('../../../src/input/dependency'); function inputs(contents) { - var dirEntry = os.tmpdir(); - var paths = {}; - for (var filename in contents) { + const dirEntry = os.tmpdir(); + const paths = {}; + for (const filename in contents) { paths[filename] = path.join(dirEntry, '/', filename); fs.writeFileSync(paths[filename], contents[filename]); } @@ -17,19 +17,19 @@ function inputs(contents) { } test('dependency', async function() { - let { paths, cleanup } = inputs({ + const { paths, cleanup } = inputs({ 'index.js': 'module.exports = 1;', 'requires.js': "module.exports = require('./foo');", 'foo.js': 'module.exports = 2;' }); { - let dependencies = await dependency([paths['index.js']], { + const dependencies = await dependency([paths['index.js']], { parseExtension: ['js'] }); expect(dependencies.length).toEqual(1); } { - let dependencies = await dependency([paths['requires.js']], { + const dependencies = await dependency([paths['requires.js']], { parseExtension: ['js'] }); expect(dependencies.length).toEqual(2); diff --git a/__tests__/lib/input/shallow.js b/__tests__/lib/input/shallow.js index 9e075b889..430a19b8c 100644 --- a/__tests__/lib/input/shallow.js +++ b/__tests__/lib/input/shallow.js @@ -1,4 +1,5 @@ -var path = require('path'), shallow = require('../../../src/input/shallow'); +const path = require('path'); +const shallow = require('../../../src/input/shallow'); test('shallow deps', async function() { const deps = await shallow( @@ -37,7 +38,7 @@ test('throws on non-string or object input', function() { }); test('shallow deps literal', async function() { - var obj = { + const obj = { file: 'foo.js', source: '//bar' }; diff --git a/__tests__/lib/lint.js b/__tests__/lib/lint.js index 6e06fef30..6ec6bd386 100644 --- a/__tests__/lib/lint.js +++ b/__tests__/lib/lint.js @@ -1,6 +1,6 @@ -var parse = require('../../src/parsers/javascript'), - lintComments = require('../../src/lint').lintComments, - formatLint = require('../../src/lint').formatLint; +const parse = require('../../src/parsers/javascript'); +const lintComments = require('../../src/lint').lintComments; +const formatLint = require('../../src/lint').formatLint; function toComment(fn, filename) { return parse( @@ -20,8 +20,8 @@ test('lintComments', function() { expect( evaluate(function() { /** - * @param {foo - */ + * @param {foo + */ }).errors ).toEqual([ { message: 'Braces are not balanced' }, @@ -31,17 +31,17 @@ test('lintComments', function() { expect( evaluate(function() { /** - * @param {Object} foo.bar - */ + * @param {Object} foo.bar + */ }).errors ).toEqual([{ commentLineNumber: 1, message: 'Parent of foo.bar not found' }]); expect( evaluate(function() { /** - * @param {String} foo - * @param {array} bar - */ + * @param {String} foo + * @param {array} bar + */ }).errors ).toEqual([ { @@ -54,14 +54,14 @@ test('lintComments', function() { expect( evaluate(function() { /** - * @param {string} foo - */ + * @param {string} foo + */ }).errors ).toEqual([]); }); test('formatLint', function() { - var comment = evaluate(function() { + const comment = evaluate(function() { // 2 // 3 /** 4 @@ -71,7 +71,7 @@ test('formatLint', function() { */ }); - var formatted = formatLint([comment]); + const formatted = formatLint([comment]); expect(formatted.match(/input.js/g)); expect(formatted.match(/4:1[^\n]+Braces are not balanced/g)); diff --git a/__tests__/lib/merge_config.js b/__tests__/lib/merge_config.js index 5cc4e49a8..fe0fc8199 100644 --- a/__tests__/lib/merge_config.js +++ b/__tests__/lib/merge_config.js @@ -1,6 +1,6 @@ -var path = require('path'), - _ = require('lodash'), - mergeConfig = require('../../src/merge_config'); +const path = require('path'); +const _ = require('lodash'); +const mergeConfig = require('../../src/merge_config'); test('bad config', async function() { try { @@ -12,7 +12,7 @@ test('bad config', async function() { test('right merging package configuration', async function() { // Omit configuration from output, for simplicity - var nc = _.curryRight(_.omit, 2)([ + const nc = _.curryRight(_.omit, 2)([ 'config', 'no-package', 'parseExtension', @@ -35,7 +35,7 @@ test('right merging package configuration', async function() { test('nc(mergeConfig)', async function() { // Omit configuration from output, for simplicity - var nc = _.curryRight(_.omit, 2)([ + const nc = _.curryRight(_.omit, 2)([ 'config', 'no-package', 'parseExtension', diff --git a/__tests__/lib/module_filters.js b/__tests__/lib/module_filters.js index 82309cf08..cda60c7dc 100644 --- a/__tests__/lib/module_filters.js +++ b/__tests__/lib/module_filters.js @@ -1,4 +1,4 @@ -var moduleFilters = require('../../src/module_filters'); +const moduleFilters = require('../../src/module_filters'); test('moduleFilters.internalOnly', function() { expect(moduleFilters.internalOnly('./foo')).toEqual(true); diff --git a/__tests__/lib/nest.js b/__tests__/lib/nest.js index 40469949f..d73d92815 100644 --- a/__tests__/lib/nest.js +++ b/__tests__/lib/nest.js @@ -1,17 +1,16 @@ -var nestTag = require('../../src/nest').nestTag; +const nestTag = require('../../src/nest').nestTag; // Print a tree of tags in a way that's easy to test. -var printTree = indent => node => - `${new Array(indent + 1).join(' ')}- ${node.name}${node.properties ? '\n' : ''}${(node.properties || [ - ]) - .map(printTree(indent + 1)) - .join('\n')}`; +const printTree = indent => node => + `${new Array(indent + 1).join(' ')}- ${node.name}${ + node.properties ? '\n' : '' + }${(node.properties || []).map(printTree(indent + 1)).join('\n')}`; -var printNesting = params => +const printNesting = params => printTree(0)({ properties: nestTag(params), name: 'root' }); test('nest params - basic', function() { - var params = [ + const params = [ 'foo', 'foo.bar', 'foo.bar.third', @@ -29,7 +28,7 @@ test('nest params - basic', function() { }); test('nest params - multiple roots', function() { - var params = ['a', 'b', 'c'].map(name => ({ name })); + const params = ['a', 'b', 'c'].map(name => ({ name })); expect(printNesting(params)).toBe( `- root - a @@ -39,14 +38,14 @@ test('nest params - multiple roots', function() { }); test('nest params - missing parent', function() { - var params = ['foo', 'foo.bar.third'].map(name => ({ name })); + const params = ['foo', 'foo.bar.third'].map(name => ({ name })); expect(() => { nestTag(params); }).toThrow(); }); test('nest params - #658', function() { - var params = [ + const params = [ 'state', 'payload', 'payload.input_meter_levels', @@ -70,7 +69,7 @@ test('nest params - #658', function() { }); test('nest params - #554', function() { - var params = [ + const params = [ 'x', 'yIn', 'options', diff --git a/__tests__/lib/output/util/formatters.js b/__tests__/lib/output/util/formatters.js index 3861e12c4..e2dd2c1dc 100644 --- a/__tests__/lib/output/util/formatters.js +++ b/__tests__/lib/output/util/formatters.js @@ -1,4 +1,4 @@ -var formatters = require('../../../../src/output/util/formatters')(getHref); +const formatters = require('../../../../src/output/util/formatters')(getHref); test('formatters.parameters -- long form', function() { expect(formatters.parameters({})).toEqual('()'); diff --git a/__tests__/lib/parse.js b/__tests__/lib/parse.js index 06daf5aa0..6853ba364 100644 --- a/__tests__/lib/parse.js +++ b/__tests__/lib/parse.js @@ -1,6 +1,6 @@ -var parse = require('../../src/parsers/javascript'), - remark = require('remark'), - visit = require('unist-util-visit'); +const parse = require('../../src/parsers/javascript'); +const remark = require('remark'); +const visit = require('unist-util-visit'); function pick(obj, props) { if (Array.isArray(props)) { @@ -84,9 +84,9 @@ test('parse - @description', function() { expect( evaluate(function() { /** - * This is a free-form description - * @description This tagged description wins, and [is markdown](http://markdown.com). - */ + * This is a free-form description + * @description This tagged description wins, and [is markdown](http://markdown.com). + */ })[0].description ).toEqual( remark().parse( @@ -322,10 +322,10 @@ test('parse - @example', function() { expect( evaluate(function() { /** - * @example - * a - * b - */ + * @example + * a + * b + */ })[0].examples[0] ).toEqual({ description: 'a\nb' @@ -334,10 +334,10 @@ test('parse - @example', function() { expect( evaluate(function() { /** - * @example caption - * a - * b - */ + * @example caption + * a + * b + */ })[0].examples[0] ).toEqual({ description: 'a\nb', @@ -913,9 +913,9 @@ test('parse - @see', function() { expect( evaluate(function() { /** - * @see a - * @see b - */ + * @see a + * @see b + */ })[0].sees ).toEqual([remark().parse('a'), remark().parse('b')]); }); @@ -975,9 +975,9 @@ test('parse - @throws', function() { expect( evaluate(function() { /** - * @throws a - * @throws b - */ + * @throws a + * @throws b + */ })[0].throws ).toEqual([ { @@ -999,9 +999,9 @@ test('parse - @todo', function() { expect( evaluate(function() { /** - * @todo a - * @todo b - */ + * @todo a + * @todo b + */ })[0].todos ).toEqual([remark().parse('a'), remark().parse('b')]); }); diff --git a/__tests__/lib/parsers/javascript.js b/__tests__/lib/parsers/javascript.js index cf5b114fa..1f92d4c62 100644 --- a/__tests__/lib/parsers/javascript.js +++ b/__tests__/lib/parsers/javascript.js @@ -1,5 +1,5 @@ -var remark = require('remark'), - parse = require('../../../src/parsers/javascript'); +const remark = require('remark'); +const parse = require('../../../src/parsers/javascript'); function toComments(source, filename, opts) { source = typeof source === 'string' ? source : '(' + source.toString() + ')'; diff --git a/__tests__/lib/server.js b/__tests__/lib/server.js index 8ad9fa332..6b5187d94 100644 --- a/__tests__/lib/server.js +++ b/__tests__/lib/server.js @@ -1,23 +1,23 @@ -var get = require('../utils').get; -var File = require('vinyl'); -var getPort = require('get-port'); -var Server = require('../../src/serve/server'); +const get = require('../utils').get; +const File = require('vinyl'); +const getPort = require('get-port'); +const Server = require('../../src/serve/server'); -var jsFile = new File({ +const jsFile = new File({ cwd: '/', base: '/test/', path: '/test/file.js', contents: new Buffer('var test = 123;') }); -var coffeeFile = new File({ +const coffeeFile = new File({ cwd: '/', base: '/test/', path: '/test/file.coffee', contents: new Buffer('test = 123') }); -var indexFile = new File({ +const indexFile = new File({ cwd: '/', base: '/test/', path: '/test/index.html', @@ -26,10 +26,10 @@ var indexFile = new File({ test('server - throws on bad port', function() { expect(function() { - var server = new Server('${port}'); + const server = new Server('${port}'); }).toThrow(); expect(function() { - var server = new Server(); + const server = new Server(); }).toThrow(); }); @@ -45,7 +45,7 @@ test('server', async function() { } server.setFiles([coffeeFile]); - var text; + let text; text = await get(`http://localhost:${port}/file.coffee`); expect(text).toMatchSnapshot(); diff --git a/__tests__/lib/sort.js b/__tests__/lib/sort.js index 099b671ea..015a0d43f 100644 --- a/__tests__/lib/sort.js +++ b/__tests__/lib/sort.js @@ -1,10 +1,10 @@ -var sort = require('../../src/sort'), - path = require('path'); +const sort = require('../../src/sort'); +const path = require('path'); test('sort stream alphanumeric', function() { - var apples = { context: { sortKey: 'a' }, name: 'apples' }; - var carrot = { context: { sortKey: 'b' }, name: 'carrot' }; - var banana = { context: { sortKey: 'c' }, name: 'bananas' }; + const apples = { context: { sortKey: 'a' }, name: 'apples' }; + const carrot = { context: { sortKey: 'b' }, name: 'carrot' }; + const banana = { context: { sortKey: 'c' }, name: 'bananas' }; expect(sort([apples, carrot, banana])).toEqual([apples, carrot, banana]); @@ -12,9 +12,9 @@ test('sort stream alphanumeric', function() { }); test('sort stream with configuration', function() { - var apples = { context: { sortKey: 'a' }, name: 'apples' }; - var carrot = { context: { sortKey: 'b' }, name: 'carrot' }; - var bananas = { context: { sortKey: 'c' }, name: 'bananas' }; + const apples = { context: { sortKey: 'a' }, name: 'apples' }; + const carrot = { context: { sortKey: 'b' }, name: 'carrot' }; + const bananas = { context: { sortKey: 'c' }, name: 'bananas' }; expect( sort([apples, carrot, bananas], { @@ -24,16 +24,16 @@ test('sort stream with configuration', function() { }); test('sort stream with configuration and a section', function() { - var apples = { context: { sortKey: 'a' }, name: 'apples' }; - var carrot = { context: { sortKey: 'b' }, name: 'carrot' }; - var bananas = { context: { sortKey: 'c' }, name: 'bananas' }; + const apples = { context: { sortKey: 'a' }, name: 'apples' }; + const carrot = { context: { sortKey: 'b' }, name: 'carrot' }; + const bananas = { context: { sortKey: 'c' }, name: 'bananas' }; - var section = { + const section = { name: 'This is the banana type', description: 'here lies bananas' }; - var sectionMarkdown = { + const sectionMarkdown = { name: 'This is the banana type', description: { type: 'root', @@ -105,15 +105,15 @@ test('sort stream with configuration and a section', function() { test('sort an already-sorted stream containing a section/description', function() { // this happens in the 'serve' task - var apples = { context: { sortKey: 'a' }, name: 'apples' }; - var carrot = { context: { sortKey: 'b' }, name: 'carrot' }; - var bananas = { context: { sortKey: 'c' }, name: 'bananas' }; + const apples = { context: { sortKey: 'a' }, name: 'apples' }; + const carrot = { context: { sortKey: 'b' }, name: 'carrot' }; + const bananas = { context: { sortKey: 'c' }, name: 'bananas' }; - var section = { + const section = { name: 'This is the banana type', description: 'here lies bananas' }; - var sectionMarkdown = { + const sectionMarkdown = { name: 'This is the banana type', description: { type: 'root', @@ -176,21 +176,21 @@ test('sort an already-sorted stream containing a section/description', function( ] }; - var config = { + const config = { toc: ['carrot', section, 'bananas'] }; - var sortOnce = sort([apples, carrot, bananas], config); - var sortTwice = sort(sortOnce, config); + const sortOnce = sort([apples, carrot, bananas], config); + const sortTwice = sort(sortOnce, config); expect(sortTwice).toEqual([carrot, sectionMarkdown, bananas, apples]); }); test('sort toc with files', function() { - var apples = { context: { sortKey: 'a' }, name: 'apples' }; - var carrot = { context: { sortKey: 'b' }, name: 'carrot' }; - var bananas = { context: { sortKey: 'c' }, name: 'bananas' }; + const apples = { context: { sortKey: 'a' }, name: 'apples' }; + const carrot = { context: { sortKey: 'b' }, name: 'carrot' }; + const bananas = { context: { sortKey: 'c' }, name: 'bananas' }; - var snowflake = { + const snowflake = { name: 'snowflake', file: path.join(__dirname, '../fixture/snowflake.md') }; @@ -203,11 +203,11 @@ test('sort toc with files', function() { }); test('sort toc with files absolute path', function() { - var apples = { context: { sortKey: 'a' }, name: 'apples' }; - var carrot = { context: { sortKey: 'b' }, name: 'carrot' }; - var bananas = { context: { sortKey: 'c' }, name: 'bananas' }; + const apples = { context: { sortKey: 'a' }, name: 'apples' }; + const carrot = { context: { sortKey: 'b' }, name: 'carrot' }; + const bananas = { context: { sortKey: 'c' }, name: 'bananas' }; - var snowflake = { + const snowflake = { name: 'snowflake', file: path.join(__dirname, '../fixture/snowflake.md') }; @@ -219,23 +219,23 @@ test('sort toc with files absolute path', function() { }); test('sort toc with files absolute path', function() { - var apples = { + const apples = { context: { sortKey: 'a' }, name: 'apples', memberof: 'classB' }; - var carrot = { + const carrot = { context: { sortKey: 'b' }, name: 'carrot', memberof: 'classB' }; - var bananas = { + const bananas = { context: { sortKey: 'c' }, name: 'bananas', memberof: 'classB' }; - var snowflake = { + const snowflake = { name: 'snowflake', file: path.join(__dirname, '../fixture/snowflake.md') }; diff --git a/__tests__/lib/walk.js b/__tests__/lib/walk.js index bc0f81b7f..2fa1702cd 100644 --- a/__tests__/lib/walk.js +++ b/__tests__/lib/walk.js @@ -1,8 +1,8 @@ -var walk = require('../../src/walk').walk; +const walk = require('../../src/walk').walk; describe('walk', function() { test('flat comments', function() { - var comments = [{ name: 'Tom' }]; + const comments = [{ name: 'Tom' }]; function renamer(comment, options) { if (options) { @@ -20,7 +20,7 @@ describe('walk', function() { }); test('nested comments', function() { - var comments = [ + const comments = [ { name: 'Tom', members: { diff --git a/__tests__/linker.js b/__tests__/linker.js index 3b39120cd..35cead80c 100644 --- a/__tests__/linker.js +++ b/__tests__/linker.js @@ -1,7 +1,7 @@ -var LinkerStack = require('../src/output/util/linker_stack'); +const LinkerStack = require('../src/output/util/linker_stack'); test('linkerStack', function() { - var linkerStack = new LinkerStack({}); + const linkerStack = new LinkerStack({}); expect(linkerStack.link('string')).toBe( 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String' @@ -23,7 +23,7 @@ test('linkerStack', function() { }).link('Image') ).toBe('http://custom.com/'); - var linker = new LinkerStack({ + const linker = new LinkerStack({ paths: { Image: 'http://custom.com/' } diff --git a/__tests__/test.js b/__tests__/test.js index 71a11f121..2f6533536 100644 --- a/__tests__/test.js +++ b/__tests__/test.js @@ -1,28 +1,28 @@ -var documentationSchema = require('documentation-schema'), - validate = require('json-schema'), - documentation = require('../'), - outputMarkdown = require('../src/output/markdown.js'), - outputMarkdownAST = require('../src/output/markdown_ast.js'), - outputHtml = require('../src/output/html.js'), - normalize = require('./utils').normalize, - glob = require('glob'), - pify = require('pify'), - path = require('path'), - fs = require('fs'), - _ = require('lodash'), - chdir = require('chdir'); - -var UPDATE = !!process.env.UPDATE; +const documentationSchema = require('documentation-schema'); +const validate = require('json-schema'); +const documentation = require('../'); +const outputMarkdown = require('../src/output/markdown.js'); +const outputMarkdownAST = require('../src/output/markdown_ast.js'); +const outputHtml = require('../src/output/html.js'); +const normalize = require('./utils').normalize; +const glob = require('glob'); +const pify = require('pify'); +const path = require('path'); +const fs = require('fs'); +const _ = require('lodash'); +const chdir = require('chdir'); + +const UPDATE = !!process.env.UPDATE; function makePOJO(ast) { return JSON.parse(JSON.stringify(ast)); } function readOptionsFromFile(file) { - var s = fs.readFileSync(file, 'utf-8'); - var lines = s.split(/\n/, 20); - for (var i = 0; i < lines.length; i++) { - var m = lines[i].match(/^\/\/\s+Options:\s*(.+)$/); + const s = fs.readFileSync(file, 'utf-8'); + const lines = s.split(/\n/, 20); + for (let i = 0; i < lines.length; i++) { + const m = lines[i].match(/^\/\/\s+Options:\s*(.+)$/); if (m) { return JSON.parse(m[1]); } @@ -33,7 +33,7 @@ function readOptionsFromFile(file) { if (fs.existsSync(path.join(__dirname, '../.git'))) { test('git option', async function() { jest.setTimeout(10000); // 10 second timeout. After update flow.js on 0.56 version the test is executed more time. - var file = path.join(__dirname, './fixture/simple.input.js'); + const file = path.join(__dirname, './fixture/simple.input.js'); const result = await documentation.build([file], { github: true }); normalize(result); expect(result).toMatchSnapshot(); @@ -44,7 +44,7 @@ if (fs.existsSync(path.join(__dirname, '../.git'))) { } test('document-exported error', async function() { - var file = path.join(__dirname, 'fixture', 'document-exported-bad', 'x.js'); + const file = path.join(__dirname, 'fixture', 'document-exported-bad', 'x.js'); try { await documentation.build([file], { documentExported: true }); } catch (err) { @@ -60,7 +60,7 @@ test('external modules option', async function() { } ); normalize(result); - var outputfile = path.join( + const outputfile = path.join( __dirname, 'fixture', '_external-deps-included.json' @@ -100,7 +100,7 @@ describe('html', function() { readOptionsFromFile(file) ); const html = await outputHtml(result, {}); - var clean = html + const clean = html .sort((a, b) => a.path > b.path) .filter(r => r.path.match(/(html)$/)) .map(r => r.contents) @@ -144,12 +144,11 @@ describe('outputs', function() { test('JSON', function() { normalize(result); result.forEach(function(comment) { - validate( - comment, - documentationSchema.jsonSchema - ).errors.forEach(function(error) { - expect(error).toBeFalsy(); - }); + validate(comment, documentationSchema.jsonSchema).errors.forEach( + function(error) { + expect(error).toBeFalsy(); + } + ); }); expect(makePOJO(result)).toMatchSnapshot(); }); @@ -158,13 +157,13 @@ describe('outputs', function() { }); test('highlightAuto md output', async function() { - var file = path.join( - __dirname, - 'fixture/auto_lang_hljs/multilanguage.input.js' - ), - hljsConfig = { - hljs: { highlightAuto: true, languages: ['js', 'css', 'html'] } - }; + const file = path.join( + __dirname, + 'fixture/auto_lang_hljs/multilanguage.input.js' + ); + const hljsConfig = { + hljs: { highlightAuto: true, languages: ['js', 'css', 'html'] } + }; const result = await documentation.build(file, {}); const md = await outputMarkdown(result, hljsConfig); @@ -172,8 +171,8 @@ test('highlightAuto md output', async function() { }); test('config', async function() { - var file = path.join(__dirname, 'fixture', 'class.input.js'); - var outputfile = path.join(__dirname, 'fixture', 'class.config.output.md'); + const file = path.join(__dirname, 'fixture', 'class.input.js'); + const outputfile = path.join(__dirname, 'fixture', 'class.config.output.md'); const out = await documentation.build([file], { config: path.join(__dirname, 'fixture', 'simple.config.yml') }); @@ -182,7 +181,7 @@ test('config', async function() { }); test('config with nested sections', async function() { - var file = path.join(__dirname, 'fixture', 'sections.input.js'); + const file = path.join(__dirname, 'fixture', 'sections.input.js'); const out = await documentation.build([file], { config: path.join(__dirname, 'fixture', 'sections.config.yml') }); diff --git a/__tests__/utils.js b/__tests__/utils.js index 9031b6181..5e7675fb3 100644 --- a/__tests__/utils.js +++ b/__tests__/utils.js @@ -1,6 +1,6 @@ -var http = require('http'); +const http = require('http'); import { walk } from '../src/walk'; -var concat = require('concat-stream'); +const concat = require('concat-stream'); function get(url, callback) { return new Promise((resolve, reject) => { @@ -19,8 +19,8 @@ function get(url, callback) { function normalize(comments) { return walk(comments, function(comment) { - var hasGithub = !!comment.context.github; - var path = comment.context.path; + const hasGithub = !!comment.context.github; + const path = comment.context.path; comment.context = { loc: comment.context.loc }; @@ -40,7 +40,8 @@ module.exports.mockRepo = { path: { '.git': { HEAD: 'ref: refs/heads/master', - config: '[remote "origin"]\n' + + config: + '[remote "origin"]\n' + 'url = git@github.com:foo/bar.git\n' + 'fetch = +refs/heads/*:refs/remotes/origin/*', refs: { @@ -60,7 +61,8 @@ module.exports.mockRepo = { path: { '.git': { HEAD: 'e4cb2ffe677571d0503e659e4e64e01f45639c62', - config: '[remote "origin"]\n' + + config: + '[remote "origin"]\n' + 'url = git@github.com:foo/bar.git\n' + 'fetch = +refs/heads/*:refs/remotes/origin/*' }, @@ -85,7 +87,8 @@ module.exports.mockRepo = { path: { '.git': { HEAD: 'ref: refs/heads/master', - config: '[remote "origin"]\n' + + config: + '[remote "origin"]\n' + 'url = git@github.enterprise.com:foo/bar.git\n' + 'fetch = +refs/heads/*:refs/remotes/origin/*', refs: { diff --git a/bin/documentation.js b/bin/documentation.js index 0afb4a175..40d862331 100755 --- a/bin/documentation.js +++ b/bin/documentation.js @@ -2,10 +2,10 @@ /* eslint no-console: 0 */ -var yargs = require('yargs'); -var commands = require('../lib/commands'); +const yargs = require('yargs'); +const commands = require('../lib/commands'); -var argv = yargs +const argv = yargs .strict() .command(commands.serve) .command(commands.build) diff --git a/src/commands/build.js b/src/commands/build.js index 75f1931fa..fc00deb61 100644 --- a/src/commands/build.js +++ b/src/commands/build.js @@ -1,13 +1,13 @@ /* @flow */ -var streamArray = require('stream-array'), - sharedOptions = require('./shared_options'), - path = require('path'), - fs = require('fs'), - vfs = require('vinyl-fs'), - chokidar = require('chokidar'), - documentation = require('../'), - _ = require('lodash'); +const streamArray = require('stream-array'); +const sharedOptions = require('./shared_options'); +const path = require('path'); +const fs = require('fs'); +const vfs = require('vinyl-fs'); +const chokidar = require('chokidar'); +const documentation = require('../'); +const _ = require('lodash'); module.exports.command = 'build [input..]'; module.exports.describe = 'build documentation'; @@ -42,7 +42,7 @@ module.exports.builder = Object.assign( * just a thin wrapper around this one. */ module.exports.handler = function build(argv: Object) { - var watcher; + let watcher; argv._handled = true; if (!argv.input.length) { diff --git a/src/commands/lint.js b/src/commands/lint.js index 3e465cc9c..d6ef90cff 100644 --- a/src/commands/lint.js +++ b/src/commands/lint.js @@ -1,8 +1,8 @@ /* @flow */ -var documentation = require('../'); -var fs = require('fs'); -var path = require('path'); +const documentation = require('../'); +const fs = require('fs'); +const path = require('path'); /* eslint no-console: 0 */ diff --git a/src/commands/readme.js b/src/commands/readme.js index 4cc3df073..c2914e46f 100644 --- a/src/commands/readme.js +++ b/src/commands/readme.js @@ -1,13 +1,13 @@ /* @flow */ -var fs = require('fs'); -var remark = require('remark'); -var path = require('path'); -var documentation = require('../'); -var sharedOptions = require('./shared_options'); -var inject = require('mdast-util-inject'); -var chalk = require('chalk'); -var disparity = require('disparity'); +const fs = require('fs'); +const remark = require('remark'); +const path = require('path'); +const documentation = require('../'); +const sharedOptions = require('./shared_options'); +const inject = require('mdast-util-inject'); +const chalk = require('chalk'); +const disparity = require('disparity'); module.exports.command = 'readme [input..]'; module.exports.description = 'inject documentation into your README.md'; @@ -78,7 +78,7 @@ module.exports.handler = function readme(argv: Object) { } }; - var readmeContent = fs.readFileSync(argv.readmeFile, 'utf8'); + const readmeContent = fs.readFileSync(argv.readmeFile, 'utf8'); documentation .build(argv.input, argv) @@ -92,7 +92,7 @@ module.exports.handler = function readme(argv: Object) { .process(readmeContent) ) .then(file => { - var diffOutput = disparity.unified(readmeContent, file.contents, { + const diffOutput = disparity.unified(readmeContent, file.contents, { paths: [argv.readmeFile, argv.readmeFile] }); if (!diffOutput.length) { diff --git a/src/commands/serve.js b/src/commands/serve.js index 1097b63ab..34ac9a324 100644 --- a/src/commands/serve.js +++ b/src/commands/serve.js @@ -1,14 +1,14 @@ /* @flow */ -var errorPage = require('../serve/error_page'), - fs = require('fs'), - path = require('path'), - chokidar = require('chokidar'), - sharedOptions = require('./shared_options'), - Server = require('../serve/server'), - _ = require('lodash'), - getPort = require('get-port'), - documentation = require('../'); +const errorPage = require('../serve/error_page'); +const fs = require('fs'); +const path = require('path'); +const chokidar = require('chokidar'); +const sharedOptions = require('./shared_options'); +const Server = require('../serve/server'); +const _ = require('lodash'); +const getPort = require('get-port'); +const documentation = require('../'); module.exports.command = 'serve [input..]'; module.exports.description = 'generate, update, and display HTML documentation'; @@ -55,8 +55,8 @@ module.exports.handler = function serve(argv: Object) { } getPort(argv.port).then(port => { - var server = new Server(port); - var watcher; + const server = new Server(port); + let watcher; server.on('listening', function() { process.stdout.write(`documentation.js serving on port ${port}\n`); diff --git a/src/extractors/comments.js b/src/extractors/comments.js index 6bf52eb83..7d984773e 100644 --- a/src/extractors/comments.js +++ b/src/extractors/comments.js @@ -1,6 +1,6 @@ /* @flow */ import traverse from 'babel-traverse'; -var isJSDocComment = require('../is_jsdoc_comment'); +const isJSDocComment = require('../is_jsdoc_comment'); /** * Iterate through the abstract syntax tree, finding a different kind of comment @@ -21,7 +21,7 @@ function walkComments( data: Object, addComment: Function ): Array { - var newResults = []; + const newResults = []; traverse(ast, { /** diff --git a/src/extractors/exported.js b/src/extractors/exported.js index b8b724529..7de594976 100644 --- a/src/extractors/exported.js +++ b/src/extractors/exported.js @@ -1,11 +1,11 @@ /* @flow */ import traverse from 'babel-traverse'; -var isJSDocComment = require('../is_jsdoc_comment'); -var t = require('babel-types'); -var nodePath = require('path'); -var fs = require('fs'); +const isJSDocComment = require('../is_jsdoc_comment'); +const t = require('babel-types'); +const nodePath = require('path'); +const fs = require('fs'); import { parseToAst } from '../parsers/parse_to_ast'; -var findTarget = require('../infer/finders').findTarget; +const findTarget = require('../infer/finders').findTarget; /** * Iterate through the abstract syntax tree, finding ES6-style exports, @@ -25,16 +25,16 @@ function walkExported( } */, addComment: Function ) { - var newResults = []; - var filename = data.file; - var dataCache = new Map(); + const newResults = []; + const filename = data.file; + const dataCache = new Map(); function addBlankComment(data, path, node) { return addComment(data, '', node.loc, path, node.loc, true); } function getComments(data, path) { - var comments = (path.node.leadingComments || []).filter(isJSDocComment); + const comments = (path.node.leadingComments || []).filter(isJSDocComment); if (!comments.length) { // If this is the first declarator we check for comments on the VariableDeclaration. @@ -45,7 +45,7 @@ function walkExported( return getComments(data, path.parentPath); } - var added = addBlankComment(data, path, path.node); + const added = addBlankComment(data, path, path.node); return added ? [added] : []; } @@ -64,7 +64,7 @@ function walkExported( } function addComments(data, path, overrideName) { - var comments = getComments(data, path); + const comments = getComments(data, path); if (overrideName) { comments.forEach(function(comment) { comment.name = overrideName; @@ -78,7 +78,7 @@ function walkExported( path.skip(); }, ExportDeclaration(path) { - var declaration = path.get('declaration'); + const declaration = path.get('declaration'); if (t.isDeclaration(declaration)) { traverseExportedSubtree(declaration, data, addComments); return path.skip(); @@ -86,7 +86,7 @@ function walkExported( if (path.isExportDefaultDeclaration()) { if (declaration.isIdentifier()) { - var binding = declaration.scope.getBinding(declaration.node.name); + const binding = declaration.scope.getBinding(declaration.node.name); traverseExportedSubtree(binding.path, data, addComments); return path.skip(); } @@ -96,23 +96,23 @@ function walkExported( } if (t.isExportNamedDeclaration(path)) { - var specifiers = path.get('specifiers'); - var source = path.node.source; - var exportKind = path.node.exportKind; + const specifiers = path.get('specifiers'); + const source = path.node.source; + const exportKind = path.node.exportKind; specifiers.forEach(specifier => { - var specData = data; - var local, exported; + let specData = data; + let local; if (t.isExportDefaultSpecifier(specifier)) { local = 'default'; } else { // ExportSpecifier local = specifier.node.local.name; } - exported = specifier.node.exported.name; + const exported = specifier.node.exported.name; - var bindingPath; + let bindingPath; if (source) { - var tmp = findExportDeclaration( + const tmp = findExportDeclaration( dataCache, local, exportKind, @@ -145,7 +145,7 @@ function walkExported( } function traverseExportedSubtree(path, data, addComments, overrideName) { - var attachCommentPath = path; + let attachCommentPath = path; if (path.parentPath && path.parentPath.isExportDeclaration()) { attachCommentPath = path.parentPath; } @@ -179,15 +179,15 @@ function traverseExportedSubtree(path, data, addComments, overrideName) { } function getCachedData(dataCache, filePath) { - var path = filePath; + let path = filePath; if (!nodePath.extname(path)) { path = require.resolve(path); } - var value = dataCache.get(path); + let value = dataCache.get(path); if (!value) { - var input = fs.readFileSync(path, 'utf-8'); - var ast = parseToAst(input); + const input = fs.readFileSync(path, 'utf-8'); + const ast = parseToAst(input); value = { data: { file: path, @@ -208,12 +208,12 @@ function findExportDeclaration( referrer, filename ) { - var depPath = nodePath.resolve(nodePath.dirname(referrer), filename); - var tmp = getCachedData(dataCache, depPath); - var ast = tmp.ast; - var data = tmp.data; + const depPath = nodePath.resolve(nodePath.dirname(referrer), filename); + const tmp = getCachedData(dataCache, depPath); + const ast = tmp.ast; + let data = tmp.data; - var rv; + let rv; traverse(ast, { Statement(path) { path.skip(); @@ -223,9 +223,9 @@ function findExportDeclaration( rv = path.get('declaration'); path.stop(); } else if (path.isExportNamedDeclaration()) { - var declaration = path.get('declaration'); + const declaration = path.get('declaration'); if (t.isDeclaration(declaration)) { - var bindingName; + let bindingName; if ( declaration.isFunctionDeclaration() || declaration.isClassDeclaration() || @@ -247,11 +247,11 @@ function findExportDeclaration( // export {x as y} // export {x as y} from './file.js' - var specifiers = path.get('specifiers'); - var source = path.node.source; - for (var i = 0; i < specifiers.length; i++) { - var specifier = specifiers[i]; - var local, exported; + const specifiers = path.get('specifiers'); + const source = path.node.source; + for (let i = 0; i < specifiers.length; i++) { + const specifier = specifiers[i]; + let local, exported; if (t.isExportDefaultSpecifier(specifier)) { // export x from ... local = 'default'; @@ -264,7 +264,7 @@ function findExportDeclaration( if (exported === name) { if (source) { // export {local as exported} from './file.js'; - var tmp = findExportDeclaration( + const tmp = findExportDeclaration( dataCache, local, exportKind, @@ -304,7 +304,7 @@ function findExportDeclaration( // Since we cannot use scope.getBinding for types this walks the current scope looking for a // top-level type alias. function findLocalType(scope, local) { - var rv; + let rv; scope.path.traverse({ Statement(path) { path.skip(); diff --git a/src/filter_access.js b/src/filter_access.js index 5ff4dbc6e..b348eef8f 100644 --- a/src/filter_access.js +++ b/src/filter_access.js @@ -20,7 +20,7 @@ function filterAccess(levels: Array, comments: Array) { } function recurse(comment) { - for (var scope in comment.members) { + for (const scope in comment.members) { comment.members[scope] = comment.members[scope].filter(filter); } } diff --git a/src/flow_doctrine.js b/src/flow_doctrine.js index 208df57d8..2e134eb4c 100644 --- a/src/flow_doctrine.js +++ b/src/flow_doctrine.js @@ -2,13 +2,13 @@ const generate = require('babel-generator').default; -var namedTypes = { +const namedTypes = { NumberTypeAnnotation: 'number', BooleanTypeAnnotation: 'boolean', StringTypeAnnotation: 'string' }; -var oneToOne = { +const oneToOne = { AnyTypeAnnotation: 'AllLiteral', MixedTypeAnnotation: 'AllLiteral', NullLiteralTypeAnnotation: 'NullLiteral', @@ -16,7 +16,7 @@ var oneToOne = { }; function propertyToField(property) { - var type = flowDoctrine(property.value); + let type = flowDoctrine(property.value); if (property.optional) { // Doctrine does not support optional fields but it does have something called optional types // (which makes no sense, but let's play along). @@ -45,7 +45,7 @@ function propertyToField(property) { */ function flowDoctrine(type: Object): DoctrineType { if (type.type in namedTypes) { - let doctrineType = { + const doctrineType = { type: 'NameExpression', name: namedTypes[type.type] }; diff --git a/src/git/find_git.js b/src/git/find_git.js index 8dfb0e8e5..ffa18351a 100644 --- a/src/git/find_git.js +++ b/src/git/find_git.js @@ -1,7 +1,7 @@ /* @flow */ -var path = require('path'); -var fs = require('fs'); +const path = require('path'); +const fs = require('fs'); /** * Given a full path to a single file, iterate upwards through the filesystem @@ -10,9 +10,11 @@ var fs = require('fs'); * @returns repository path */ function findGit(filename: string) { - var paths = filename.split(path.sep); - for (var i = paths.length; i > 0; i--) { - var p = path.resolve(paths.slice(0, i).join(path.sep) + path.sep + '.git'); + const paths = filename.split(path.sep); + for (let i = paths.length; i > 0; i--) { + const p = path.resolve( + paths.slice(0, i).join(path.sep) + path.sep + '.git' + ); if (fs.existsSync(p)) { return p; } diff --git a/src/git/url_prefix.js b/src/git/url_prefix.js index 10315914f..46cd178ee 100644 --- a/src/git/url_prefix.js +++ b/src/git/url_prefix.js @@ -1,8 +1,8 @@ /* @flow */ -var fs = require('fs'); -var path = require('path'); -var gitUrlParse = require('git-url-parse'); -var getRemoteOrigin = require('remote-origin-url'); +const fs = require('fs'); +const path = require('path'); +const gitUrlParse = require('git-url-parse'); +const getRemoteOrigin = require('remote-origin-url'); /** * Sometimes git will [pack refs](https://git-scm.com/docs/git-pack-refs) @@ -34,14 +34,14 @@ function parsePackedRefs(packedRefs, branchName) { * @throws {Error} if the root is not a git repo */ function getGithubURLPrefix(root: string) { - var sha; + let sha; try { - var head = fs.readFileSync(path.join(root, '.git', 'HEAD'), 'utf8'); - var branch = head.match(/ref: (.*)/); + const head = fs.readFileSync(path.join(root, '.git', 'HEAD'), 'utf8'); + const branch = head.match(/ref: (.*)/); if (branch) { - var branchName = branch[1]; - var branchFileName = path.join(root, '.git', branchName); - var packedRefsName = path.join(root, '.git', 'packed-refs'); + const branchName = branch[1]; + const branchFileName = path.join(root, '.git', branchName); + const packedRefsName = path.join(root, '.git', 'packed-refs'); if (fs.existsSync(branchFileName)) { sha = fs.readFileSync(branchFileName, 'utf8'); } else if (fs.existsSync(packedRefsName)) { diff --git a/src/github.js b/src/github.js index a739c5aae..1a80cfffc 100644 --- a/src/github.js +++ b/src/github.js @@ -1,8 +1,8 @@ /* @flow */ -var path = require('path'); -var findGit = require('./git/find_git'); -var getGithubURLPrefix = require('./git/url_prefix'); +const path = require('path'); +const findGit = require('./git/find_git'); +const getGithubURLPrefix = require('./git/url_prefix'); /** * Attempts to link code to its place on GitHub. @@ -12,17 +12,18 @@ var getGithubURLPrefix = require('./git/url_prefix'); * @returns {Object} comment with github inferred */ module.exports = function(comment: Comment) { - var repoPath = findGit(comment.context.file); - var root = repoPath ? path.dirname(repoPath) : '.'; - var urlPrefix = getGithubURLPrefix(root); - var fileRelativePath = comment.context.file + const repoPath = findGit(comment.context.file); + const root = repoPath ? path.dirname(repoPath) : '.'; + const urlPrefix = getGithubURLPrefix(root); + const fileRelativePath = comment.context.file .replace(root + path.sep, '') .split(path.sep) .join('/'); if (urlPrefix) { comment.context.github = { - url: urlPrefix + + url: + urlPrefix + fileRelativePath + '#L' + comment.context.loc.start.line + diff --git a/src/hierarchy.js b/src/hierarchy.js index b4067a5d0..ab94adf8e 100644 --- a/src/hierarchy.js +++ b/src/hierarchy.js @@ -1,18 +1,18 @@ -var _ = require('lodash'); -var hasOwnProperty = Object.prototype.hasOwnProperty; +const _ = require('lodash'); +const hasOwnProperty = Object.prototype.hasOwnProperty; /** * Check if a given member object is of kind `event`. * @param {Object} member - The member to check. * @returns {boolean} `true` if it is of kind `event`, otherwise false. */ -let isEvent = member => member.kind === 'event'; +const isEvent = member => member.kind === 'event'; /** * We need to have members of all valid JSDoc scopes. * @private */ -let getMembers = () => ({ +const getMembers = () => ({ global: Object.create(null), inner: Object.create(null), instance: Object.create(null), @@ -32,7 +32,7 @@ function pick(comment) { return undefined; } - var item = { + const item = { name: comment.name, kind: comment.kind }; @@ -50,10 +50,10 @@ function pick(comment) { * at the top level. */ module.exports = function(comments) { - var id = 0, - root = { - members: getMembers() - }; + let id = 0; + const root = { + members: getMembers() + }; const namesToUnroot = []; @@ -81,12 +81,12 @@ module.exports = function(comments) { }); } - var node = root; + let node = root; while (path.length) { - var segment = path.shift(), - scope = segment.scope, - name = segment.name; + const segment = path.shift(); + const scope = segment.scope; + const name = segment.name; if (!hasOwnProperty.call(node.members[scope], name)) { // If segment.toc is true, everything up to this point in the path @@ -141,13 +141,13 @@ module.exports = function(comments) { * Person~say // the inner method named "say." */ function toComments(nodes, root, hasUndefinedParent, path) { - var result = [], - scope; + const result = []; + let scope; path = path || []; - for (var name in nodes) { - var node = nodes[name]; + for (const name in nodes) { + const node = nodes[name]; for (scope in node.members) { node.members[scope] = toComments( @@ -160,16 +160,16 @@ module.exports = function(comments) { ); } - for (var i = 0; i < node.comments.length; i++) { - var comment = node.comments[i]; + for (let i = 0; i < node.comments.length; i++) { + const comment = node.comments[i]; comment.members = {}; for (scope in node.members) { comment.members[scope] = node.members[scope]; } - var events = comment.members.events; - var groups = []; + let events = comment.members.events; + let groups = []; if (comment.members.instance.length) { groups = _.groupBy(comment.members.instance, isEvent); @@ -201,9 +201,12 @@ module.exports = function(comments) { comment.members.events = events; - comment.path = path.map(pick).concat(pick(comment)).filter(Boolean); + comment.path = path + .map(pick) + .concat(pick(comment)) + .filter(Boolean); - var scopeChars = { + const scopeChars = { instance: '#', static: '.', inner: '~', @@ -222,10 +225,10 @@ module.exports = function(comments) { }, ''); if (hasUndefinedParent) { - var memberOfTag = comment.tags.filter( + const memberOfTag = comment.tags.filter( tag => tag.title === 'memberof' )[0]; - var memberOfTagLineNumber = + const memberOfTagLineNumber = (memberOfTag && memberOfTag.lineNumber) || 0; comment.errors.push({ diff --git a/src/index.js b/src/index.js index d8e0b147b..6ccc2bb62 100644 --- a/src/index.js +++ b/src/index.js @@ -1,27 +1,27 @@ -var fs = require('fs'), - _ = require('lodash'), - sort = require('./sort'), - nest = require('./nest'), - filterAccess = require('./filter_access'), - dependency = require('./input/dependency'), - shallow = require('./input/shallow'), - parseJavaScript = require('./parsers/javascript'), - github = require('./github'), - hierarchy = require('./hierarchy'), - inferName = require('./infer/name'), - inferKind = require('./infer/kind'), - inferAugments = require('./infer/augments'), - inferParams = require('./infer/params'), - inferProperties = require('./infer/properties'), - inferMembership = require('./infer/membership'), - inferReturn = require('./infer/return'), - inferAccess = require('./infer/access'), - inferType = require('./infer/type'), - formatLint = require('./lint').formatLint, - garbageCollect = require('./garbage_collect'), - lintComments = require('./lint').lintComments, - markdownAST = require('./output/markdown_ast'), - mergeConfig = require('./merge_config'); +const fs = require('fs'); +const _ = require('lodash'); +const sort = require('./sort'); +const nest = require('./nest'); +const filterAccess = require('./filter_access'); +const dependency = require('./input/dependency'); +const shallow = require('./input/shallow'); +const parseJavaScript = require('./parsers/javascript'); +const github = require('./github'); +const hierarchy = require('./hierarchy'); +const inferName = require('./infer/name'); +const inferKind = require('./infer/kind'); +const inferAugments = require('./infer/augments'); +const inferParams = require('./infer/params'); +const inferProperties = require('./infer/properties'); +const inferMembership = require('./infer/membership'); +const inferReturn = require('./infer/return'); +const inferAccess = require('./infer/access'); +const inferType = require('./infer/type'); +const formatLint = require('./lint').formatLint; +const garbageCollect = require('./garbage_collect'); +const lintComments = require('./lint').lintComments; +const markdownAST = require('./output/markdown_ast'); +const mergeConfig = require('./merge_config'); /** * Build a pipeline of comment handlers. @@ -32,7 +32,7 @@ var fs = require('fs'), */ function pipeline(fns) { return comment => { - for (var i = 0; comment && i < fns.length; i++) { + for (let i = 0; comment && i < fns.length; i++) { if (fns[i]) { comment = fns[i](comment); } @@ -42,10 +42,10 @@ function pipeline(fns) { } function configure(indexes, args) { - let mergedConfig = mergeConfig(args); + const mergedConfig = mergeConfig(args); return mergedConfig.then(config => { - let expandedInputs = expandInputs(indexes, config); + const expandedInputs = expandInputs(indexes, config); return expandedInputs.then(inputs => { return { @@ -76,14 +76,14 @@ function expandInputs(indexes, config) { } function buildInternal(inputsAndConfig) { - let config = inputsAndConfig.config; - let inputs = inputsAndConfig.inputs; + const config = inputsAndConfig.config; + const inputs = inputsAndConfig.inputs; if (!config.access) { config.access = ['public', 'undefined', 'protected']; } - var buildPipeline = pipeline([ + const buildPipeline = pipeline([ inferName, inferAccess(config.inferPrivate), inferAugments, @@ -98,7 +98,7 @@ function buildInternal(inputsAndConfig) { garbageCollect ]); - let extractedComments = _.flatMap(inputs, function(sourceFile) { + const extractedComments = _.flatMap(inputs, function(sourceFile) { if (!sourceFile.source) { sourceFile.source = fs.readFileSync(sourceFile.file, 'utf8'); } @@ -113,10 +113,10 @@ function buildInternal(inputsAndConfig) { } function lintInternal(inputsAndConfig) { - let inputs = inputsAndConfig.inputs; - let config = inputsAndConfig.config; + const inputs = inputsAndConfig.inputs; + const config = inputsAndConfig.config; - let lintPipeline = pipeline([ + const lintPipeline = pipeline([ lintComments, inferName, inferAccess(config.inferPrivate), @@ -130,7 +130,7 @@ function lintInternal(inputsAndConfig) { nest ]); - let extractedComments = _.flatMap(inputs, sourceFile => { + const extractedComments = _.flatMap(inputs, sourceFile => { if (!sourceFile.source) { sourceFile.source = fs.readFileSync(sourceFile.file, 'utf8'); } @@ -171,7 +171,7 @@ function lintInternal(inputsAndConfig) { * } * }); */ -let lint = (indexes, args) => configure(indexes, args).then(lintInternal); +const lint = (indexes, args) => configure(indexes, args).then(lintInternal); /** * Generate JavaScript documentation as a list of parsed JSDoc @@ -211,7 +211,7 @@ let lint = (indexes, args) => configure(indexes, args).then(lintInternal); * // any other kind of code data. * }); */ -let build = (indexes, args) => configure(indexes, args).then(buildInternal); +const build = (indexes, args) => configure(indexes, args).then(buildInternal); /** * Documentation's formats are modular methods that take comments @@ -220,7 +220,7 @@ let build = (indexes, args) => configure(indexes, args).then(buildInternal); * output. * @public */ -var formats = { +const formats = { html: require('./output/html'), md: require('./output/markdown'), remark: (comments, config) => diff --git a/src/infer/access.js b/src/infer/access.js index 5908b2a87..b43a0f5f8 100644 --- a/src/infer/access.js +++ b/src/infer/access.js @@ -9,7 +9,7 @@ * @private */ function inferAccessWithPattern(pattern: ?string) { - var re = pattern && new RegExp(pattern); + const re = pattern && new RegExp(pattern); /** * Infers access (only private atm) from the name. diff --git a/src/infer/augments.js b/src/infer/augments.js index 1801eefb5..1dd8860a6 100644 --- a/src/infer/augments.js +++ b/src/infer/augments.js @@ -1,7 +1,7 @@ /* @flow */ import generate from 'babel-generator'; -var findTarget = require('./finders').findTarget; +const findTarget = require('./finders').findTarget; /** * Infers an `augments` tag from an ES6 class declaration @@ -14,7 +14,7 @@ function inferAugments(comment: Comment) { return comment; } - var path = findTarget(comment.context.ast); + const path = findTarget(comment.context.ast); if (!path) { return comment; diff --git a/src/infer/finders.js b/src/infer/finders.js index f85471b08..b2e9f70fb 100644 --- a/src/infer/finders.js +++ b/src/infer/finders.js @@ -1,6 +1,6 @@ /* @flow */ -var t = require('babel-types'); +const t = require('babel-types'); /** * Try to find the part of JavaScript a comment is referring to, by diff --git a/src/infer/kind.js b/src/infer/kind.js index be0310927..d7c1bb428 100644 --- a/src/infer/kind.js +++ b/src/infer/kind.js @@ -1,6 +1,6 @@ /* @flow */ -var t = require('babel-types'); +const t = require('babel-types'); /** * Infers a `kind` tag from the context. diff --git a/src/infer/membership.js b/src/infer/membership.js index f887109cd..1fc0b51a5 100644 --- a/src/infer/membership.js +++ b/src/infer/membership.js @@ -1,9 +1,9 @@ /* @flow */ -var n = require('babel-types'), - pathParse = require('parse-filepath'), - isJSDocComment = require('../is_jsdoc_comment'), - parse = require('../parse'); +const n = require('babel-types'); +const pathParse = require('parse-filepath'); +const isJSDocComment = require('../is_jsdoc_comment'); +const parse = require('../parse'); function inferModuleName(comment) { return ( @@ -26,12 +26,12 @@ function findLendsIdentifiers(path) { return; } - var leadingComments = path.get('leadingComments'); + const leadingComments = path.get('leadingComments'); - for (var i = 0; i < leadingComments.length; i++) { - var comment = leadingComments[i]; + for (let i = 0; i < leadingComments.length; i++) { + const comment = leadingComments[i]; if (isJSDocComment(comment.node)) { - var lends = parse(comment.node.value).lends; + const lends = parse(comment.node.value).lends; if (lends) { return lends.split('.'); } @@ -50,7 +50,7 @@ function findLendsIdentifiers(path) { * @private */ function extractThis(path, comment) { - var identifiers = []; + let identifiers = []; path.traverse({ /** @@ -60,7 +60,7 @@ function extractThis(path, comment) { * @private */ ThisExpression(path) { - var scope = path.scope; + let scope = path.scope; while (n.isBlockStatement(scope.block)) { scope = scope.parent; @@ -111,7 +111,7 @@ function extractThis(path, comment) { * @private */ function extractIdentifiers(path) { - var identifiers = []; + const identifiers = []; path.traverse({ /** @@ -161,9 +161,9 @@ function normalizeMemberof(comment: Comment): Comment { return comment; } - var memberof = comment.memberof; + const memberof = comment.memberof; - var isPrototype = /.prototype$/; + const isPrototype = /.prototype$/; if (memberof.match(isPrototype) !== null) { comment.memberof = memberof.replace(isPrototype, ''); @@ -172,7 +172,7 @@ function normalizeMemberof(comment: Comment): Comment { return comment; } - var isInstanceMember = /#$/; + const isInstanceMember = /#$/; if (memberof.match(isInstanceMember) !== null) { comment.memberof = memberof.replace(isInstanceMember, ''); @@ -191,7 +191,7 @@ function normalizeMemberof(comment: Comment): Comment { * @returns {Object} comment with membership inferred */ module.exports = function() { - var currentModule; + let currentModule; /** * Set `memberof` and `instance`/`static` tags on `comment` based on the @@ -221,7 +221,7 @@ module.exports = function() { * Test whether identifiers start with a module export (`exports` or `module.exports`), * and if so replace those identifiers with the name of the current module. */ - var moduleIdentifierCount = countModuleIdentifiers(comment, identifiers); + const moduleIdentifierCount = countModuleIdentifiers(comment, identifiers); if (moduleIdentifierCount) { identifiers = identifiers.slice(moduleIdentifierCount); identifiers.unshift(inferModuleName(currentModule || comment)); @@ -258,7 +258,7 @@ module.exports = function() { return normalizeMemberof(comment); } - var path = comment.context.ast; + let path = comment.context.ast; // If this chunk doesn't have code attached, like if it was the result // of a polyglot parse, don't try to infer anything. if (!path) { @@ -271,7 +271,10 @@ module.exports = function() { if ( path.isExpressionStatement() && path.get('expression').isAssignmentExpression() && - path.get('expression').get('left').isMemberExpression() + path + .get('expression') + .get('left') + .isMemberExpression() ) { path = path.get('expression').get('left'); } @@ -289,7 +292,7 @@ module.exports = function() { // // Lends is not supported in this codepath. if (path.isMemberExpression()) { - var memberIdentifiers = [].concat( + const memberIdentifiers = [].concat( extractThis(path, comment), extractIdentifiers(path) ); @@ -314,7 +317,7 @@ module.exports = function() { path.parentPath.isClassBody() && path.parentPath.parentPath.isClass() ) { - var scope = 'instance'; + let scope = 'instance'; if (path.node.static == true) { scope = 'static'; } @@ -327,7 +330,7 @@ module.exports = function() { ); } - var declarationNode = path.parentPath.parentPath.node; + const declarationNode = path.parentPath.parentPath.node; if (!declarationNode.id) { // export default function () {} // export default class {} @@ -351,7 +354,7 @@ module.exports = function() { // doesn't matter for the membership phase, as long as we end up knowing // that it belongs to an object. So we first establish objectParent, // and then have the logic for the numerous ways an object can be named. - var objectParent; + let objectParent; if ( path.isIdentifier() && @@ -367,7 +370,7 @@ module.exports = function() { if (objectParent) { // The @lends comment is sometimes attached to the first property rather than // the object expression itself. - var lendsIdentifiers = + const lendsIdentifiers = findLendsIdentifiers(objectParent) || findLendsIdentifiers(objectParent.get('properties')[0]); diff --git a/src/infer/name.js b/src/infer/name.js index 99048ffe6..8b39d4428 100644 --- a/src/infer/name.js +++ b/src/infer/name.js @@ -1,6 +1,7 @@ /* @flow */ -var pathParse = require('parse-filepath'), t = require('babel-types'); +const pathParse = require('parse-filepath'); +const t = require('babel-types'); /** * Infers a `name` tag from the context. @@ -35,7 +36,7 @@ function inferName(comment: Comment) { } } - var path = comment.context.ast; + const path = comment.context.ast; if (path) { if (path.type === 'ExportDefaultDeclaration') { if (t.isDeclaration(path.node.declaration) && path.node.declaration.id) { diff --git a/src/infer/params.js b/src/infer/params.js index 4c8751c83..117222fa4 100644 --- a/src/infer/params.js +++ b/src/infer/params.js @@ -13,7 +13,7 @@ import flowDoctrine from '../flow_doctrine'; * @returns {Object} comment with parameters */ function inferParams(comment: Comment) { - var path = finders.findTarget(comment.context.ast); + let path = finders.findTarget(comment.context.ast); if (!path) { return comment; } @@ -30,7 +30,7 @@ function inferParams(comment: Comment) { t.isClassDeclaration(path) && !(comment.constructorComment && comment.constructorComment.hideconstructor) ) { - let constructor = path.node.body.body.find(item => { + const constructor = path.node.body.body.find(item => { // https://github.com/babel/babylon/blob/master/ast/spec.md#classbody return t.isClassMethod(item) && item.kind === 'constructor'; }); @@ -51,8 +51,8 @@ function inferParams(comment: Comment) { } function inferAndCombineParams(params, comment) { - var inferredParams = params.map((param, i) => paramToDoc(param, '', i)); - var mergedParamsAndErrors = mergeTrees(inferredParams, comment.params); + const inferredParams = params.map((param, i) => paramToDoc(param, '', i)); + const mergedParamsAndErrors = mergeTrees(inferredParams, comment.params); // Then merge the trees. This is the hard part. return Object.assign(comment, { @@ -181,7 +181,7 @@ function paramToDoc( // instead we're going to (immutably) rename the parameters to their // indices properties: _.flatMap(param.elements, (element, idx) => { - var indexedElement = Object.assign({}, element, { + const indexedElement = Object.assign({}, element, { name: String(idx), indexed: true }); @@ -190,7 +190,7 @@ function paramToDoc( }; } return _.flatMap(param.elements, (element, idx) => { - var indexedElement = Object.assign({}, element, { + const indexedElement = Object.assign({}, element, { name: String(idx) }); return paramToDoc(indexedElement, prefix); @@ -209,7 +209,7 @@ function paramToDoc( } case 'RestProperty': // (a, ...b) case 'RestElement': { - let type: DoctrineType = { + const type: DoctrineType = { type: 'RestType' }; if (param.typeAnnotation) { @@ -224,7 +224,7 @@ function paramToDoc( } default: { // (a) - var newParam: CommentTag = { + const newParam: CommentTag = { title: 'param', name: prefix ? prefixedName : param.name, lineNumber: param.loc.start.line @@ -255,7 +255,7 @@ function paramToDoc( * also $0.x and maybe $0.x.y.z all to options.x and options.x.y.z */ function renameTree(node, explicitName) { - var parts = node.name.split(PATH_SPLIT_CAPTURING); + const parts = node.name.split(PATH_SPLIT_CAPTURING); parts[0] = explicitName; node.name = parts.join(''); if (node.properties) { @@ -274,7 +274,7 @@ function mergeTrees(inferred, explicit) { // to destructuring parameters, which do not have inferred names. This is // _only_ enabled in the case in which all parameters are specified explicitly if (inferred.length === explicit.length) { - for (var i = 0; i < inferred.length; i++) { + for (let i = 0; i < inferred.length; i++) { if (inferred[i].anonymous === true) { renameTree(inferred[i], explicit[i].name); } @@ -291,7 +291,7 @@ function mergeTopNodes(inferred, explicit) { return tagDepth(tag) === 1 && !inferredNames.has(tag.name); }); - var errors = explicitTagsWithoutInference.map(tag => { + const errors = explicitTagsWithoutInference.map(tag => { return { message: `An explicit parameter named ${tag.name || @@ -337,7 +337,7 @@ function mergeNodes(inferred, explicit) { function combineTags(inferredTag, explicitTag) { let type = explicitTag.type; - var defaultValue; + let defaultValue; if (!explicitTag.type) { type = inferredTag.type; } else if (!explicitTag.default && inferredTag.default) { diff --git a/src/infer/properties.js b/src/infer/properties.js index 12d9639ee..dddb4eec6 100644 --- a/src/infer/properties.js +++ b/src/infer/properties.js @@ -1,7 +1,7 @@ /* @flow */ -var flowDoctrine = require('../flow_doctrine'), - findTarget = require('./finders').findTarget; +const flowDoctrine = require('../flow_doctrine'); +const findTarget = require('./finders').findTarget; function prefixedName(name, prefix) { if (prefix.length) { @@ -11,8 +11,8 @@ function prefixedName(name, prefix) { } function propertyToDoc(property, prefix): CommentTag { - var type = flowDoctrine(property.value); - var name = property.key.name || property.key.value + let type = flowDoctrine(property.value); + const name = property.key.name || property.key.value; if (property.optional) { type = { type: 'OptionalType', @@ -34,7 +34,7 @@ function propertyToDoc(property, prefix): CommentTag { * @returns {Object} comment with inferred properties */ function inferProperties(comment: Comment): Comment { - let explicitProperties = new Set(); + const explicitProperties = new Set(); // Ensure that explicitly specified properties are not overridden // by inferred properties comment.properties.forEach(prop => explicitProperties.add(prop)); @@ -55,7 +55,7 @@ function inferProperties(comment: Comment): Comment { } } - var path = findTarget(comment.context.ast); + const path = findTarget(comment.context.ast); if (path) { if (path.isTypeAlias()) { diff --git a/src/infer/return.js b/src/infer/return.js index bd22c9f00..e48cf97b1 100644 --- a/src/infer/return.js +++ b/src/infer/return.js @@ -1,8 +1,8 @@ /* @flow */ -var findTarget = require('./finders').findTarget, - t = require('babel-types'), - flowDoctrine = require('../flow_doctrine'); +const findTarget = require('./finders').findTarget; +const t = require('babel-types'); +const flowDoctrine = require('../flow_doctrine'); /** * Infers returns tags by using Flow return type annotations @@ -19,8 +19,8 @@ function inferReturn(comment: Comment) { ) { return comment; } - var path = findTarget(comment.context.ast); - var fn = path && path.node; + const path = findTarget(comment.context.ast); + let fn = path && path.node; if (!fn) { return comment; } @@ -32,7 +32,7 @@ function inferReturn(comment: Comment) { } if (t.isFunction(fn) && fn.returnType && fn.returnType.typeAnnotation) { - var returnType = flowDoctrine(fn.returnType.typeAnnotation); + const returnType = flowDoctrine(fn.returnType.typeAnnotation); if (comment.returns && comment.returns.length > 0) { comment.returns[0].type = returnType; } else { diff --git a/src/infer/type.js b/src/infer/type.js index 9d4d2b03a..ce03466a7 100644 --- a/src/infer/type.js +++ b/src/infer/type.js @@ -1,10 +1,10 @@ /* @flow */ -var findTarget = require('./finders').findTarget, - flowDoctrine = require('../flow_doctrine'), - t = require('babel-types'); +const findTarget = require('./finders').findTarget; +const flowDoctrine = require('../flow_doctrine'); +const t = require('babel-types'); -var constTypeMapping = { +const constTypeMapping = { BooleanLiteral: { type: 'BooleanTypeAnnotation' }, NumericLiteral: { type: 'NumberTypeAnnotation' }, StringLiteral: { type: 'StringTypeAnnotation' } @@ -22,13 +22,13 @@ function inferType(comment: Comment) { return comment; } - var path = findTarget(comment.context.ast); + const path = findTarget(comment.context.ast); if (!path) { return comment; } - var n = path.node; - var type; + const n = path.node; + let type; switch (n.type) { case 'VariableDeclarator': type = n.id.typeAnnotation; diff --git a/src/inline_tokenizer.js b/src/inline_tokenizer.js index 30006cded..3c893b13b 100644 --- a/src/inline_tokenizer.js +++ b/src/inline_tokenizer.js @@ -11,8 +11,8 @@ * @returns {Function} tokenizer */ function makeTokenizer(type, regex) { - var tokenizer = function(eat, value) { - var match = regex.exec(value); + const tokenizer = function(eat, value) { + const match = regex.exec(value); if (!match) { return; @@ -40,8 +40,8 @@ function makeTokenizer(type, regex) { return tokenizer; } -var tokenizeLink = makeTokenizer('link', /^\{@link\s+(.+?)(?:[\s|](.*?))?\}/); -var tokenizeTutorial = makeTokenizer( +const tokenizeLink = makeTokenizer('link', /^\{@link\s+(.+?)(?:[\s|](.*?))?\}/); +const tokenizeTutorial = makeTokenizer( 'tutorial', /^\{@tutorial\s+(.+?)(?:[\s|](.*?))?\}/ ); @@ -58,10 +58,10 @@ var tokenizeTutorial = makeTokenizer( * @returns {undefined} */ module.exports = function(/* options: Object*/) { - var proto = this.Parser.prototype; + const proto = this.Parser.prototype; proto.inlineTokenizers.tokenizeLink = tokenizeLink; proto.inlineTokenizers.tokenizeTutorial = tokenizeTutorial; - var methods = proto.inlineMethods; + const methods = proto.inlineMethods; methods.splice( methods.indexOf('inlineText'), 0, diff --git a/src/input/dependency.js b/src/input/dependency.js index 7fad0cad9..95eac7ae6 100644 --- a/src/input/dependency.js +++ b/src/input/dependency.js @@ -1,11 +1,11 @@ /* @flow */ -var mdeps = require('module-deps-sortable'); -var path = require('path'); -var babelify = require('babelify'); -var concat = require('concat-stream'); -var moduleFilters = require('../module_filters'); -var smartGlob = require('../smart_glob.js'); +const mdeps = require('module-deps-sortable'); +const path = require('path'); +const babelify = require('babelify'); +const concat = require('concat-stream'); +const moduleFilters = require('../module_filters'); +const smartGlob = require('../smart_glob.js'); /** * Returns a readable stream of dependencies, given an array of entry @@ -22,7 +22,7 @@ function dependencyStream( indexes: Array, config: DocumentationConfig ): Promise> { - var md = mdeps({ + const md = mdeps({ /** * Determine whether a module should be included in documentation * @param {string} id path to a module diff --git a/src/input/shallow.js b/src/input/shallow.js index 8d5ce743a..5d85ead00 100644 --- a/src/input/shallow.js +++ b/src/input/shallow.js @@ -1,6 +1,6 @@ /* @flow */ -var smartGlob = require('../smart_glob.js'); +const smartGlob = require('../smart_glob.js'); /** * A readable source for content that doesn't do dependency resolution, but @@ -22,9 +22,9 @@ module.exports = function( indexes: Array, config: DocumentationConfig ): Promise> { - var objects = []; - var strings = []; - for (var index of indexes) { + const objects = []; + const strings = []; + for (const index of indexes) { if (typeof index === 'string') { strings.push(index); } else if (typeof index === 'object') { diff --git a/src/is_jsdoc_comment.js b/src/is_jsdoc_comment.js index c8495f8e8..e1eefecbb 100644 --- a/src/is_jsdoc_comment.js +++ b/src/is_jsdoc_comment.js @@ -18,7 +18,7 @@ module.exports = function isJSDocComment( type: string }*/ ) { - var asterisks = comment.value.match(/^(\*+)/); + const asterisks = comment.value.match(/^(\*+)/); return ( comment.type === 'CommentBlock' && asterisks && asterisks[1].length === 1 ); diff --git a/src/lint.js b/src/lint.js index 7ecccb719..a941e7a5a 100644 --- a/src/lint.js +++ b/src/lint.js @@ -1,12 +1,12 @@ /* @flow */ -var VFile = require('vfile'); +const VFile = require('vfile'); import { walk } from './walk'; import vfileSort from 'vfile-sort'; import reporter from 'vfile-reporter'; import nest from './nest'; -var CANONICAL = { +const CANONICAL = { String: 'string', Boolean: 'boolean', Undefined: 'undefined', @@ -70,10 +70,10 @@ function lintComments(comment: Comment) { * @returns {string} user-readable output */ function formatLint(comments: Array): string { - var vFiles = {}; + const vFiles = {}; walk(comments, function(comment) { comment.errors.forEach(function(error) { - var p = comment.context.file; + const p = comment.context.file; vFiles[p] = vFiles[p] || new VFile({ diff --git a/src/merge_config.js b/src/merge_config.js index 65dcf733d..a14a49877 100644 --- a/src/merge_config.js +++ b/src/merge_config.js @@ -1,11 +1,11 @@ /* @flow */ -var yaml = require('js-yaml'), - fs = require('fs'), - pify = require('pify'), - readPkgUp = require('read-pkg-up'), - path = require('path'), - stripComments = require('strip-json-comments'); +const yaml = require('js-yaml'); +const fs = require('fs'); +const pify = require('pify'); +const readPkgUp = require('read-pkg-up'); +const path = require('path'); +const stripComments = require('strip-json-comments'); function processToc(config: DocumentationConfig, absFilePath: string) { if (!config || !config.toc) { @@ -58,31 +58,37 @@ function mergePackage(config: Object): Promise { */ function mergeConfigFile(config): Promise { if (config && typeof config.config === 'string') { - var filePath = config.config; - var ext = path.extname(filePath); - var absFilePath = path.resolve(process.cwd(), filePath); - return pify(fs).readFile(absFilePath, 'utf8').then(rawFile => { - if (ext === '.json') { + const filePath = config.config; + const ext = path.extname(filePath); + const absFilePath = path.resolve(process.cwd(), filePath); + return pify(fs) + .readFile(absFilePath, 'utf8') + .then(rawFile => { + if (ext === '.json') { + return Object.assign( + {}, + config, + processToc(JSON.parse(stripComments(rawFile)), absFilePath) + ); + } return Object.assign( {}, config, - processToc(JSON.parse(stripComments(rawFile)), absFilePath) + processToc(yaml.safeLoad(rawFile), absFilePath) ); - } - return Object.assign( - {}, - config, - processToc(yaml.safeLoad(rawFile), absFilePath) - ); - }); + }); } return Promise.resolve(config || {}); } function mergeConfig(config: Object): Promise { - config.parseExtension = (config.parseExtension || []) - .concat(['js', 'jsx', 'es5', 'es6']); + config.parseExtension = (config.parseExtension || []).concat([ + 'js', + 'jsx', + 'es5', + 'es6' + ]); return mergeConfigFile(config).then(mergePackage); } diff --git a/src/module_filters.js b/src/module_filters.js index bf5bd796b..59745bfca 100644 --- a/src/module_filters.js +++ b/src/module_filters.js @@ -1,10 +1,10 @@ /* @flow */ -var path = require('path'); -var micromatch = require('micromatch'); +const path = require('path'); +const micromatch = require('micromatch'); // Skip external modules. Based on http://git.io/pzPO. -var internalModuleRegexp = +const internalModuleRegexp = process.platform === 'win32' ? /* istanbul ignore next */ /^(\.|\w:)/ @@ -32,11 +32,11 @@ module.exports = { indexes: Array, options: Object ) { - var externalFilters = false; + let externalFilters = false; if (options.external) { externalFilters = indexes.map(index => { // grab the path of the top-level node_modules directory. - var topNodeModules = path.join(path.dirname(index), 'node_modules'); + const topNodeModules = path.join(path.dirname(index), 'node_modules'); return function matchGlob(file, pkg) { // if a module is not found, don't include it. if (!file || !pkg) { @@ -51,14 +51,14 @@ module.exports = { file = path.dirname(file); } // test the path relative to the top node_modules dir. - var p = path.relative(topNodeModules, file); + const p = path.relative(topNodeModules, file); return micromatch.any(p, options.external); }; }); } return function(id: string, file: string, pkg: Object) { - var internal = internalModuleRegexp.test(id); + const internal = internalModuleRegexp.test(id); return ( internal || (externalFilters && externalFilters.some(f => f(file, pkg))) ); diff --git a/src/nest.js b/src/nest.js index a2869d237..8ad7484a3 100644 --- a/src/nest.js +++ b/src/nest.js @@ -1,6 +1,6 @@ /* @flow */ -var _ = require('lodash'); +const _ = require('lodash'); const PATH_SPLIT = /(?:\[])?\./g; @@ -8,7 +8,7 @@ function removeUnnamedTags(tags: Array): Array { return tags.filter(tag => typeof tag.name === 'string'); } -var tagDepth = tag => tag.name.split(PATH_SPLIT).length; +const tagDepth = tag => tag.name.split(PATH_SPLIT).length; /** * Nest nestable tags, like param and property, into nested @@ -32,7 +32,7 @@ var tagDepth = tag => tag.name.split(PATH_SPLIT).length; * @param {Array} tags a list of tags * @returns {Object} nested comment */ -var nestTag = ( +const nestTag = ( tags: Array, errors: Array // Use lodash here both for brevity and also because, unlike JavaScript's @@ -52,7 +52,7 @@ var nestTag = ( } else { // The recursive case: try to find the child that owns // this tag. - let child = + const child = node.properties && node.properties.find( property => parts[0] === _.last(property.name.split(PATH_SPLIT)) @@ -99,7 +99,7 @@ var nestTag = ( * @param {Object} comment input comment * @returns {Object} nested comment */ -var nest = (comment: Comment) => +const nest = (comment: Comment) => Object.assign(comment, { params: nestTag(comment.params, comment.errors), properties: nestTag(comment.properties, comment.errors) diff --git a/src/output/highlighter.js b/src/output/highlighter.js index 90ce41731..37e5035e3 100644 --- a/src/output/highlighter.js +++ b/src/output/highlighter.js @@ -1,6 +1,6 @@ /* @flow */ -var visit = require('unist-util-visit'); -var hljs = require('highlight.js'); +const visit = require('unist-util-visit'); +const hljs = require('highlight.js'); /** * Adapted from remark-highlight.js diff --git a/src/output/html.js b/src/output/html.js index 0c004889e..c39453531 100644 --- a/src/output/html.js +++ b/src/output/html.js @@ -1,7 +1,7 @@ /* @flow */ -var path = require('path'); -var mergeConfig = require('../merge_config'); +const path = require('path'); +const mergeConfig = require('../merge_config'); /** * Formats documentation as HTML. @@ -28,7 +28,7 @@ function html(comments: Array, config?: Object) { config = {}; } return mergeConfig(config).then((config: DocumentationConfig) => { - var themePath = '../default_theme/'; + let themePath = '../default_theme/'; if (config.theme) { themePath = path.resolve(process.cwd(), config.theme); } diff --git a/src/output/markdown.js b/src/output/markdown.js index 1379d6f17..709a2e331 100644 --- a/src/output/markdown.js +++ b/src/output/markdown.js @@ -1,7 +1,7 @@ /* @flow */ -var remark = require('remark'), - markdownAST = require('./markdown_ast'); +const remark = require('remark'); +const markdownAST = require('./markdown_ast'); /** * Formats documentation as diff --git a/src/output/markdown_ast.js b/src/output/markdown_ast.js index 3096f096e..f479e6952 100644 --- a/src/output/markdown_ast.js +++ b/src/output/markdown_ast.js @@ -1,16 +1,16 @@ /* @flow */ -var u = require('unist-builder'), - remark = require('remark'), - mergeConfig = require('../merge_config'), - toc = require('remark-toc'), - hljs = require('highlight.js'), - GithubSlugger = require('github-slugger'), - LinkerStack = require('./util/linker_stack'), - rerouteLinks = require('./util/reroute_links'), - _formatType = require('./util/format_type'); +const u = require('unist-builder'); +const remark = require('remark'); +const mergeConfig = require('../merge_config'); +const toc = require('remark-toc'); +const hljs = require('highlight.js'); +const GithubSlugger = require('github-slugger'); +const LinkerStack = require('./util/linker_stack'); +const rerouteLinks = require('./util/reroute_links'); +const _formatType = require('./util/format_type'); -var DEFAULT_LANGUAGE = 'javascript'; +const DEFAULT_LANGUAGE = 'javascript'; /** * Given a hierarchy-nested set of comments, generate an remark-compatible @@ -33,26 +33,27 @@ function buildMarkdownAST( config: DocumentationConfig ) { // Configure code highlighting - var hljsOptions = config.hljs || {}; + const hljsOptions = config.hljs || {}; hljs.configure(hljsOptions); - var linkerStack = new LinkerStack( - config - ).namespaceResolver(comments, namespace => { - var slugger = new GithubSlugger(); - return '#' + slugger.slug(namespace); - }); + const linkerStack = new LinkerStack(config).namespaceResolver( + comments, + namespace => { + const slugger = new GithubSlugger(); + return '#' + slugger.slug(namespace); + } + ); - var formatType = _formatType.bind(undefined, linkerStack.link); + const formatType = _formatType.bind(undefined, linkerStack.link); - var generatorComment = [ + const generatorComment = [ u( 'html', '' ) ]; - var tableOfContentsHeading = [ + const tableOfContentsHeading = [ u('heading', { depth: 3 }, [u('text', 'Table of Contents')]) ]; @@ -159,7 +160,7 @@ function buildMarkdownAST( comment.examples.length > 0 && [u('strong', [u('text', 'Examples')])].concat( comment.examples.reduce(function(memo, example) { - var language = hljsOptions.highlightAuto + const language = hljsOptions.highlightAuto ? hljs.highlightAuto(example.description).language : DEFAULT_LANGUAGE; return memo @@ -268,7 +269,7 @@ function buildMarkdownAST( } function metaSection(comment: Comment) { - let meta = [ + const meta = [ 'version', 'since', 'copyright', @@ -358,7 +359,7 @@ function buildMarkdownAST( .filter(Boolean); } - var root = rerouteLinks( + let root = rerouteLinks( linkerStack.link, u( 'root', @@ -374,7 +375,9 @@ function buildMarkdownAST( ); if (config.markdownToc) { - root = remark().use(toc, { tight: true }).run(root); + root = remark() + .use(toc, { tight: true }) + .run(root); } return Promise.resolve(root); diff --git a/src/output/util/format_type.js b/src/output/util/format_type.js index 4e2ad406f..1be977525 100644 --- a/src/output/util/format_type.js +++ b/src/output/util/format_type.js @@ -1,6 +1,6 @@ /* @flow */ -var Syntax = require('doctrine-temporary-fork').Syntax, - u = require('unist-builder'); +const Syntax = require('doctrine-temporary-fork').Syntax; +const u = require('unist-builder'); /** * Shortcut to create a new text node @@ -26,7 +26,7 @@ function t(text) { * link('string').url // => 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String' */ function link(text, getHref, description) { - var href = getHref(text); + const href = getHref(text); if (href) { // TODO: this is a temporary fix until we drop remark 3.x support, // and then we should remove the 'href' property and only @@ -57,11 +57,11 @@ function link(text, getHref, description) { * @returns {Array} formatted remark AST */ function commaList(getHref, items, start, end, sep) { - var res = []; + let res = []; if (start) { res.push(t(start)); } - for (var i = 0, iz = items.length; i < iz; ++i) { + for (let i = 0, iz = items.length; i < iz; ++i) { res = res.concat(formatType(getHref, items[i])); if (i + 1 !== iz) { res.push(t(sep || ', ')); @@ -101,7 +101,7 @@ function decorate(formatted, str, prefix) { * // => 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String' */ function formatType(getHref: Function, node: ?Object) { - var result = []; + let result = []; if (!node) { return [t('any')]; diff --git a/src/output/util/formatters.js b/src/output/util/formatters.js index a5c523afe..27c7a4747 100644 --- a/src/output/util/formatters.js +++ b/src/output/util/formatters.js @@ -1,11 +1,11 @@ /* @flow */ -var remark = require('remark'), - html = require('remark-html'), - Syntax = require('doctrine-temporary-fork').Syntax, - u = require('unist-builder'), - _rerouteLinks = require('./reroute_links'), - highlighter = require('../highlighter'), - formatType = require('./format_type'); +const remark = require('remark'); +const html = require('remark-html'); +const Syntax = require('doctrine-temporary-fork').Syntax; +const u = require('unist-builder'); +const _rerouteLinks = require('./reroute_links'); +const highlighter = require('../highlighter'); +const formatType = require('./format_type'); /** * Create a formatter group, given a linker method that resolves @@ -15,9 +15,9 @@ var remark = require('remark'), * @returns {formatters} formatter object */ module.exports = function(getHref: Function) { - var rerouteLinks = _rerouteLinks.bind(undefined, getHref); + const rerouteLinks = _rerouteLinks.bind(undefined, getHref); - var formatters = {}; + const formatters = {}; /** * Format a parameter name. This is used in formatParameters @@ -48,7 +48,9 @@ module.exports = function(getHref: Function) { */ formatters.markdown = function(ast) { if (ast) { - return remark().use(html).stringify(highlighter(rerouteLinks(ast))); + return remark() + .use(html) + .stringify(highlighter(rerouteLinks(ast))); } return ''; }; @@ -71,7 +73,7 @@ module.exports = function(getHref: Function) { * @returns {string} potentially linked HTML */ formatters.autolink = function(text: string) { - var href = getHref(text); + const href = getHref(text); if (href) { // TODO: this is a temporary fix until we drop remark 3.x support, // and then we should remove the 'href' property and only diff --git a/src/output/util/linker_stack.js b/src/output/util/linker_stack.js index 49569fcce..1c621197d 100644 --- a/src/output/util/linker_stack.js +++ b/src/output/util/linker_stack.js @@ -1,5 +1,5 @@ /* @flow */ -var globalsDocs = require('globals-docs'); +const globalsDocs = require('globals-docs'); import { walk } from '../../walk'; /** @@ -25,8 +25,8 @@ function pathsLinker(paths /* Object */) { * @returns {*} any output */ function firstPass(fns: Array, input) { - for (var i = 0; i < fns.length; i++) { - var output = fns[i](input); + for (let i = 0; i < fns.length; i++) { + const output = fns[i](input); if (output) { return output; } @@ -85,7 +85,7 @@ class LinkerStack { * }); */ namespaceResolver(comments: Array, resolver: Function) { - var namespaces = {}; + const namespaces = {}; walk(comments, comment => { namespaces[comment.namespace] = true; }); diff --git a/src/output/util/reroute_links.js b/src/output/util/reroute_links.js index f5a189e37..378811563 100644 --- a/src/output/util/reroute_links.js +++ b/src/output/util/reroute_links.js @@ -1,5 +1,5 @@ /* @flow */ -var visit = require('unist-util-visit'); +const visit = require('unist-util-visit'); /** * Reroute inline jsdoc links in documentation diff --git a/src/parse.js b/src/parse.js index 256214f8d..5b5512c5a 100644 --- a/src/parse.js +++ b/src/parse.js @@ -1,7 +1,7 @@ /* @flow */ -var doctrine = require('doctrine-temporary-fork'); -var parseMarkdown = require('./parse_markdown'); +const doctrine = require('doctrine-temporary-fork'); +const parseMarkdown = require('./parse_markdown'); /** * Flatteners: these methods simplify the structure of JSDoc comments @@ -9,7 +9,7 @@ var parseMarkdown = require('./parse_markdown'); * information where appropriate. * @private */ -var flatteners = { +const flatteners = { abstract: flattenBoolean, /** * Parse tag @@ -76,7 +76,7 @@ var flatteners = { default: todo, defaultvalue: synonym('default'), deprecated(result, tag) { - let description = tag.description || 'This is deprecated.'; + const description = tag.description || 'This is deprecated.'; result.deprecated = parseMarkdown(description); }, flattenMarkdownDescription, @@ -114,7 +114,7 @@ var flatteners = { return; } - var example: CommentExample = { + const example: CommentExample = { description: tag.description }; @@ -236,7 +236,7 @@ var flatteners = { * @returns {undefined} has side-effects */ param(result, tag) { - var param: CommentTag = { + const param: CommentTag = { title: 'param', name: tag.name, lineNumber: tag.lineNumber // TODO: remove @@ -277,7 +277,7 @@ var flatteners = { * @returns {undefined} has side-effects */ property(result, tag) { - var property: CommentTag = { + const property: CommentTag = { title: 'property', name: tag.name, lineNumber: tag.lineNumber // TODO: remove @@ -322,7 +322,7 @@ var flatteners = { * @returns {undefined} has side-effects */ returns(result, tag) { - var returns: CommentTag = { + const returns: CommentTag = { description: parseMarkdown(tag.description), title: 'returns' }; @@ -363,7 +363,7 @@ var flatteners = { * @returns {undefined} has side-effects */ throws(result, tag) { - var throws = {}; + const throws = {}; if (tag.description) { throws.description = parseMarkdown(tag.description); @@ -569,7 +569,7 @@ function flattenKindShorthand(result, tag, key) { * [documentation schema](https://github.com/documentationjs/api-json) */ function parseJSDoc(comment: string, loc: ?Object, context: ?Object): Comment { - var result = doctrine.parse(comment, { + const result = doctrine.parse(comment, { // have doctrine itself remove the comment asterisks from content unwrap: true, // enable parsing of optional parameters in brackets, JSDoc3 style @@ -610,7 +610,7 @@ function parseJSDoc(comment: string, loc: ?Object, context: ?Object): Comment { result.tags.forEach(function(tag) { if (tag.errors) { - for (var j = 0; j < tag.errors.length; j++) { + for (let j = 0; j < tag.errors.length; j++) { result.errors.push({ message: tag.errors[j] }); } } else if (flatteners[tag.title]) { diff --git a/src/parse_markdown.js b/src/parse_markdown.js index 2e7d544f0..8acffd2e9 100644 --- a/src/parse_markdown.js +++ b/src/parse_markdown.js @@ -1,6 +1,6 @@ /* @flow */ -var remark = require('remark'); -var inlineTokenizer = require('./inline_tokenizer'); +const remark = require('remark'); +const inlineTokenizer = require('./inline_tokenizer'); /** * Parse a string of Markdown into a Remark @@ -11,7 +11,9 @@ var inlineTokenizer = require('./inline_tokenizer'); * @private */ function parseMarkdown(string: string) { - return remark().use(inlineTokenizer).parse(string); + return remark() + .use(inlineTokenizer) + .parse(string); } module.exports = parseMarkdown; diff --git a/src/parsers/javascript.js b/src/parsers/javascript.js index 37aa06087..1df33fbab 100644 --- a/src/parsers/javascript.js +++ b/src/parsers/javascript.js @@ -1,13 +1,13 @@ /* @flow */ -var _ = require('lodash'), - t = require('babel-types'), - parse = require('../parse'), - walkComments = require('../extractors/comments'), - walkExported = require('../extractors/exported'), - util = require('util'), - debuglog = util.debuglog('documentation'), - findTarget = require('../infer/finders').findTarget; +const _ = require('lodash'); +const t = require('babel-types'); +const parse = require('../parse'); +const walkComments = require('../extractors/comments'); +const walkExported = require('../extractors/exported'); +const util = require('util'); +const debuglog = util.debuglog('documentation'); +const findTarget = require('../infer/finders').findTarget; import { parseToAst } from './parse_to_ast'; @@ -36,11 +36,11 @@ function leftPad(str, width) { * @returns {Array} an array of parsed comments */ function parseJavaScript(data: Object, config: DocumentationConfig) { - var visited = new Set(); + const visited = new Set(); const commentsByNode = new Map(); - var ast = parseToAst(data.source); - var addComment = _addComment.bind(null, visited, commentsByNode); + const ast = parseToAst(data.source); + const addComment = _addComment.bind(null, visited, commentsByNode); return _.flatMap( config.documentExported @@ -66,12 +66,12 @@ function _addComment( ) { // Avoid visiting the same comment twice as a leading // and trailing node - var key = + const key = data.file + ':' + commentLoc.start.line + ':' + commentLoc.start.column; if (!visited.has(key)) { visited.add(key); - var context /* : { + const context /* : { loc: Object, file: string, sortKey: string, @@ -93,7 +93,7 @@ function _addComment( }); if (path.parentPath && path.parentPath.node) { - var parentNode = path.parentPath.node; + const parentNode = path.parentPath.node; context.code = data.source.substring(parentNode.start, parentNode.end); } } diff --git a/src/parsers/parse_to_ast.js b/src/parsers/parse_to_ast.js index 5bc2aa5bd..1cd3ca22f 100644 --- a/src/parsers/parse_to_ast.js +++ b/src/parsers/parse_to_ast.js @@ -1,8 +1,8 @@ /* @flow */ -var babylon = require('babylon'); +const babylon = require('babylon'); -var opts = { +const opts = { allowImportExportEverywhere: true, sourceType: 'module', plugins: [ diff --git a/src/serve/error_page.js b/src/serve/error_page.js index 0978561e8..b35b07cab 100644 --- a/src/serve/error_page.js +++ b/src/serve/error_page.js @@ -1,9 +1,9 @@ /* @flow */ /* eslint no-console: 0 */ -var File = require('vinyl'); -var ansiHTML = require('ansi-html'); +const File = require('vinyl'); +const ansiHTML = require('ansi-html'); -var template = +const template = ''; @@ -27,7 +27,7 @@ ansiHTML.setColors({ * @returns {Object} vinyl file object */ function errorPage(error: Error) { - var errorText = error.toString(); + let errorText = error.toString(); console.error(error); if (error.codeFrame) { errorText += '
' + ansiHTML(error.codeFrame) + '
'; diff --git a/src/serve/server.js b/src/serve/server.js index dfcf2fa0b..950110748 100644 --- a/src/serve/server.js +++ b/src/serve/server.js @@ -2,12 +2,12 @@ // This file triggers https://github.com/prettier/prettier/issues/1151 -var http = require('http'), - mime = require('mime'), - pify = require('pify'), - EventEmitter = require('events').EventEmitter, - liveReload = require('tiny-lr'), - sep = require('path').sep; +const http = require('http'); +const mime = require('mime'); +const pify = require('pify'); +const EventEmitter = require('events').EventEmitter; +const liveReload = require('tiny-lr'); +const sep = require('path').sep; declare type ServerFile = { relative: string, @@ -66,14 +66,14 @@ class Server extends EventEmitter { * @private */ handler(request: http.IncomingMessage, response: http.ServerResponse) { - var path = request.url.substring(1); + let path = request.url.substring(1); if (path === '') { path = 'index.html'; } - for (var i = 0; i < this._files.length; i++) { - var file = this._files[i]; - var filePath = file.relative.split(sep).join('/'); + for (let i = 0; i < this._files.length; i++) { + const file = this._files[i]; + const filePath = file.relative.split(sep).join('/'); if (filePath === path) { response.writeHead(200, { 'Content-Type': mime.getType(path) }); response.end(file.contents); diff --git a/src/smart_glob.js b/src/smart_glob.js index 64122caf6..6bf1d690b 100644 --- a/src/smart_glob.js +++ b/src/smart_glob.js @@ -1,8 +1,8 @@ /* @flow */ -var fs = require('fs'); -var path = require('path'); -var glob = require('glob'); -var shell = require('shelljs'); +const fs = require('fs'); +const path = require('path'); +const glob = require('glob'); +const shell = require('shelljs'); /** * Replace Windows with posix style paths @@ -11,8 +11,8 @@ var shell = require('shelljs'); * @returns {string} Converted filepath */ function convertPathToPosix(filepath) { - var normalizedFilepath = path.normalize(filepath); - var posixFilepath = normalizedFilepath.replace(/\\/g, '/'); + const normalizedFilepath = path.normalize(filepath); + const posixFilepath = normalizedFilepath.replace(/\\/g, '/'); return posixFilepath; } @@ -33,14 +33,14 @@ function convertPathToPosix(filepath) { * pathname is a directory. */ function processPath(extensions) { - var cwd = process.cwd(); + const cwd = process.cwd(); extensions = extensions || ['.js']; extensions = extensions.map(function(ext) { return ext.replace(/^\./, ''); }); - var suffix = '/**'; + let suffix = '/**'; if (extensions.length === 1) { suffix += '/*.' + extensions[0]; @@ -56,8 +56,8 @@ function processPath(extensions) { * @private */ return function(pathname) { - var newPath = pathname; - var resolvedPath = path.resolve(cwd, pathname); + let newPath = pathname; + const resolvedPath = path.resolve(cwd, pathname); if (shell.test('-d', resolvedPath)) { newPath = pathname.replace(/[/\\]$/, '') + suffix; @@ -74,7 +74,7 @@ function processPath(extensions) { * @returns {string[]} The equivalent glob patterns and filepath strings. */ function resolveFileGlobPatterns(patterns, extensions) { - var processPathExtensions = processPath(extensions); + const processPathExtensions = processPath(extensions); return patterns.map(processPathExtensions); } @@ -86,10 +86,10 @@ function resolveFileGlobPatterns(patterns, extensions) { * @returns Resolved absolute filenames. */ function listFilesToProcess(globPatterns: Array): Array { - var files = [], - added = new Set(); + const files = []; + const added = new Set(); - var cwd = process.cwd(); + const cwd = process.cwd(); /** * Executes the linter on a file defined by the `filename`. Skips @@ -106,11 +106,11 @@ function listFilesToProcess(globPatterns: Array): Array { } globPatterns.forEach(function(pattern) { - var file = path.resolve(cwd, pattern); + const file = path.resolve(cwd, pattern); if (shell.test('-f', file)) { addFile(fs.realpathSync(file)); } else { - var globOptions = { + const globOptions = { nodir: true, dot: true, cwd diff --git a/src/sort.js b/src/sort.js index d0dad9bf5..ee1344576 100644 --- a/src/sort.js +++ b/src/sort.js @@ -1,9 +1,9 @@ /* @flow */ -var parseMarkdown = require('./parse_markdown'); -var chalk = require('chalk'); -var path = require('path'); -var fs = require('fs'); +const parseMarkdown = require('./parse_markdown'); +const chalk = require('chalk'); +const path = require('path'); +const fs = require('fs'); /** * Sort two documentation objects, given an optional order object. Returns @@ -65,7 +65,7 @@ module.exports = function sortDocs(comments: Array, options: Object) { // Table of contents 'theme' entries: defined as objects // in the YAML list options.toc.forEach(walk.bind(null, [])); - var unfixed = []; + const unfixed = []; comments.forEach(function(comment) { let commentPath; if (!comment.memberof && (commentPath = paths[comment.name])) { diff --git a/src/walk.js b/src/walk.js index 28a3a2787..939960af4 100644 --- a/src/walk.js +++ b/src/walk.js @@ -12,7 +12,7 @@ export function walk(comments: Array, fn: Function, options: ?Object) { comments.forEach(comment => { fn(comment, options); - for (var scope in comment.members) { + for (const scope in comment.members) { walk(comment.members[scope], fn, options); } });