How do I document NodeJS native (V8) modules? - javascript

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.

Related

Javascript Dot-Syntax function disappears in listen callback

I'm trying to update Annotorious (https://annotorious.github.io/#) to the latest version of Closure / Javascript.
When I compile it with "SIMPLE" optimizations, dot-syntax functions seem to disappear when goog.events.listen callbacks are invoked. Here's an example:
Here's the "main":
goog.provide('annotorious.Annotorious');
...
/**
* The main entrypoint to the application. The Annotorious class is instantiated exactly once,
* and added to the global window object as 'window.anno'. It exposes the external JavaScript API
* and internally manages the 'modules'. (Each module is responsible for one particular media
* type - image, OpenLayers, etc.)
* #constructor
*/
annotorious.Annotorious = function() {
/** #private **/
this._isInitialized = false;
/** #private **/
this._modules = [ new annotorious.mediatypes.image.ImageModule() ];
...
In another file (they're all compiled together), we have this:
goog.provide('annotorious.Annotation');
goog.require('annotorious.shape');
/**
* A 'domain class' implementation of the external annotation interface.
* #param {string} src the source URL of the annotated object
* #param {string} text the annotation text
* #param {annotorious.shape.Shape} shape the annotated fragment shape
* #constructor
*/
annotorious.Annotation = function(src, text, shape) {
this.src = src;
this.text = text;
this.shapes = [ shape ];
this['context'] = document.URL; // Prevents dead code removal
}
So we start up the code, and at some point we end in the editor for the annotation, listening for a "Save" button:
goog.provide('annotorious.Editor');
....
/**
* Annotation edit form.
* #param {Object} annotator reference to the annotator
* #constructor
*/
annotorious.Editor = function(annotator) {
this.element = goog.soy.renderAsElement(annotorious.templates.editform);
....
/** #private **/
//this._btnSave = goog.dom.query('.annotorious-editor-button-save', this.element)[0];
this._btnSave = this.element.querySelector('.annotorious-editor-button-save');
...
goog.events.listen(this._btnSave, goog.events.EventType.CLICK, function(event) {
event.preventDefault();
var annotation = self.getAnnotation();
annotator.addAnnotation(annotation);
annotator.stopSelection();
if (self._original_annotation)
annotator.fireEvent(annotorious.events.EventType.ANNOTATION_UPDATED, annotation, annotator.getItem());
else
annotator.fireEvent(annotorious.events.EventType.ANNOTATION_CREATED, annotation, annotator.getItem());
self.close();
});
If I put a breakpoint at "goog.events.listen(this._btnSave...", and type "annotorious.Annotation", I get what I expect:
In fact, it has all kinds of methods:
Then I let the code go, and break in the listener (event.preventDefault();, etc, above):
Now, all the dot-syntax methods are gone.
This of course causes crashes later on.
All of these files are compiled together.
This happens for all callbacks - 'load' events, other ux callbacks, etc.
This must have worked in prior versions of Closure / JS.
What could be causing this?
Thanks!
Ok, I was able to resolve the problem by adding "--assume_function_wrapper" to the closure compiler command line.
Previously, I was compiling the package using Plovr. However, since Plovr hasn't been updated in a long time, I switched to using the closure compiler natively.
Apparently either Plovr provided '--assume_function_wrapper' internally or the version of the compiler Plovr used didn't break the functions as described.
As #john suggests above I'll bet '--assume_function_wrapper' keeps goog.provide from "destroying" namespaces by re-declaring them.

How to document ECMA6 classes with JSDoc?

Background
I have a project in Nodejs using ECMA6 classes and I am using JSDoc to comment my code, as to make it more accessible to other developers.
However, my comments are not well accepted by the tool, and my documentation is a train wreck.
Problem
My problem is that I don't know how to document ECMA6 classes with JSDoc and I can't find any decent information.
What I tried
I tried reading the official example but I find it lacking and incomplete. My classes have members, constant variables and much more, and I don't usually know which tags to use for what.
I also made an extensive search in the web, but most information I found is prior to 2015 where JSDocs didn't support ECMA6 scripts yet. Recent articles are scarce and don't cover my needs.
The closest thing I found was this GitHub Issue:
https://github.com/jsdoc3/jsdoc/issues/819
But it is outdated by now.
Objective
My main objective is to learn how to document ECMA6 classes in NodeJS with JSDoc.
I have a precise example that I would like to see work properly:
/**
* #fileOverview What is this file for?
* #author Who am I?
* #version 2.0.0
*/
"use strict";
//random requirements.
//I believe you don't have to document these.
let cheerio = require('cheerio');
//constants to be documented.
//I usually use the #const, #readonly and #default tags for them
const CONST_1 = "1";
const CONST_2 = 2;
//An example class
class MyClass {
//the class constructor
constructor(config) {
//class members. Should be private.
this.member1 = config;
this.member2 = "bananas";
}
//A normal method, public
methodOne() {
console.log( methodThree("I like bananas"));
}
//Another method. Receives a Fruit object parameter, public
methodTwo(fruit) {
return "he likes " + fruit.name;
}
//private method
methodThree(str) {
return "I think " + str;
}
}
module.exports = MyClass;
Question
Given this mini class example above, how would you go about documenting it using JSDoc?
An example will be appreciated.
Late answer, but since I came across this googling something else I thought I'd have a crack at it.
You've probably found by now that the JSDoc site has decent explanations and examples on how to document ES6 features.
Given that, here's how I would document your example:
/**
* module description
* #module MyClass
*/
//constants to be documented.
//I usually use the #const, #readonly and #default tags for them
/** #const {String} [description] */
const CONST_1 = "1";
/** #const {Number} [description] */
const CONST_2 = 2;
//An example class
/** MyClass description */
class MyClass {
//the class constructor
/**
* constructor description
* #param {[type]} config [description]
*/
constructor(config) {
//class members. Should be private.
/** #private */
this.member1 = config;
/** #private */
this.member2 = "bananas";
}
//A normal method, public
/** methodOne description */
methodOne() {
console.log( methodThree("I like bananas"));
}
//Another method. Receives a Fruit object parameter, public
/**
* methodTwo description
* #param {Object} fruit [description]
* #param {String} fruit.name [description]
* #return {String} [description]
*/
methodTwo(fruit) {
return "he likes " + fruit.name;
}
//private method
/**
* methodThree description
* #private
* #param {String} str [description]
* #return {String} [description]
*/
methodThree(str) {
return "I think " + str;
}
}
module.exports = MyClass;
Note that #const implies readonly and default automatically. JSDoc will pick up the export, the #class and the #constructor correctly, so only the oddities like private members need to be specified.
For anyone visiting this question in 2019:
The answer given by #FredStark is still correct, however, the following points should be noted:
Most/all of the links in this page are dead. For the documentation of the JSDoc, you can see here.
In many IDEs or code editors (such as VSCode), you will find auto-completions such as #class or #constructor which are not necessary for the case of ES6 classes since these editors will recognize the constructor after the new keyword.

Prevent Closure Compiler from renaming properties without using bracket notation

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.

JSDoc links to callback function

I have decided to use JSDoc to document a project I am working on. While reading the usage guide and questions here I still feel that I am not grasping some of the core concepts of JSDoc and I illustrated my incompetence in the following example: http://jsfiddle.net/zsbtykpv/
/**
* #module testModule
*/
/**
* #constructor
*/
var Test = function() {
/**
* #callback myCallback
* #param {Object} data An object that contains important data.
*/
/**
* A method that does something async
* #param {myCallback} cb a callback function
* #return {boolean} always returns true
*/
this.method = function(cb) {
doSomethingAsync(function(data) {
cb(data);
});
return true;
}
}
module.exports = Test;
Here, I have defined a module, indicated a constructor, and documented a method that takes a callback as one of its' parameters. Sounds pretty simple and appears to follow the guidelines set by the usage guide http://usejsdoc.org/.
But for some reason beyond my understanding (and that's probably the core concept I'm not getting), it shows the callback myCallback as a member of the testModule instead of the Test class. Shouldn't it default to be a member of the class and not the module? This also appears to prevent JSDoc from making a link to the callback definition, which is not a lot of fun.
Now I realize that if I were to write:
/**
* #callback module:testModule~Test~myCallback
* #param {Object} data An object that contains important data.
*/
/**
* A method that does something async
* #param {module:testModule~Test~myCallback} cb a callback function
* #return {boolean} always returns true
*/
I would get my desired behavior. But this seems to be a very clunky way of doing things and the generated links are far from pretty.
Sorry for the long buildup and thank you in advance for your help in my documentation effort :)
I have come across much the same problem. If you want nicer-looking links, you can always add a {#link} in the description and just use the canonical name in the #type like this:
/**
* #callback module:testModule~Test~myCallback
* #param {Object} data An object that contains important data.
*/
/**
* #param {myCallback} cb {#link module:testModule~Test~myCallback|myCallback}: a callback function
* #return {boolean} always returns true
*/
I realize that's a bit more frustrating to type, but it documents myCallback as a member of the class rather than the module, and the link looks nice.
If you really want the link in the #type and you don't care about how it documents the callback, you could also do this, which is a little less verbose (and what I've decided to do for my project):
/**
* #callback myCallback
* #param {Object} data An object that contains important data.
*/
/**
* #param {module:testModule~myCallback} cb a callback function
* #return {boolean} always returns true
*/
That will properly link to myCallback and document it as a member of the module.

JSDoc within AngularJS services

I'm creating an AngularJS service to validate form inputs and I can't for the life of me figure out how to use JSDoc3 to create reasonable documentation.
Ideally I need to export the documentation for the validator service as well as the documentation for each validator (internal objects)
After googling around a bit I was able to get it kind of working by hacking around a bit with namespaces, but I'm wondering if there's a right way to do this. A way that won't muck up somebody else's JSDoc if they include my service.
Example:
angular.module('services.utility')
.factory('validator', [function () {
var validators = {
/**
* Requires a field to have something in it.
* #param {String|Boolean} val The value to be checked.
* #return {Object}
*/
'required': function(val){
// check against validator
return {'valid': true, 'msg': 'passed!'};
},
/**
* Requires a field to be less than a number.
* #param {Number} val The value to be checked.
* #param {Number} check The value to be checked against.
* #return {Object}
*/
'lessThan': function(val){
// check against validator
return {'valid': true, 'msg': 'passed!'};
}
};
return {
/**
* This is the main validation routine.
* #param {Object} vObjs An object to be processed.
* #return {Boolean}
*/
'validate': function(thingsToValidate){
// run some validations from the validators
// and return a bool.
}
};
}]);
In a perfect world, modifications to the above would let me generate a nice, non-global, JSDoc hierarchy where a user could read about how to use the validator as a whole, or dive in and look what needed to be passed in for each type of validation.
Thanks so much for any help you can give!
The way my team works is that we actually only document the actual factory function as if the user were going to read it. You've actually skipped over that guy. Either way, you can treat that as the entry point for your documentation and combine it with your "method" documentation for the full picture. You could make use of the #namespace documentation in combination with this.
/** Here is how you use my factory. #param #return */
my.validator.factory = function() { return { validate: function(){} }; }
/** Here are some validators. #enum {Function(*):ValidationResult} **/
my.validator.Validators = {}
module.factory('validator', my.validator.factory);
Depending on what you really want, you may prefer to use a prototype. That's where documentation can really shine:
/** Here is how you use my factory. #param #return #constructor */
my.Validator = function() {}
/** My validation function. #param #return */
my.Validator.prototype.validate = function() {}
/** Here are some validators. #enum {Function(*):ValidationResult} **/
my.Validator.Validators = {}
module.service('validator', my.Validator);
Using the prototype with your documentation really sticks it all together for me. It's like documenting your validator as one class entity, which makes the most sense to me.

Categories