jscs-dev / jscs-jsdoc Goto Github PK
View Code? Open in Web Editor NEWJsDoc validation rules for jscs
License: MIT License
JsDoc validation rules for jscs
License: MIT License
At first glance they swapped name and type in @param
. But probably there are much more critical changes.
http://manual.qooxdoo.org/2.1/pages/development/api_jsdoc_ref.html
It's cool to support all things but implementing at least swapping of name and type would be harder than it looks like because of comment-parser
waits for "name {type} desc" for all tag types. But we can patch this. Need to look at it much closer after big wave of refactoring.
Given:
/**
* Create a new precondition.
*
* @param {Object} parameter the parameter value
* @param {String} name the parameter name
* @return {ObjectPreconditions} the precondition
*/
Preconditions.requireThat = function(parameter, name)
{
ObjectPreconditions.instanceOf(name, "name", String);
if (Utilities.instanceOf(parameter, String))
return new StringPreconditions(parameter, name);
if (Array.isArray(parameter))
return new ArrayPreconditions(parameter, name);
return new ObjectPreconditions(parameter, name);
};
where ArrayPreconditions
and StringPreconditions
both subclass ObjectPreconditions
as follows:
/**
* @class ObjectPreconditions
*/
function ObjectPreconditions(parameter, name)
{
...
}
/**
* @class StringPreconditions
* @extends ObjectPreconditions
*/
function StringPreconditions(parameter, name)
{
...
}
StringPreconditions.prototype = Object.create(ObjectPreconditions.prototype);
StringPreconditions.prototype.constructor = ObjectPreconditions;
I am expecting to be able to return ObjectPreconditions
without having to specify every possible subclass. From the end-user's point of view, the subclasses are an implementation detail.
It looks like the code to parse type expressions from the comments does not work properly with nested curly braces:
// test.js
/**
* @return {{a: number, b: string}}
*/
function foo() {
return {};
}
// .jscsrc
{
"additionalRules": [
"node_modules/jscs-jsdoc/lib/rules/*.js"
],
"jsDoc": {
"checkTypes": true
}
}
// jscs --config .jscsrc test.js
Invalid JsDoc type definition at test.js :
1 |/**
2 | * @return {{a: number, b: string}}
-----------^
3 | */
4 |function foo() {
1 code style error found.
If you look at the string that gets passed to jsDocParseType you will notice that it is {a: number, b: string
, so it is missing the closing curly brace.
I am getting:
jsDoc checkTypes: Expected valid type instead of URI.<operator>[] at Operator.js
What determines whether a type is valid
? In the above case, a type called URI
is defined (by URI.js) and I am attempting to denote what kind of resource the URI points to. I am more than happy to change the syntax I am using but I am not sure what you expect.
As defined in JSDoc:
Given:
/**
* Land and the buildings on it, along with its natural resources such as crops, minerals, or water.
*
* @class
* @property {uri.<property>} uri the property's URI
* @property {String} listing the URI of the property listing
* @property {String} address the property address
* @property {String} postalCode the property postal code
* @property {Number} askingPrice the asking price for the property
* @property {String} currency the currency of all prices
* @property {Number} municipalEvaluationPrice the municipal evaluation price of the property (null if not set)
* @property {Number} municipalEvaluationYear the municipal evaluation year (null if not set)
* @property {Number} schoolTaxes the annual school taxes (null if not set)
* @property {Number} municipalTaxes the annual municipal taxes (null if not set)
* @property {Number} energyCost the annual energy cost (null if not set)
* @property {Number} rooms the number of rooms in the property
* @property {Number} bedrooms the number of bedrooms in the property (null if not set)
* @property {Number} bathrooms the number of bathrooms in the property (null if not set)
* @property {Number} powderRooms the number of powder rooms in the property (null if not set)
* @property {Number} garages the number of garages in the property (null if not set)
* @property {Number} constructionYear the year the property was constructed (null if not set)
* @property {Number} lotArea the lot area, in meters^2 (null if not set)
*
* @param {uri.<property>} uri the property's URI
* @param {String} listing the URI of the property listing
* @param {String} address the property address
* @param {String} postalCode the property postal code
* @param {Number} askingPrice the asking price for the property
* @param {String} currency the currency of all prices
* @param {Number} municipalEvaluationPrice the municipal evaluation price of the property (null if not set)
* @param {Number} municipalEvaluationYear the municipal evaluation year (null if not set)
* @param {Number} schoolTaxes the annual school taxes (null if not set)
* @param {Number} municipalTaxes the annual municipal taxes (null if not set)
* @param {Number} energyCost the annual energy cost (null if not set)
* @param {Number} rooms the number of rooms in the property
* @param {Number} bedrooms the number of bedrooms in the property (null if not set)
* @param {Number} bathrooms the number of bathrooms in the property (null if not set)
* @param {Number} powderRooms the number of powder rooms in the property (null if not set)
* @param {Number} garages the number of garages in the property (null if not set)
* @param {Number} constructionYear the year the property was constructed (null if not set)
* @param {Number} lotArea the lot area, in meters^2 (null if not set)
* @return {Property} the property
*/
function Property(uri, listing, address, postalCode, askingPrice, currency, municipalEvaluationPrice,
municipalEvaluationYear, municipalTaxes, schoolTaxes, energyCost, rooms, bedrooms, bathrooms, powderRooms,
garages, constructionYear, lotArea)
{
...
}
I get tons of warnings like:
Invalid JsDoc @param argument name at ../../../target/classes/js/net/Property.js :
38 | * @param {Number} municipalEvaluationPrice the municipal evaluation price of the property (null if not set)
39 | * @param {Number} municipalEvaluationYear the municipal evaluation year (null if not set)
40 | * @param {Number} schoolTaxes the annual school taxes (null if not set)
-------------^
41 | * @param {Number} municipalTaxes the annual municipal taxes (null if not set)
42 | * @param {Number} energyCost the annual energy cost (null if not set)
It's not clear why the warnings begin at this line while previous lines pass.
Action items:
jsDocName
and param.name
. Knowing these values would certainly help us figure out whether this is user-error or a bug in the plugin.https://github.com/apidoc/apidoc/
Blocked by #69
According to jscs-dev/node-jscs#245 we should check it all and describe in docs.
e.g.
/**
* @param {Object} person comment
* - {String} title comment
* - {Number} [age] comment
*/
I'm using JSDoc3 (is that compatible?) and am getting uncaught exceptions on a fairly large codebase. I'm not sure how to detect which file and jsdoc entry in my code is causing the exceptions however. In any case, the nature of them is as follows:
TypeError: Cannot call method 'toLowerCase' of undefined
at Object.jsDocMatchType [as match] (/myproject/node_modules/jscs-jsdoc/lib/jsdoc-helpers.js:129:29)
If on that line, I detect that and continue
the loop iteration (effectively skipping these errors), I get the next uncaught error:
TypeError: Cannot read property 'type' of null
at Object.jsDocMatchType [as match] (/myproject/node_modules/jscs-jsdoc/lib/jsdoc-helpers.js:135:32)
Please note that the line number there is skewed by a few because of the continue
statement I injected above it. The error is about the usage of if (!argument.value.type) {
.
Is there anything I can do to figure out what chunk of JSDoc caused this?
I've got checkRedundantReturns
enabled. So far I've gotten a warning for @return {undefined}
(which I understand) but then I just got it for:
/**
* @return {UnauthorizedException} the exception
*/
function UnauthorizedException()
{
...
}
Why is the @return
redundant? Isn't it possible for the constructor to return a subclass?
if I have params with properties and more than one argument I have wrong detection for redundant param statement.
Example of code linting fails on jscs-jsdoc v 0.4.0:
/**
* Example function
* @param {Object} options some options
* @param {Number} options.id some id
* @param {String} options.filename some filename
* @param {Array} rest rest arguments
* @returns {Boolean} to be or not to be
*/
function hello(options, rest) {
return (options.filename) ? true : false;
}
Fail log:
Message:
redundant param statement at example.js :
1 |/**
--------^
2 | * Example function
3 | * @param {Object} options some options
If code looks like this it works like a charm:
/**
* Example function
* @param {Object} options some options
* @param {Number} options.id some id
* @param {String} options.filename some filename
* @returns {Boolean} to be or not to be
*/
function hello(options) {
return (options.filename) ? true : false;
}
/**
* @function
* @this AuthenticationsPage
* @return {Promise} a Promise that returns {@code undefined} on success and {@code Error} on
* failure
*/
This is a function, not a constructor, yet I am getting the Redundant JsDoc @returns error on the @return line.
You asked what kind of JsDoc I am using... I'm not actually producing any documentation from this yet. I am currently coding this (mostly) blind using http://usejsdoc.org/ as reference and https://netbeans.org/ for some light syntax validation (they have some built-in JsDoc engine but it's not clear which).
__constructor
__proto__
see also https://github.com/jscs-dev/node-jscs/blob/master/lib/rules/disallow-dangling-underscores.js#L24
Add option to add your own exceptions.
For example:
/**
* Shouldn't report
* @param {String} a
* @returns {String}
*/
function (a) {
if (a.indexOf('x')) {
return '?';
}
return a + 'b';
}
/**
* But this should report
* @param {Number} b
* @returns {String}
*/
function (b) {
return b.quantity / 2;
}
It would be awesome if the plugin supported (i.e., validated) Closure Compiler type expressions, for instance via catharsis.
Could be toggleable like so:
"jsDoc": {
"checkTypes": "closurecompiler"
// or
"checkTypes": "jsdoc"
// or
"checkTypes": true // defaults to "jsdoc"
}
and likewise for @return
annotations.
Check configuration and throw errors if come values are not valid.
As well as in jscs
it should be done here.
Using JSCS v1.7.3
With jsDoc options:
"jsDoc": {
"checkParamNames": true,
"checkRedundantParams": true,
"requireParamTypes": true,
"checkReturnTypes": true,
"requireReturnTypes": true,
"checkTypes": true,
"checkRedundantReturns": true,
"checkRedundantAccess": true,
"leadingUnderscoreAccess": "private"
}
This code in v0.0.19:
/**
* Test
*
* @param {String} mystr
* @return {String}
*/
exports.testStr = function(mystr) {
'use strict';
return mystr;
};
Validates as:
↳ jscs server/lib/test.js
redundant param statement at server/lib/test.js :
1 |/**
--------^
2 | * Test
3 | *
missing param name at server/lib/test.js :
3 | *
4 | * @param {String} mystr
5 | * @return {String}
-----------^
6 | */
7 |exports.testStr = function(mystr) {
2 code style errors found.
v0.0.16 will pass the checks
Bunch of these options could be very nice to support at server-side checking
// .jscsrc
{
"additionalRules": [
"node_modules/jscs-jsdoc/lib/rules/*.js"
],
"jsDoc": {
"checkReturnTypes": true
}
}
// test.js
/**
* @return {Foo}
*/
function getFoo() {
return new Bar();
}
TypeError: Cannot call method 'replace' of undefined
at renderLine (/home/pigullar/workspaces/tmp/node_modules/jscs/lib/errors.js:168:17)
at Object.Errors.explainError (/home/pigullar/workspaces/tmp/node_modules/jscs/lib/errors.js:99:13)
at /home/pigullar/workspaces/tmp/node_modules/jscs/lib/reporters/console.js:16:36
at Array.forEach (native)
at /home/pigullar/workspaces/tmp/node_modules/jscs/lib/reporters/console.js:14:35
at Array.forEach (native)
at module.exports (/home/pigullar/workspaces/tmp/node_modules/jscs/lib/reporters/console.js:9:22)
at /home/pigullar/workspaces/tmp/node_modules/jscs/lib/cli.js:144:13
at Array.0 (/home/pigullar/workspaces/tmp/node_modules/jscs/node_modules/vow/lib/vow.js:576:56)
at Object.callFns [as _onImmediate] (/home/pigullar/workspaces/tmp/node_modules/jscs/node_modules/vow/lib/vow.js:1176:35)
According to jscs-dev/node-jscs#210
Hi,
How do you enable/disable individual rules? I have been able to disable either all rules with:
// jscs:disable
And I have been able to disable all jsDoc rules with:
// jscs:disable jsDoc
But I have not figured out how to disable select jsdoc rules while using the others. For neither of the following work:
// jscs:disable checkRedundantParams
// jscs:disable jsDoc.checkRedundantParams
Is there a way to do what I am looking to do?
Thanks
It would be nice if the plugin could also validate annotation names, e.g.:
/**
* @pubblic
*/
would fail because no such tag exists (typo).
Ideally, there would be various ways to configure this:
"jsDoc": {
"checkAnnotations": "jsdoc" // whitelists JSDoc tags
// or
"checkAnnotations": "jsduck" // whitelists JSDuck tags
// or
"checkAnnotations": "closurecompiler" // whitelist Closure Compiler tags
}
Might be a good idea to add version support from the get-go, so use jsdoc3
, jsduck4
, jsduck5
etc.
Example straight from the JSDoc docs:
// foo.js
/**
* Creates a new Person.
* @class
*/
function Person() {
}
var p = new Person();
Output from JSCS Grunt task:
Running "jscs:lib" (jscs) task
incomplete data in tag class at src/foo.js :
1 |/**
2 | * Creates a new Person.
3 | * @class
-----------^
4 | */
5 |function Person() {
Relevant portion of .jscsrc
:
"plugins": [
"jscs-jsdoc"
],
"jsDoc": {
"checkAnnotations": "jsdoc3",
"checkParamNames": true,
"checkRedundantParams": true,
"requireParamTypes": true
}
Relevant versions in use:
├─┬ [email protected]
│ ├─┬ [email protected]
├─┬ [email protected]
├─┬ [email protected]
In follow of #35
According to jscs-dev/node-jscs#344
Not all functions are checked for missing jsdoc tag definitions.
I have created a minimum example:
MyNamespace = MyNamespace || {};
MyNamespace.Test = function () {
};
(function () {
MyNamespace.Test.prototype.foo = function() {
function bar() {
}
};
})();
Using a .jscsrc configuration like this:
{
"additionalRules": [
"node_modules/jscs-jsdoc/lib/rules/*.js"
],
"requireSpaceAfterKeywords": ["function"],
"jsDoc": {
"enforceExistence": true
}
}
Produces these errors:
js\\Test.js: line 3, col 27, Should be one space instead of 0, after "function" keyword
js\\Test.js: line 7, col 45, Should be one space instead of 0, after "function" keyword
js\\Test.js: line 8, col 8, jsdoc definition required
Clearly JSCS detects the function definitions in lines 3 and 7, but JSCS-JSDoc fails to report the missing JSDoc tags
My team would like to use jscs-jsdoc. However, we generally have a coding practice that involves both using anonymous functions to create our methods, and using frameworks like Backbone, Marionette, and underscore to create our object prototypes. With this in mind, is there any way to create a rule that either allows you to enforce the existence of jsdoc on anonymous functions, or perhaps to do so when anonymous functions are members of objects?
Given:
/**
* @typedef {Object} UsersState
*
* @property {String} id the DOM id of the component that generated the state
* @property {Object} state the page's state
*/
/**
* @return {UsersState} the page's state
*/
Users.prototype.getState = function()
{
return {
id: "main",
state:
{
table: this.table.getState(),
addUserModal: this.addUserModal.getState(),
editUserModal: this.editUserModal.getState()
}
};
};
The function returns the correct type (following duck typing) yet jscs-jsdoc fails with:
Wrong returns value at ../../../target/classes/js/html/Users.js :
322 | Users.prototype.getState = function()
323 | {
324 | return {
------------------^
325 | id: "main",
326 | state:
I believe my syntax is correct because http://justjson.blogspot.ca/2013/07/jsdoc-documenting-configparamcustom.html does the same for the @returns {JustJson.Greeting.Config}
example.
Could this be a rule?
* @param {string} somebody - Somebody's name.
vs.
* @param {string} somebody Somebody's name.
When my JSDoc contains * @returns {string|null}
or * @returns {?string}
, a return null;
statement in the following function is not allowed, giving me:
Wrong returns value at lib/myfile.js :
57 |MyClass.prototype.getIp = function (version) {
58 | if (!this.addresses) {
59 | return null;
-----------------^
Using JSCS v1.7.3
my jsDoc options:
"jsDoc": {
"checkParamNames": true,
"checkRedundantParams": true,
"requireParamTypes": true,
"checkReturnTypes": true,
"requireReturnTypes": true,
"checkTypes": true,
"checkRedundantReturns": true,
"checkRedundantAccess": true,
"leadingUnderscoreAccess": "private"
}
jscs-jsdoc v0.0.17 throws:
jscs server/**/*.js
TypeError: Cannot call method 'iterateByType' of null
at Object.validateCheckParamNames (/node_modules/jscs-jsdoc/lib/rules/validate-jsdoc/check-param-names.js:14:16)
at /node_modules/jscs-jsdoc/lib/rules/validate-jsdoc.js:96:27
at Array.forEach (native)
at /node_modules/jscs-jsdoc/lib/rules/validate-jsdoc.js:95:32
at Array.forEach (native)
at Object.JsFile.iterateNodesByType (/usr/local/lib/node_modules/jscs/lib/js-file.js:284:42)
at /node_modules/jscs-jsdoc/lib/rules/validate-jsdoc.js:86:18
at Array.forEach (native)
at Object.module.exports.check (/node_modules/jscs-jsdoc/lib/rules/validate-jsdoc.js:78:29)
at null.<anonymous> (/usr/local/lib/node_modules/jscs/lib/string-checker.js:285:26)
v0.0.16 works as expected.
Just because.
Also it should fix multiline params parsing issue: jscs-dev/node-jscs#245
Like employees[].name
jscs-jsdoc can currently not be installed with the latest version of jscs. Very unfortunate, because this plugin seems pretty awesome! I wanna try it out :) Can this be resolved?
npm ERR! peerinvalid The package jscs does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants [email protected]
JSCS checks for additional rules relative to the config path or process working directory. Files not found are silently ignored (even if they were specified with full path instead of *.js).
according to JSDoc manual, the example tag [http://usejsdoc.org/tags-example.html] should be available.
Am I missing somthing here:
/**
* @example
* // some sample comment
* aFunctionSampleCall({a:1, b:2, c:3, e:null}, {a:4, d:5}, {b:6, c:7});
*/
* @param {Array} arr
vs.
* @param {array} arr
maybe an exception for string, number, etc?
Current version is 0.0.13
. By semver it means — don't use it, it is in the early development state.
I propose releasing 1.0.0
version of the package.
Given:
/**
* Returns the sum of all numbers passed to the function.
* @param {...number} num - A positive or negative number.
*/
function sum(num) {
var i = 0, n = arguments.length, t = 0;
for (; i < n; i++) {
t += arguments[i];
}
return t;
}
from http://usejsdoc.org/tags-param.html you will get "Invalid JsDoc type definition" for the @param
. It looks like the varargs syntax is not recognized.
According to discussion in #52
Instead of true/false it should have explicit checking type.
True and false should be deprecated values in future and left as is for now.
upd: To use jsdoc3/jsduck5 as a base with some special subsets like closurecompiler or apidoc.
It's a check now for a several @access
tags (or analogues) in jsdoc.
It should also check somehow for dangling underscores (except __proto__
, __constructor
, etc.).
Invalid:
/**
* Some description
* @returns {srting}
*/
Valid:
/**
* Some description
*
* @returns {srting}
*/
Since updating to 0.3.x
, I get a lot of linting errors where there previously were none.
Config:
jsDoc: {
checkAnnotations: 'closurecompiler',
checkParamNames: true,
checkRedundantParams: true,
checkRedundantReturns: true,
requireParamTypes: true,
requireReturnTypes: true
}
Example that produces the error:
/**
* Pad the given string so that it is at least `len` length.
* @param {String} str
* @param {Number} len
* @return {String}
*/
function padUntil(str, len) {
return str + Array(len - str.length).join(' ');
}
It's not clear to me what the problem is now.
// test.js
module.exports = {
/**
* @return {foo.Bar}
*/
foo: function () {
return new foo.Bar();
}
};
// .jscsrc
{
"additionalRules": [
"node_modules/jscs-jsdoc/lib/rules/*.js"
],
"jsDoc": {
"checkParamNames": true,
"checkRedundantParams": true,
"requireParamTypes": true,
"checkReturnTypes": true,
"requireReturnTypes": true,
"checkTypes": true,
"checkRedundantReturns": true,
"checkRedundantAccess": true,
"leadingUnderscoreAccess": "private",
"enforceExistence": true
}
}
// command line
node_modules/jscs/bin/jscs --config .jscsrc test.js
TypeError: Cannot call method 'toLowerCase' of undefined
at Object.jsDocMatchType [as match] (/home/pigulla/node_modules/jscs-jsdoc/lib/jsdoc-helpers.js:222:87)
at /home/pigulla/node_modules/jscs-jsdoc/lib/rules/validate-jsdoc/returns.js:74:31
at Array.forEach (native)
at Object.validateReturnsTag (/home/pigulla/node_modules/jscs-jsdoc/lib/rules/validate-jsdoc/returns.js:73:35)
at /home/pigulla/node_modules/jscs-jsdoc/lib/jsdoc-helpers.js:72:23
at Array.forEach (native)
at Object.jsDocForEachTag [as forEachTag] (/home/pigulla/node_modules/jscs-jsdoc/lib/jsdoc-helpers.js:39:24)
at Object.<anonymous> (/home/pigulla/node_modules/jscs-jsdoc/lib/jsdoc-helpers.js:70:20)
at /home/pigulla/node_modules/jscs-jsdoc/lib/rules/validate-jsdoc.js:53:37
at Array.forEach (native)
Just look these cases
/**
* would report:
* expected message but got `message`
*
* @param {String} `message`
*/
function methodOne(message) {}
/**
* would report:
* expected required but got <required>
*
* @param {String} <required>
* @param {Object} [optional]
*/
function methodTwo(required, optional) {}
/**
* would report:
* expected required but got `<required>`
* expected optional but got `[optional]`
*
* @param {String} `<required>`
* @param {Object} `[optional]`
*/
function methodThree(required, optional) {}
Need explanation? Reports because of **, <, >** chars in
tag.name.value`'s
The solution is to add escaping just before if statement
tag.name.value = tag.name.value.replace(/[\`\<\[\]\>]/g, '');
We use these because we use code comments to generate markdown docs automagically.
Want PR?
I have a declaration like this:
/**
* Creates a processor.
* @param {!IOptions} options
* @param {!ISeries} series
* @param {!IChapter} chapter
* @return {IProcessor}
*/
With the following settings:
"jsDoc": {
"checkAnnotations": "closurecompiler",
"checkParamNames": true,
"checkRedundantAccess": true,
"checkRedundantParams": true,
"checkRedundantReturns": true,
"checkReturnTypes": true,
"checkTypes": "strictNativeCase",
"enforceExistence": true,
"leadingUnderscoreAccess": true,
"requireParamTypes": true,
"requireReturnTypes": true
},
And I get a warning that @returnis unavailable. It should be
@return, not
@returns` for closure.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.