gulp-validateTypedoc.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. 'use strict';
  2. var fs = require('fs');
  3. var Vinyl = require('vinyl');
  4. var through = require('through2');
  5. var PluginError = require('plugin-error');
  6. var nodeColorConsole = require('../../NodeHelpers/colorConsole');
  7. const log = nodeColorConsole.log;
  8. const warn = nodeColorConsole.warn;
  9. const err = nodeColorConsole.error;
  10. const success = nodeColorConsole.success;
  11. // ______________________________________________ VALIDATION ____________________________________________
  12. function unixStylePath(filePath) {
  13. return filePath.replace(/\\/g, '/');
  14. }
  15. function Validate(validationBaselineFileName, namespaceName, validateNamingConvention, generateBaseLine) {
  16. this.validationBaselineFileName = validationBaselineFileName;
  17. this.namespaceName = namespaceName;
  18. this.validateNamingConvention = validateNamingConvention;
  19. this.generateBaseLine = generateBaseLine;
  20. this.previousResults = {};
  21. this.results = {
  22. errors: 0
  23. };
  24. }
  25. Validate.hasTag = function(node, tagName) {
  26. tagName = tagName.trim().toLowerCase();
  27. if (node.comment && node.comment.tags) {
  28. for (var i = 0; i < node.comment.tags.length; i++) {
  29. if (node.comment.tags[i].tag === tagName) {
  30. return true;
  31. }
  32. }
  33. }
  34. return false;
  35. }
  36. Validate.position = function(node) {
  37. if (!node.sources) {
  38. log(node);
  39. }
  40. return node.sources[0].fileName + ':' + node.sources[0].line;
  41. }
  42. Validate.upperCase = new RegExp("^[A-Z_]*$");
  43. Validate.pascalCase = new RegExp("^[A-Z][a-zA-Z0-9_]*$");
  44. Validate.camelCase = new RegExp("^[a-z][a-zA-Z0-9_]*$");
  45. Validate.underscoreCamelCase = new RegExp("^_[a-z][a-zA-Z0-9_]*$");
  46. Validate.underscorePascalCase = new RegExp("^_[A-Z][a-zA-Z0-9_]*$");
  47. Validate.prototype.errorCallback = function(parent, node, nodeKind, category, type, msg, position) {
  48. this.results[this.filePath] = this.results[this.filePath] || { errors: 0 };
  49. var results = this.results[this.filePath];
  50. if (node === "toString") {
  51. node = "ToString";
  52. }
  53. // Checks against previous results.
  54. var previousResults = this.previousResults[this.filePath];
  55. if (previousResults) {
  56. var previousRootName = parent ? parent : node;
  57. var needCheck = true;
  58. if (Array.isArray(previousRootName)) {
  59. while (previousRootName.length > 1) {
  60. var previousFirst = previousRootName.shift();
  61. previousResults = previousResults[previousFirst];
  62. if (!previousResults) {
  63. needCheck = false;
  64. break;
  65. }
  66. }
  67. previousRootName = previousRootName.shift();
  68. }
  69. if (needCheck) {
  70. var previousNode = previousResults[previousRootName];
  71. if (previousNode) {
  72. var previousNodeKind = previousNode[nodeKind];
  73. if (previousNodeKind) {
  74. if (parent) {
  75. previousNode = previousNodeKind[node];
  76. }
  77. else {
  78. previousNode = previousNodeKind;
  79. }
  80. if (previousNode) {
  81. var previousCategory = previousNode[category];
  82. if (previousCategory) {
  83. var previousType = previousCategory[type];
  84. if (previousType) {
  85. // Early exit as it was already in the previous build.
  86. return;
  87. }
  88. }
  89. }
  90. }
  91. }
  92. }
  93. }
  94. // Write Error in output JSON.
  95. var rootName = parent ? parent : node;
  96. var current = results;
  97. if (Array.isArray(rootName)) {
  98. while (rootName.length > 1) {
  99. var first = rootName.shift();
  100. current = current[first] = current[first] || {};
  101. }
  102. rootName = rootName.shift();
  103. }
  104. current = current[rootName] = current[rootName] || {};
  105. current = current[nodeKind] = current[nodeKind] || {};
  106. if (parent) {
  107. current = current[node] = current[node] || {};
  108. }
  109. current = current[category] = current[category] || {};
  110. current = current[type] = true;
  111. results.errors++;
  112. if (!this.generateBaseLine) {
  113. err(msg, position);
  114. }
  115. }
  116. Validate.prototype.init = function(cb) {
  117. var self = this;
  118. if (!this.generateBaseLine && fs.existsSync(this.validationBaselineFileName)) {
  119. fs.readFile(this.validationBaselineFileName, "utf-8", function(err, data) {
  120. self.previousResults = JSON.parse(data);
  121. cb();
  122. });
  123. }
  124. else {
  125. cb();
  126. }
  127. }
  128. Validate.prototype.add = function(filePath, content) {
  129. this.filePath = filePath && unixStylePath(filePath);
  130. if (!Buffer.isBuffer(content)) {
  131. content = Buffer.from(content);
  132. }
  133. var contentString = content.toString();
  134. var json = JSON.parse(contentString);
  135. this.validateTypedoc(json);
  136. if (this.results[this.filePath]) {
  137. this.results.errors += this.results[this.filePath].errors;
  138. }
  139. }
  140. Validate.prototype.getResults = function() {
  141. return this.results;
  142. }
  143. Validate.prototype.getContents = function() {
  144. return Buffer.from(JSON.stringify(this.results));
  145. }
  146. /**
  147. * Validate a TypeDoc JSON file
  148. */
  149. Validate.prototype.validateTypedoc = function(json) {
  150. for (var i = 0; i < json.children.length; i++) {
  151. var namespaces = json.children[i].children;
  152. this.validateTypedocNamespaces(namespaces);
  153. }
  154. }
  155. /**
  156. * Validate namespaces attach to a declaration file from a TypeDoc JSON file
  157. */
  158. Validate.prototype.validateTypedocNamespaces = function(namespaces) {
  159. var namespace = null;
  160. // Check for BABYLON namespace
  161. for (var child in namespaces) {
  162. if (namespaces[child].name === this.namespaceName) {
  163. namespace = namespaces[child];
  164. break;
  165. }
  166. }
  167. // Exit if not BABYLON related.
  168. if (!namespace || !namespace.children) {
  169. return;
  170. }
  171. // Validate the namespace.
  172. this.validateTypedocNamespace(namespace);
  173. }
  174. /**
  175. * Validate classes and modules attach to a declaration file from a TypeDoc JSON file
  176. */
  177. Validate.prototype.validateTypedocNamespace = function(namespace) {
  178. var containerNode;
  179. var childNode;
  180. var children;
  181. var signatures;
  182. var signatureNode;
  183. var tags;
  184. var isPublic;
  185. for (var a in namespace.children) {
  186. containerNode = namespace.children[a];
  187. // Validate Sub Module
  188. if (containerNode.kindString === "Module" || containerNode.kindString === "Namespace") {
  189. this.validateTypedocNamespace(containerNode);
  190. continue;
  191. }
  192. // else Validate Classes
  193. // Account for undefined access modifiers.
  194. if (!containerNode.flags.isPublic &&
  195. !containerNode.flags.isPrivate &&
  196. !containerNode.flags.isProtected) {
  197. containerNode.flags.isPublic = true;
  198. }
  199. isPublic = containerNode.flags.isPublic;
  200. // Validate naming.
  201. this.validateNaming(null, containerNode);
  202. // Validate Comments.
  203. if (isPublic && !this.validateComment(containerNode)) {
  204. this.errorCallback(null,
  205. containerNode.name,
  206. containerNode.kindString,
  207. "Comments",
  208. "MissingText",
  209. "Missing text for " + containerNode.kindString + " : " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(containerNode));
  210. }
  211. children = containerNode.children;
  212. //Validate Properties
  213. if (children) {
  214. for (var b in children) {
  215. childNode = children[b];
  216. // Account for undefined access modifiers.
  217. if (!childNode.flags.isPublic &&
  218. !childNode.flags.isPrivate &&
  219. !childNode.flags.isProtected) {
  220. childNode.flags.isPublic = true;
  221. }
  222. isPublic = childNode.flags.isPublic;
  223. // Validate Naming.
  224. this.validateNaming(containerNode, childNode);
  225. if (isPublic) {
  226. tags = this.validateTags(childNode);
  227. if (tags) {
  228. this.errorCallback(containerNode.name,
  229. childNode.name,
  230. childNode.kindString,
  231. "Tags",
  232. tags,
  233. "Unrecognized tag " + tags + " at " + childNode.name + " (id: " + childNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  234. }
  235. }
  236. if (!this.validateComment(childNode)) {
  237. //Validate Signatures
  238. signatures = childNode.signatures;
  239. if (signatures) {
  240. for (var c in signatures) {
  241. signatureNode = signatures[c];
  242. if (isPublic) {
  243. if (!this.validateComment(signatureNode)) {
  244. this.errorCallback(containerNode.name,
  245. signatureNode.name,
  246. childNode.kindString,
  247. "Comments",
  248. "MissingText",
  249. "Missing text for " + childNode.kindString + " : " + signatureNode.name + " (id: " + signatureNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  250. }
  251. tags = this.validateTags(signatureNode);
  252. if (tags) {
  253. this.errorCallback(containerNode.name,
  254. signatureNode.name,
  255. childNode.kindString,
  256. "Tags",
  257. tags,
  258. "Unrecognized tag " + tags + " at " + signatureNode.name + " (id: " + signatureNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  259. }
  260. if (signatureNode.kindString !== "Constructor" &&
  261. signatureNode.kindString !== "Constructor signature") {
  262. if (signatureNode.type.name !== "void" && signatureNode.comment && !signatureNode.comment.returns) {
  263. this.errorCallback(containerNode.name,
  264. signatureNode.name,
  265. childNode.kindString,
  266. "Comments",
  267. "MissingReturn",
  268. "No Return Comment at " + signatureNode.name + " (id: " + signatureNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  269. }
  270. if (signatureNode.type.name === "void" && signatureNode.comment && signatureNode.comment.returns) {
  271. this.errorCallback(containerNode.name,
  272. signatureNode.name,
  273. childNode.kindString,
  274. "Comments",
  275. "UselessReturn",
  276. "No Return Comment Needed at " + signatureNode.name + " (id: " + signatureNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  277. }
  278. }
  279. }
  280. this.validateParameters(containerNode, childNode, signatureNode, signatureNode.parameters, isPublic);
  281. }
  282. } else {
  283. this.errorCallback(containerNode.name,
  284. childNode.name,
  285. childNode.kindString,
  286. "Comments",
  287. "MissingText",
  288. "Missing text for " + childNode.kindString + " : " + childNode.name + " (id: " + childNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  289. }
  290. }
  291. // this.validateParameters(containerNode, childNode, childNode.parameters, isPublic);
  292. }
  293. }
  294. }
  295. }
  296. /**
  297. * Validate that tags are recognized
  298. */
  299. Validate.prototype.validateTags = function(node) {
  300. var tags;
  301. var errorTags = [];
  302. if (node.comment) {
  303. tags = node.comment.tags;
  304. if (tags) {
  305. for (var i = 0; i < tags.length; i++) {
  306. var tag = tags[i];
  307. var validTags = ["constructor", "throw", "type", "deprecated", "example", "examples", "remark", "see", "remarks", "ignorenaming"]
  308. if (validTags.indexOf(tag.tag) === -1) {
  309. errorTags.push(tag.tag);
  310. }
  311. }
  312. }
  313. }
  314. return errorTags.join(",");
  315. }
  316. /**
  317. * Validate that a JSON node has the correct TypeDoc comments
  318. */
  319. Validate.prototype.validateComment = function(node) {
  320. // Return true for all contents coming from the TS d.ts
  321. if (node.sources && node.sources[0].fileName.indexOf("lib.dom.d.ts") > -1) {
  322. return true;
  323. }
  324. // Return-only methods are allowed to just have a @return tag
  325. if ((node.kindString === "Call signature" || node.kindString === "Accessor") && !node.parameters && node.comment && node.comment.returns) {
  326. return true;
  327. }
  328. // Return true for private properties (dont validate)
  329. if ((node.kindString === "Property" || node.kindString === "Object literal") && (node.flags.isPrivate || node.flags.isProtected)) {
  330. return true;
  331. }
  332. // Return true for inherited properties
  333. if (node.inheritedFrom) {
  334. return true;
  335. }
  336. // Return true for overwrited properties
  337. if (node.overwrites) {
  338. return true;
  339. }
  340. // Check comments.
  341. if (node.comment) {
  342. if (node.comment.text || node.comment.shortText) {
  343. return node.kindString !== "Constructor";
  344. }
  345. return false;
  346. }
  347. // Return true for inherited properties (need to check signatures)
  348. if (node.kindString === "Function") {
  349. return true;
  350. }
  351. return false;
  352. }
  353. /**
  354. * Validate comments for paramters on a node
  355. */
  356. Validate.prototype.validateParameters = function(containerNode, method, signature, parameters, isPublic) {
  357. var parametersNode;
  358. for (var parameter in parameters) {
  359. parametersNode = parameters[parameter];
  360. if (isPublic && !this.validateComment(parametersNode)) {
  361. // throw containerNode.name + " " + method.kindString + " " + method.name + " " + parametersNode.name + " " + parametersNode.kindString;
  362. this.errorCallback([containerNode.name, method.kindString, signature.name],
  363. parametersNode.name,
  364. parametersNode.kindString,
  365. "Comments",
  366. "MissingText",
  367. "Missing text for parameter " + parametersNode.name + " (id: " + parametersNode.id + ") of " + method.name + " (id: " + method.id + ")", Validate.position(method));
  368. }
  369. if (this.validateNamingConvention && !Validate.camelCase.test(parametersNode.name)) {
  370. if (containerNode.kindString === "Constructor" ||
  371. containerNode.kindString !== "Constructor signature") {
  372. if (Validate.underscoreCamelCase.test(parametersNode.name)) {
  373. continue;
  374. }
  375. }
  376. this.errorCallback([containerNode.name, method.kindString, signature.name],
  377. parametersNode.name,
  378. parametersNode.kindString,
  379. "Naming",
  380. "NotCamelCase",
  381. "Parameter " + parametersNode.name + " should be Camel Case (id: " + method.id + ")", Validate.position(method));
  382. }
  383. }
  384. }
  385. /**
  386. * Validate naming conventions of a node
  387. */
  388. Validate.prototype.validateNaming = function(parent, node) {
  389. if (!this.validateNamingConvention) {
  390. return;
  391. }
  392. // Ignore Naming Tag Check
  393. if (Validate.hasTag(node, 'ignoreNaming')) {
  394. return;
  395. } else {
  396. if (node.signatures) {
  397. for (var index = 0; index < node.signatures.length; index++) {
  398. var signature = node.signatures[index];
  399. if (Validate.hasTag(signature, 'ignoreNaming')) {
  400. return;
  401. }
  402. }
  403. }
  404. }
  405. if (node.inheritedFrom) {
  406. return;
  407. }
  408. // Internals are not subject to the public visibility policy.
  409. if (node.name && node.name.length > 0 && node.name[0] === "_") {
  410. return;
  411. }
  412. if ((node.flags.isPrivate || node.flags.isProtected) && node.flags.isStatic) {
  413. if (!Validate.underscorePascalCase.test(node.name)) {
  414. this.errorCallback(parent ? parent.name : null,
  415. node.name,
  416. node.kindString,
  417. "Naming",
  418. "NotUnderscorePascalCase",
  419. node.name + " should be Underscore Pascal Case (id: " + node.id + ")", Validate.position(node));
  420. }
  421. }
  422. else if (node.flags.isPrivate || node.flags.isProtected) {
  423. if (!Validate.underscoreCamelCase.test(node.name)) {
  424. this.errorCallback(parent ? parent.name : null,
  425. node.name,
  426. node.kindString,
  427. "Naming",
  428. "NotUnderscoreCamelCase",
  429. node.name + " should be Underscore Camel Case (id: " + node.id + ")", Validate.position(node));
  430. }
  431. }
  432. else if (node.flags.isStatic) {
  433. if (!Validate.pascalCase.test(node.name)) {
  434. this.errorCallback(parent ? parent.name : null,
  435. node.name,
  436. node.kindString,
  437. "Naming",
  438. "NotPascalCase",
  439. node.name + " should be Pascal Case (id: " + node.id + ")", Validate.position(node));
  440. }
  441. }
  442. else if (node.kindString == "Module") {
  443. if (!(Validate.upperCase.test(node.name) || Validate.pascalCase.test(node.name))) {
  444. this.errorCallback(parent ? parent.name : null,
  445. node.name,
  446. node.kindString,
  447. "Naming",
  448. "NotUpperCase",
  449. "Module is not Upper Case or Pascal Case " + node.name + " (id: " + node.id + ")", Validate.position(node));
  450. }
  451. }
  452. else if (node.kindString == "Interface" ||
  453. node.kindString == "Class" ||
  454. node.kindString == "Enumeration" ||
  455. node.kindString == "Enumeration member" ||
  456. node.kindString == "Type alias") {
  457. if (!Validate.pascalCase.test(node.name)) {
  458. this.errorCallback(parent ? parent.name : null,
  459. node.name,
  460. node.kindString,
  461. "Naming",
  462. "NotPascalCase",
  463. node.name + " should be Pascal Case (id: " + node.id + ")", Validate.position(node));
  464. }
  465. }
  466. else if (node.kindString == "Method" ||
  467. node.kindString == "Property" ||
  468. node.kindString == "Accessor" ||
  469. node.kindString == "Object literal") {
  470. // Only warn here as special properties such as FOV may be better capitalized
  471. if (!Validate.camelCase.test(node.name)) {
  472. this.errorCallback(parent ? parent.name : null,
  473. node.name,
  474. node.kindString,
  475. "Naming",
  476. "NotCamelCase",
  477. node.name + " should be Camel Case (id: " + node.id + ")", Validate.position(node));
  478. }
  479. }
  480. else if (node.kindString == "Variable") {
  481. this.errorCallback(parent ? parent.name : null,
  482. node.name,
  483. node.kindString,
  484. "Naming",
  485. "ShouldNotBeLooseVariable",
  486. node.name + " should not be a variable (id: " + node.id + ")", Validate.position(node));
  487. }
  488. else if (node.kindString === "Function") {
  489. if (!Validate.camelCase.test(node.name)) {
  490. this.errorCallback(parent ? parent.name : null,
  491. node.name,
  492. node.kindString,
  493. "Naming",
  494. "NotCamelCase",
  495. node.name + " should be Camel Case (id: " + node.id + ")", Validate.position(node));
  496. }
  497. }
  498. else if (node.kindString == "Constructor") {
  499. // Do Nothing Here, this is handled through the class name.
  500. }
  501. else {
  502. this.errorCallback(parent ? parent.name : null,
  503. node.name,
  504. node.kindString,
  505. "Naming",
  506. "UnknownNamingConvention",
  507. "Unknown naming convention for " + node.kindString + " at " + node.name + " (id: " + node.id + ")", Validate.position(node));
  508. }
  509. }
  510. // ______________________________________________ PLUGIN ____________________________________________
  511. // consts
  512. const PLUGIN_NAME = 'gulp-validateTypedoc';
  513. // plugin level function (dealing with files)
  514. function gulpValidateTypedoc(validationBaselineFileName, namespaceName, validateNamingConvention, generateBaseLine) {
  515. if (!validationBaselineFileName) {
  516. throw new PluginError(PLUGIN_NAME, 'Missing validation filename!');
  517. }
  518. if (typeof validationBaselineFileName !== "string") {
  519. throw new PluginError(PLUGIN_NAME, 'Validation filename must be a string!');
  520. }
  521. var validate;
  522. var latestFile;
  523. function bufferContents(file, enc, cb) {
  524. // ignore empty files
  525. if (file.isNull()) {
  526. cb();
  527. return;
  528. }
  529. // we don't do streams (yet)
  530. if (file.isStream()) {
  531. this.emit('error', new Error('gulp-validatTypedoc: Streaming not supported'));
  532. cb();
  533. return;
  534. }
  535. // set latest file if not already set,
  536. // or if the current file was modified more recently.
  537. latestFile = file;
  538. // What will happen once all set.
  539. var done = function() {
  540. // add file to concat instance
  541. validate.add(file.relative, file.contents);
  542. cb();
  543. }
  544. // Do the validation.
  545. if (!validate) {
  546. validate = new Validate(validationBaselineFileName, namespaceName, validateNamingConvention, generateBaseLine);
  547. validate.init(done);
  548. }
  549. else {
  550. done();
  551. }
  552. }
  553. function endStream(cb) {
  554. // no files passed in, no file goes out
  555. if (!latestFile) {
  556. var error = new PluginError(PLUGIN_NAME, 'gulp-validatTypedoc: No Baseline found.');
  557. this.emit('error', error);
  558. cb();
  559. return;
  560. }
  561. var results = validate.getResults();
  562. var buffer = Buffer.from(JSON.stringify(results, null, 2))
  563. if (generateBaseLine) {
  564. fs.writeFileSync(validationBaselineFileName, buffer || '');
  565. }
  566. var jsFile = new Vinyl({
  567. base: null,
  568. path: validationBaselineFileName,
  569. contents: buffer
  570. });
  571. this.push(jsFile);
  572. var action = generateBaseLine ? "baseline generation" : "validation";
  573. var self = this;
  574. var error = function(message) {
  575. generateBaseLine ? warn : err;
  576. if (generateBaseLine) {
  577. warn(message);
  578. }
  579. else {
  580. err(message);
  581. var error = new PluginError(PLUGIN_NAME, message);
  582. self.emit('error', error);
  583. }
  584. }
  585. if (results.errors > 1) {
  586. var message = results.errors + " errors have been detected during the " + action + " !";
  587. error(message);
  588. }
  589. else if (results.errors === 1) {
  590. var message = "1 error has been detected during the " + action + " !";
  591. error(message);
  592. }
  593. else {
  594. var message = "All formatting check passed successfully during the " + action + " !";
  595. success(message);
  596. }
  597. cb();
  598. }
  599. return through.obj(bufferContents, endStream);
  600. };
  601. // exporting the plugin main function
  602. module.exports = gulpValidateTypedoc;