What is the correct JSDdoc declaration for company being a String in the code below?
fetch('https://api.github.com/users/mdo').then(res => res.json()).then(res => {
console.log(res.company);
});
I use WebStorm and it understandably underscores company as an Unresolved variable:
if I add
/** #namespace bogus.company **/
anywhere in the file, WebStorm is happy, but that doesn't make sense:
Is this a bug in WebStorm, or am I missing something about how JSDoc declarations are supposed to work?
Is JSDoc even supposed to be used for this use case?
If you check the inspection for unresolved javascript variable there is a Report undeclared properties as error option that you could uncheck.
I like to do something like this:
/**
* #param {Object} res
* #property {String} company
*/
function myOutput(res) {
console.log(res.company);
}
fetch('https://api.github.com/users/mdo')
.then(myToJson)
.then(myOutput);
But for small anonymous functions I wouldn't even bother. It's a weak warning so turn the inspection off or learn to live with it, I'd say. It's possible to cram in /** #param {*} something */ in anonymous functions as well, but often it only serves to reduce readability.
Another option is to make a dummy file soomething.js somewhere under your content-root with an anonymous function like:
(() => {
return {
"github-users-response" : {
"company" : "sample"
}
}
});
And now webstorm will figure that company actually is defined in your other files. You can even put it in a different content-root if you want to keep it separate from your project.
Related
I have developed a native NodeJS module (using the NAN helpers). Now I am wondering what is the best way to document it.
The methods the module exports exist only in the C++ source code, however I wish to export Javascript documentation.
EDIT: I found another way that I think is better:
All JSDoc needs is to be able to attach the doclet to SOMETHING, so you can actually just do this (if you ignore JSHint warning about expecting an assignment or call instead of expression):
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
* #class
*/
nativeStuff.MyCoolClass;
/**
* My Cool Method
* #function
* #param {String} [name] The argument
*/
nativeStuff.MyCoolClass.prototype.CoolMethod;
/**
* Some Other Value
* #type {String}
*/
nativeStuff.someStringValue;
module.exports = nativeStuff;
This has the advantage of working with IDE's (at least WebStorm) and not requiring you to copy or proxy the object itself. Note though that you have to explicitly tell it what kind of field each entry is (with #function or #class or #type) because it can't infer it automatically otherwise.
Original Answer
There are a couple ways I know of, though I admit none seem particularly elegant.
In the small adapter file where you require() the native parts of the code and make it available as a module, you can assign each component individually and document them that way:
var nativeStuff = require('some/native/stuff');
// If your module only has one thing
/**
* My Cool Class
* #class MyCoolClass
*/
module.exports = nativeStuff;
// If it has several things
module.exports = {
/**
* My cool class
* #class
*/
MyCoolClass: nativeStuff.MyCoolClass,
/**
* My Other Cool Member
*/
OtherCoolMember: nativeStuff.OtherCoolMember
};
You could document members of the class this way too if you want to pick apart the class and re-assemble it, but it gets kinda unwieldy the deeper you go.
The other way I know of is to wrap every class method in native JS, which comes with a (almost negligible) performance hit:
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
*/
class MyCoolClass {
constructor() {
this._nativeObj = new nativeStuff.MyCoolClass();
}
/**
* Some Cool Method
* #param {String} [name] My name
*/
coolMethod(name) {
return this._nativeObj(name);
}
}
module.exports = MyCoolClass;
(Note this also works in older JS versions, but ES6 classes make stuff way easier to understand visually :)
You also can try using the #typedef directive to define things since a doclet about a typedef can be separate from the object it describes, but I don't think typedef's can document methods or classes in general, they're just for data objects.
I had to create a simple documentation generator to scan comments in source code in Javadoc-like style: https://github.com/aspectron/gendoc
Here is a part of such documentation, that looks like this:
/**
#module crypto
**/
/**
#class Hash
Hash generator
#function Hash(algorithm)
#param algorithm {String}
Constructor. Initiaize hash generator with specified algorithm, see #getHashes
Throws exception on unknown algorithm
**/
v8pp::class_<hash_generator> hash_class(bindings.isolate(), v8pp::v8_args_ctor);
hash_class
/**
#function reset([algorithm])
#param [algorithm] {String}
#return {Hash}
Reset hash generator to initial state optionaly changing generator algorithm.
Throws exception on unknown algorithm.
**/
.set("reset", &hash_generator::reset_v8)
...
Finally I opted for a not very elegant solution. I have created a separate JavaScript file which only has methods that are exported by my native API.
This file looks like this:
/** #namespace AwesomeLibrary
*
* #description API overview
*/
AwesomeLibrary = {
/**
* #param {string} param Input parameter
* #return combobulates {#link param}
*/
combobulate: function (param) {}
}
Then I am using JsDoc to generate the documentation of the project and passing this JavaScript file as an input rather than my native code. Finally I bundle the documentation with the binary distribution of my module.
This solution is not ideal as the documentation and the source code have to be maintained separately, however it has the advantage of zero overhead and a (rather) clean file. I have also disabled the source code generation in JsDoc as this would be obviously quite useless and only show the empty stubs.
I'm working on a product which needs to conditionally expose an API to the end user. We're using the Closure Compiler for minification. The part of the API that I'm trying to expose is a function that calls a callback with a Result whose value is an object with certain properties.
Specifically, the function I'm trying to expose looks like this (in pseudo-jsdoc notation):
/**
* #type DocumentRenderResult {status: String, image?: HTMLImageElement|HTMLCanvasElement}
* #param {function(Result<DocumentRenderResult>)} callback
**/
function renderDocument (url, page, callback) {
}
And the Result class looks like this:
/**
* #template T
* #param {Boolean} ok
* #param {T} val
* #param {Error} err
**/
function Result (ok, val, err) {
this.ok = ok;
this.val = val;
this.err = err;
}
What I'd like is to expose both the Result object API - that is, the fact that there are ok, val, and err properties, and expose the renderDocument interface so that users providing a callback will be able to access the status and image properties.
One solution (possibly) is to use bracket notation everywhere, but since this is supposed to be only conditionally exposed (for certain end users), I'd like to separate the concept of whether it's minified or not from the code.
I think some combination of #implements and #export and an externs file can accomplish this, but I haven't figured it out.
Is what I'm trying to do possible?
There are 2 primary ways to handle this situation:
Without Closure-Library
Store all of your exports in a separate file that becomes the main entry point for the api exposed library. This methodology has no dependencies on external libraries. For an example of this, see my GeolocationMarker library.
With Closure-Library (or at least a part of it)
If you are willing to utilize a very small part of closure-library code in your project, you can use the #export annotation. #export annotations do nothing unless the compilation flag --generate_exports is specified.
When --generate_exports is used, the compiler will add the appropriate call to either closure-library's goog.exportProperty or goog.exportSymbol method.
/** #const */
var mynamespace = {};
/** #export */
mynamespace.maybeExposedMethod = function() {};
With the --generate_exports flag, the compiler will generate the code:
var mynamespace = {maybeExposedMethod:function() {}};
goog.exportSymbol("mynamespace.maybeExposedMethod",
mynamespace.maybeExposedMethod);
Instead of having to depend on all of closure-library. You can copy the definition for those 2 methods into your source. All that's needed is that they exist as those names.
Conditionally Renaming Record Types
Functions which return anonymous objects must be treated differently to prevent renaming. The best option here would be to define a record type in its own file. For the public api to block renaming, include the record definition as an extern. When you want the record properties to be renamed, include the definition as source.
my_typedefs.js
/** #typedef {{image: string, status: number}} */
var my_record_type;
my_method_def.js
/** #return {my_record_type} */
function my_method() {
return {
image: 'some_image.jpg',
status: 200
};
}
If my_typedefs.js is included in the compilation with the --js flag, the record properties will be renamed, but if it is included with the --externs flag, they will not be renamed.
I am using the Google Closure Compiler on a Drupal project right now. My Javascript is structured using the Javascript Module Pattern.
Because of the way Drupal works, I am compiling each JS file individually. Simple Compilation mode works well, but I would like to use Advanced Compilation on each file.
My files are all variations on
var FOO = (function(me, $, Drupal, undefined) {
function init (context, settings) {
do_sutff();
};
Drupal.behaviors['FOO'] = {
attach: init
};
return me;
}(FOO || {}, jQuery, Drupal));
My problem is that Drupal.behaviors is a specific object in Drupal, and the attach property also is a specific property. When a Drupal page renders, Drupal.behaviors gets looped through, and all of the attach functions are called with the proper arguments. In other words, I don't want anything renamed with the Drupal object.
When I use Advanced Compilation mode, I get
var c = function(a, d, b) {
b.b.FOO = {a:function() {
do_stuff()
}};
return a
}(c || {}, jQuery, Drupal);
I have tried many variations on trying to get the compiler to recognize the whole Drupal object as an extern without luck. No matter what I try, .behaviors and .attach always get renamed.
Is there a way to tell the compiler to keep its hands off an entire object?
There is no concept "Don't modify any properties on this object". You can however setup an extern such as:
/** #interface */
function DrupalBehavior() {}
DrupalBehavior.prototype.attach = function(){};
/** #constructor */
function DrupalObject () {}
/** #type {Object.<string, DrupalBehavior>} */
DrupalObject.prototype.behaviors = {};
Then, in your code:
var FOO = (
/**
* #param {Object} me
* #param {jQuery} $
* #param {DrupalObject} Drupal
* #param {*=} undefined
*/
function(me, $, Drupal, undefined) {
function init (context, settings) {
do_sutff();
};
Drupal.behaviors['FOO'] = {
attach: init
};
return me;
}(FOO || {}, jQuery, Drupal));
In this case the Drupal argument will be renamed, but the behaviors property and its associated attach sub-property will not be.
One note on jQuery: You are passing the jQuery namespace object into the function as a
parameter. Closure-compiler does not trace the type well in this object. The annotation I have listed would be for an instace of the jQuery object as opposed to the entire jQuery namespace. This is probably not what you intended. The only type-safe way to handle this in Closure-compiler is NOT to pass namespaces through function closure.
Update: After looking through the JavaScript Module Pattern post you linked, they encourage passing global namespace objects into function closures. This pattern has known problems with Closure-compiler. You will need to choose to either follow the pattern in this regard or opt for full compatibility with ADVANCED_OPTIMIZATIONS.
When I put a comment above my variable or function with #private in it what is it actually doing? I have looked at the documentation but I'm still not sure.
goog.provide('myproject');
/** #private */
myproject.foo = "bar";
I can still access it when I open up chrome's development tools (myproject.foo). And...
goog.require('myproject');
window.addEventListener('load', function() {
//this works.
document.body.textContent = myproject.foo;
});
The above code still set's the bodies textContent to equal "bar", even when compiled. So what does #private actually do?
The access control annotations #private, #protected, and #public are
directives for the Closure Compiler that help developers enforce the
desired level of visibility for properties and functions.
To emit warnings for access violations use the Compiler flag:
--jscomp_warning=visibility
To emit errors for access violations use the Compiler flag:
--jscomp_error=visibility
Access control annotations are enforced on a per file basis,
meaning that any properties annotated #private or #protected may be
accessed anywhere within the same file. Also note that the compiler removes
these annotations from the compiled code since they are not part of the
JavaScript language.
Example
file1.js
goog.provide('ns1');
/**
* Global private variable.
* #private
*/
ns1.global = 'foo';
alert('ns1.global = ' + ns1.global); // OK in same file.
/** #constructor */
ns1.Constructor = function() {
/** #private */
this.secret_ = ns1.global;
};
ns1.instance = new ns1.Constructor();
alert(ns1.instance.secret_); // No warning in same file.
file2.js
goog.provide('ns2');
goog.require('ns1');
alert('ns1.global = ' + ns1.global); // Not allowed.
ns2.instance2 = new ns1.Constructor();
alert(ns2.instance2.secret_); // Not allowed.
With the flag --jscomp_error=visibility set, Closure Compiler emits the
following errors.
ERROR - Access to private property global of ns1 not allowed here.
alert('ns1.global = ' + ns1.global);
^
ERROR - Access to private property secret_ of ns1.Constructor not allowed here.
alert(ns2.instance2.secret_);
^
See Visibility (private and protected fields) in the Google JavaScript
Style Guide.
cpeisert implied this in his answer, but just to be explicit: these visibility annotations don't modify your output at all.
Marking a function as #private does not hide it or make it any less accessible in the resulting code than the Compiler normally would, and any third-party code that you introduce at runtime will be able to invoke such functions.
The only access protection offered by these annotations is against code that you compile in with them.
Closure Compiler documentation clearly states: "Don't use Externs instead of Exports". Because Externs are very handy to use, I came down with a problem:
function Lib(){
//some initialization
}
Lib.prototype = {
invoke : function(str){
//this function is called from outside to invoke some of Lib's events
}
}
When using Closure Compiler with ADVANCED_OPTIMIZATIONS, function invoke is removed from the source. This could be prevented in two ways:
Adding the line after prototype definition:
Lib.prototype['invoke'] = Lib.prototype.invoke;
But this adds an ugly peace of code at the end of the output code:
Lib.prototype.invoke = Lib.prototype.g;
I managed to get rid of this by adding this line to the constructor:
this.invoke = this.invoke;
And this line to the externs file:
/**
* #param {String} str
*/
Lib.prototype.invoke = function(str){};
This way, Closure Compiler can't remove invoke function from the output code, because it is assigned by itself in the constructor, and also, it can't rename it, because it is defined in the externs file.
So witch method is better?
If you use JSDoc consistently, you could use the #export tag:
/**
* #param {String} str
* #export
*/
Lib.prototype.invoke = function(str){
//this function is called from outside to invoke some of Lib's events
};
and call the compiler with the --generate_exports flag.
This requires you to either include base.js from the Google Closure library, or to copy goog.exportSymbol and goog.exportProperty to your codebase.
Personally, I like defining interfaces in externs file and having my internal classes implement them.
// Externs
/** #interface */
function IInvoke {};
IInvoke.prototype.invoke;
/**
* #constructor
* #implements {IInvoke}
*/
function Lib(){
//some initialization
}
Lib.prototype = {
invoke : function(str){
//this function is called from outside to invoke some of Lib's events
}
}
You still export the constructor itself, but not the interface methods.