パッケージの詳細

dox

visionmedia112.4kMIT1.0.0

Markdown / JSdoc documentation generator

documentation, docs, markdown, jsdoc

readme

Dox

Tests

Dox is a JavaScript documentation generator written with node. Dox no longer generates an opinionated structure or style for your docs, it simply gives you a JSON representation, allowing you to use markdown and JSDoc-style tags.

Installation

Install from npm:

$ npm install -g dox

Usage Examples

dox(1) operates over stdio:

$ dox < utils.js
...JSON...

to inspect the generated data you can use the --debug flag, which is easier to read than the JSON output:

 $ dox --debug < utils.js

utils.js:

/**
 * Escape the given `html`.
 *
 * @example
 *     utils.escape('<script></script>')
 *     // => '&lt;script&gt;&lt;/script&gt;'
 *
 * @param {String} html string to be escaped
 * @return {String} escaped html
 * @api public
 */

exports.escape = function(html){
  return String(html)
    .replace(/&(?!\w+;)/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
};

output:

[
  {
    "tags": [
      {
        "type": "example",
        "string": "    utils.escape('<script></script>')\n    // => '&lt;script&gt;&lt;/script&gt;'",
        "html": "<pre><code>utils.escape(&#39;&lt;script&gt;&lt;/script&gt;&#39;)\n// =&gt; &#39;&amp;lt;script&amp;gt;&amp;lt;/script&amp;gt;&#39;\n</code></pre>"
      },
      {
        "type": "param",
        "string": "{String} html string to be escaped",
        "types": [
          "String"
        ],
        "name": "html",
        "description": "string to be escaped"
      },
      {
        "type": "return",
        "string": "{String} escaped html",
        "types": [
          "String"
        ],
        "description": "escaped html"
      },
      {
        "type": "api",
        "string": "public",
        "visibility": "public"
      }
    ],
    "description": {
      "full": "<p>Escape the given <code>html</code>.</p>",
      "summary": "<p>Escape the given <code>html</code>.</p>",
      "body": ""
    },
    "isPrivate": false,
    "ignore": false,
    "code": "exports.escape = function(html){\n  return String(html)\n    .replace(/&(?!\\w+;)/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;');\n};",
    "ctx": {
      "type": "method",
      "receiver": "exports",
      "name": "escape",
      "string": "exports.escape()"
    }
  }
]

This output can then be passed to a template for rendering. Look below at the "Properties" section for details.

Usage


Usage: dox [options]

  Options:

    -h, --help                     output usage information
    -V, --version                  output the version number
    -r, --raw                      output "raw" comments, leaving the markdown intact
    -a, --api                      output markdown readme documentation
    -s, --skipPrefixes [prefixes]  skip comments prefixed with these prefixes, separated by commas
    -d, --debug                    output parsed comments for debugging
    -S, --skipSingleStar           set to false to ignore `/* ... */` comments

  Examples:

    # stdin
    $ dox > myfile.json

    # operates over stdio
    $ dox < myfile.js > myfile.json

Programmatic Usage


var dox = require('dox'),
    code = "...";

var obj = dox.parseComments(code);

// [{ tags:[ ... ], description, ... }, { ... }, ...]

Properties

A "comment" is comprised of the following detailed properties:

- tags
- description
- isPrivate
- isEvent
- isConstructor
- line
- ignore
- code
- ctx

Description

A dox description is comprised of three parts, the "full" description, the "summary", and the "body". The following example has only a "summary", as it consists of a single paragraph only, therefore the "full" property has only this value as well.

/**
 * Output the given `str` to _stdout_.
 */

exports.write = function(str) {
  process.stdout.write(str);
};

yields:

description:
     { full: '<p>Output the given <code>str</code> to <em>stdout</em>.</p>',
       summary: '<p>Output the given <code>str</code> to <em>stdout</em>.</p>',
       body: '' },

Large descriptions might look something like the following, where the "summary" is still the first paragraph, the remaining description becomes the "body". Keep in mind this is markdown, so you can indent code, use lists, links, etc. Dox also augments markdown, allowing "Some Title:\n" to form a header.

/**
 * Output the given `str` to _stdout_
 * or the stream specified by `options`.
 *
 * Options:
 *
 *   - `stream` defaulting to _stdout_
 *
 * Examples:
 *
 *     mymodule.write('foo')
 *     mymodule.write('foo', { stream: process.stderr })
 *
 */

exports.write = function(str, options) {
  options = options || {};
  (options.stream || process.stdout).write(str);
};

yields:

description:
     { full: '<p>Output the given <code>str</code> to <em>stdout</em><br />or the stream specified by <code>options</code>.</p>\n\n<h2>Options</h2>\n\n<ul>\n<li><code>stream</code> defaulting to <em>stdout</em></li>\n</ul>\n\n<h2>Examples</h2>\n\n<pre><code>mymodule.write(\'foo\')\nmymodule.write(\'foo\', { stream: process.stderr })\n</code></pre>',
       summary: '<p>Output the given <code>str</code> to <em>stdout</em><br />or the stream specified by <code>options</code>.</p>',
       body: '<h2>Options</h2>\n\n<ul>\n<li><code>stream</code> defaulting to <em>stdout</em></li>\n</ul>\n\n<h2>Examples</h2>\n\n<pre><code>mymodule.write(\'foo\')\nmymodule.write(\'foo\', { stream: process.stderr })\n</code></pre>' }

Tags

Dox also supports JSdoc-style tags. Currently only @api is special-cased, providing the comment.isPrivate boolean so you may omit "private" utilities etc.


/**
 * Output the given `str` to _stdout_
 * or the stream specified by `options`.
 *
 * @param {String} str
 * @param {{stream: Writable}} options
 * @return {Object} exports for chaining
 */

exports.write = function(str, options) {
  options = options || {};
  (options.stream || process.stdout).write(str);
  return this;
};

yields:

tags:
   [ { type: 'param',
       string: '{String} str',
       types: [ 'String' ],
       name: 'str',
       description: '' },
     { type: 'param',
       string: '{{stream: Writable}} options',
       types: [ { stream: ['Writable'] } ],
       name: 'options',
       description: '' },
     { type: 'return',
       string: '{Object} exports for chaining',
       types: [ 'Object' ],
       description: 'exports for chaining' },
     { type: 'api',
       visibility: 'public' } ]

Complex jsdoc tags

dox supports all jsdoc type strings specified in the jsdoc documentation. You can specify complex object types including optional flag =, nullable ?, non-nullable ! and variable arguments ....

Additionally you can use typesDescription which contains formatted HTML for displaying complex types.


/**
 * Generates a person information string based on input.
 *
 * @param {string | {name: string, age: number | date}} name Name or person object
 * @param {{separator: string} =} options An options object
 * @return {string} The constructed information string
 */

exports.generatePersonInfo = function(name, options) {
  var str = '';
  var separator = options && options.separator ? options.separator : ' ';

  if(typeof name === 'object') {
    str = [name.name, '(', name.age, ')'].join(separator);
  } else {
    str = name;
  }
};

yields:

tags:
[
  {
    "tags": [
      {
        "type": "param",
        "string": "{string | {name: string, age: number | date}} name Name or person object",
        "name": "name",
        "description": "Name or person object",
        "types": [
          "string",
          {
            "name": [
              "string"
            ],
            "age": [
              "number",
              "date"
            ]
          }
        ],
        "typesDescription": "<code>string</code>|{ name: <code>string</code>, age: <code>number</code>|<code>date</code> }",
        "optional": false,
        "nullable": false,
        "nonNullable": false,
        "variable": false
      },
      {
        "type": "param",
        "string": "{{separator: string} =} options An options object",
        "name": "options",
        "description": "An options object",
        "types": [
          {
            "separator": [
              "string"
            ]
          }
        ],
        "typesDescription": "{ separator: <code>string</code> }|<code>undefined</code>",
        "optional": true,
        "nullable": false,
        "nonNullable": false,
        "variable": false
      },
      {
        "type": "return",
        "string": "{string} The constructed information string",
        "types": [
          "string"
        ],
        "typesDescription": "<code>string</code>",
        "optional": false,
        "nullable": false,
        "nonNullable": false,
        "variable": false,
        "description": "The constructed information string"
      }
    ]

Code

The .code property is the code following the comment block, in our previous examples:

exports.write = function(str, options) {
  options = options || {};
  (options.stream || process.stdout).write(str);
  return this;
};

Ctx

The .ctx object indicates the context of the code block, is it a method, a function, a variable etc. Below are some examples:

exports.write = function(str, options) {
};

yields:

ctx:
 { type: 'method',
   receiver: 'exports',
   name: 'write',
   string: 'exports.write()' } }
var foo = 'bar';

yields:

ctx:
 { type: 'declaration',
   name: 'foo',
   value: '\'bar\'',
   string: 'foo' }
function User() {

}

yields:

ctx:
 { type: 'function',
   name: 'User',
   string: 'User()' } }

Extending Context Matching

Context matching in dox is done by performing pattern matching against the code following a comment block. dox.contextPatternMatchers is an array of all pattern matching functions, which dox will iterate over until one of them returns a result. If none return a result, then the comment block does not receive a ctx value.

This array is exposed to allow for extension of unsupported context patterns by adding more functions. Each function is passed the code following the comment block and (if detected) the parent context if the block.

dox.contextPatternMatchers.push(function (str, parentContext) {
  // return a context object if found
  // return false otherwise
});

Ignore

Comments and their associated bodies of code may be flagged with "!" to be considered worth ignoring, these are typically things like file comments containing copyright etc, however you of course can output them in your templates if you want.

/**
 * Not ignored.
 */

vs

/*!
 * Ignored.
 */

You may use -S, --skipSingleStar or {skipSingleStar: true} to ignore /* ... */ comments.

Running tests

Install dev dependencies and execute make test:

 $ npm install -d
 $ make test

License

(The MIT License)

Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

更新履歴

1.0.0 / 2022-09-06

  • jsdoctypeparser finally updated to latest version

0.9.1 / 2022-04-26

  • Dependency bumps for commander and markdown-it to address security vulnerabilities

0.9.0 / 2016-08-13

  • Markdown is now generated using the markdown-it package, which conforms to Commonmark standards.
  • Fix: Dox now recognizes ES6 template strings as strings and does not attempt to parse their contents.

  • Deps: added markdown-it@7.0.0

  • Deps: removed marked
  • DevDeps: mocha@3.0.2
  • DevDeps: should@11.0.0

0.8.1 / 2016-03-29

  • Fix: Dox will no longer falsely enter or exit string blocks when encountering an escaped quote or double-quote
  • Deps: commander@2.9.0
  • Deps: marked@0.3.5

0.8.0 / 2015-05-27

  • Fix: Tags with whitespace between the tag start and the previous line ending are now parsed correctly.
  • Deps: commander@2.8.1
  • Deps: jsdoctypeparser@1.2.0
    • Better compatibility for type declarations, but may result in changes to output with invalid types.

0.7.1 / 2015-04-03

Context parsing has been re-factored into an array of functions that are iterated over until a match is found. This array is exposed as dox.contextPatternMatchers, allowing for extension with new contexts without needing to edit the dox source.

  • Fix: ES6 classes extended from sub-properties (such as Backbone.View) are now properly matched

0.7.0 / 2015-03-24

  • Add context parsing for some ES6 syntax:
    • classes
    • class constructors
    • class methods
    • assignments via let or const
  • Add support for @description tag
  • Add context match for returned closure
  • Add: Tags without descriptions now have an html property containing a markdown parse of the tag's contents
  • Fix: more agnostic to code style when parsing contexts (eg, no longer ignores functions without spaces between function name and parenthesis)
  • Fix: No longer incorrectly tries to parse strings inside comments, causing large chunks of a file to be ignored.
  • Fix: No longer parses double slash in a string literal as being a comment start.
  • Deps: commander@2.7.1

0.6.1 / 2014-11-27

  • Tag descriptions now contain markdown and obey raw option

0.6.0 / 2014-11-27

  • Add complex jsdoc annotations
  • Add support for more tags
  • Add typesDescription field
  • Fix "skipPrefixes incorrectly assumes option.raw=false"
  • Fix "White spaces in the tag type string break the parsing of tags"

0.5.3 / 2014-10-06

  • Add --skipSingleStar option to ignore /* ... */ comments
  • Merge #106: make the other context regex like the general method one

0.5.2 / 2014-10-05

  • Support event tags, add isEvent parameter to comment object
  • Removed obsolete make rules

0.5.1 / 2014-09-07

  • Fixed: */* breaks parsing

0.5.0 / 2014-09-04

  • Marked options can be set via dox.setMarkedOptions
  • Comment blocks include line and codeStart to mark the first line of the comment block and the first line of the code context.
  • Ignores jshint, jslint and eslint directives. This can be overridden or added to via the skipPrefixes option and the --skipPrefixes command line flag, which takes a comma separated list of prefixes.
  • The code field trims extra indentation based on the indentation of the first line of code.
  • Set the isConstructor property when a @constructor tag is present and change ctx.type to constructor.
  • Recognizes the following code contexts:
    • Foo.prototype.bar; (property)
    • Foo.prototype = { (prototype)
    • foo: function () { (method)
    • foo: bar (property)
    • get foo () { (property)
    • set foo () { (property)
  • When a comment is present to identify the definition of an object literal, comments for the object's members will include a ctx.constructor property identifying the parent object.
  • Fixed: Multi-line comments with no space following the star are parsed correctly.
    • Example: /*comment*/
  • Fixed: A code context of Foo.prototype.bar = null; is parsed correctly.
  • @param tags include an optional attribute
  • @returns is recognized as an alias for @return
  • Support comments without descriptions (ex: /** @name Foo **/)
  • Fixed: Crash with the --api flag when no headers are generated.
  • Fixed: --api output includes aliases.

0.4.6 / 2014-07-09

  • do not wrap @example contents with markdown

0.4.5 / 2014-07-09

  • use marked for markdown rendering
  • multiline tags support (@example)
  • support for @template, @property, @define, @public, @private, @protected, @lends, @extends, @implements, @enum, @typedef

0.4.4 / 2013-07-28

  • add support for variable names containing "$". fix #102

0.4.3 / 2013-03-18

  • fix dox(1) --version. Closes #91
  • fix ctx.string on properties of a prototype
  • add support tab-indented comments

0.4.2 / 2013-01-18

  • Prevent error when using --api & comments have no example code.

0.4.1 / 2012-11-11

  • change # to . in --api

0.4.0 / 2012-11-09

  • add TOC to --api. Closes #72
  • add gfm code blocks. Closes #71
  • remove implicit titles. Closes #70

0.3.3 / 2012-10-16

  • fix --api .receiver

0.3.2 / 2012-10-01

  • add dox --api

0.3.1 / 2012-04-25

  • Fixed annoying title bug

0.3.0 / 2012-03-27

  • Added @memberOf [olivernn]
  • Added @arguments [olivernn]
  • Added @borrows [olivernn]

0.2.0 / 2012-02-23

  • Added -r, --raw support. Closes #48

0.1.3 / 2011-12-08

  • Added: allow arbitrary tags [logicalparadox]
  • Fixed function whitespace [TooTallNate]

0.1.2 / 2011-10-22

  • remove html escaping for now

0.1.1 / 2011-10-10

  • Fixed: colons in comment lines not intended as headers [Evan Owen]

0.0.5 / 2011-03-02

  • Adding "main" to package descriptor since "directories" are no longer supported.

0.0.4 / 2011-01-20

  • Added --intro support for including an intro file written in markdown [Alex Young]

0.0.3 / 2010-07-15

  • Linked h2s

0.0.2 / 2010-07-15

  • Collapsing files, click to open. Closes #19
  • Fixed ribbon position instead of absolute
  • Removed menu
  • Removed node-discount dependency, using markdown-js