@webex/jsdoctrinetest
Version:
119 lines (113 loc) • 3.3 kB
JavaScript
"use strict";
var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = extract;
var _fs = _interopRequireDefault(require("fs"));
var _traverse = _interopRequireDefault(require("@babel/traverse"));
var _doctrine = _interopRequireDefault(require("doctrine"));
var _types = require("@babel/types");
var _parse = _interopRequireDefault(require("./parse"));
/*!
* Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
*/
/**
* transform function which operates on each discovered example block
* @callback transformCallback
* @param {Object} options
* @param {ast} options.comment
* @param {string} options.name
* @param {string} options.filename
* @param {string} options.type
*/
/**
* Extracts comment blocks from the source code in the specified file
* @param {transformCallback} transform
* @param {string} filename
* @returns {Array<ast>}
*/
function extract(transform, filename) {
// eslint-disable-next-line no-sync
var code = _fs.default.readFileSync(filename, {
encoding: 'utf8'
});
var ast = (0, _parse.default)(code, {
sourceFilename: filename
});
var results = [];
var done = false;
(0, _traverse.default)(ast, {
enter: function enter(path) {
if (path.node.leadingComments) {
path.node.leadingComments.filter(isJSDocComment).forEach(function (comment) {
var result = _doctrine.default.parse(comment.value, {
unwrap: true,
sloppy: true,
recoverable: true,
lineNumbers: true
});
if (result.tags) {
result.tags.forEach(function (tag) {
if (tag.title === 'example') {
results.push(transform({
comment: tag.description,
name: getNodeName(path.node),
filename: path.node.loc.filename,
type: path.node.type
}));
}
});
}
});
}
},
Program: {
exit: function exit(path) {
if ((0, _types.isProgram)(path)) {
if (done) {
return;
}
path.pushContainer('body', results);
done = true;
}
}
}
});
return ast;
}
/**
* Extracts the name from the specified node
* @param {Node} node
* @returns {string}
*/
function getNodeName(node) {
if (node.id) {
return node.id.name;
}
if (node.key) {
return node.key.name;
}
throw new Error('Could not find name for node');
}
/**
* Indicates if the specified comment block is a doc block
* @param {CommentBlock} comment
* @returns {Boolean}
*/
function isJSDocComment(comment) {
var asterisks = comment.value.match(/^(\*+)/);
if (comment.value.startsWith('/*') && comment.value.endsWith('*/')) {
return false;
}
// eslint-disable-next-line
return (comment.type === 'CommentBlock' ||
// estree
// eslint-disable-next-line
comment.type === "Block") &&
// get-comments / traditional
// eslint-disable-next-line
asterisks && asterisks[1].length === 1;
}
//# sourceMappingURL=extract.js.map