Code coverage report for lib/builder.js

Statements: 77.29% (599 / 775)      Branches: 67.79% (303 / 447)      Functions: 83.33% (105 / 126)      Lines: 77.97% (598 / 767)     

All files » lib/ » builder.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611          1                           1   1                                       1       1   1 1 1 1   1       1 1 1 1   1 965 965 165     965 21   21 42   21   944   965     1 81 81 79 79 79   79     81     1 12 12     12               12   12     1 1           1             1 1 1     1 1 1                           1373   1373   1373 1373               1373                       998 998         998   998   998 998     998 46   952         998                       998   4         4 3 3   3 2       4 4 4 2692 4 4 4 4 2   4               998 297   998 994 994       998                   998 50 36   50 50   50   998                                                                                                                                                                                                                           1     1 1 1                                                                                                                                                                           153           153 1 1   1 1 1                 1 1 1           152   153 1224 1224   153                 154 154 10472 10472                 154 154                 154 154 154 154 2618 2618 2618 1694 1694 1694 1694 924 924 924               1694   1694     154 154 154                 152 152 152 9880 9880     152 152 152 9880 9880   152 152 9880   9880 30248 9880 152   9880   20368 11552   20368 9880         20368         152   152                 1423 1423 790 790       1423                   703 703 703 7369 288 465 13   452 6   452     452 5     447   452     452   452 1374 2 2       452   7081 181 181 249     249 181 175 6       6       6900   648     703               1 1 1     1 3 3 3 3   3     1 1 1 1 3 3 3 3 3             1 1 1             153 153                               787   787 787                     153   153 789     153   153                             153   153         153     153       153 153 1683     153 1       153 153 5216 306   4910     153           153 153                   1   1 1 1 1 1 1 1   1 1 1 1                   1     1 1 1 1 1     1     1 1 1                     17 17   17 17 17 17     17   17 17 17 17 17 17 17 17 17 17 17   17 16 16 77 77 77     16   17 1 1 1 1   1       1   17 4 4 6 6 6     4     17 17 17 17 17 17       17 17                   1 1   1 1   1 1 17 17     1 1 17 17 17 17 17     17     1 1 1                     12 12 32 2 2     12                                 72 72   72     72 9 9 9         9   6057 12 12 12     10 10 10     2 2 2         9 3   2       72                   70 70   70   70     70   70 70 70 70 70 70 70 70   70 70 70   70   70 70 70 70 70 70     70       70 7     70 70 47110 680       70   70 9 9 9 9                   9 9 9     9   9 9         9 9 2 2 2 2   2             70 690   399 399 399 225 439 439 3   439       399 399 6 3 3 4   3   3     399 399 399 225   174   399 399 175 175               399 2     399 399   79   79 79 11   79     79                                 79 2     79 79       200   200   200     200   200 15     200                                 200       200 200   12   12   12                                 12       12 12       70 70 70 70   70 10   70 45   70 34   70 63     70 70 70 70 70 70 70       70 70                 1 1   1 1   1 1 68 68     1 1 68 68 68 68 68     68     1 1 1                     71124 319   70805       70805 26416   70805 44378   70805               1 1   1 1   1 1 65 65     1 1 65 65 65     65 65 65     65     1 1 1                     65   65 65     65       65   65 65 65 65 65   65 65 65   65 65 65           65       65 65 65 65 65 65                           1 1 1 1                     1 1 1   1 2 79 79 11 6       2     1       1                         24944               1 1 1   1 1 1 1 1   1 1   1 1 1 1                     1 1   1 1 1 1 1                
/*
Copyright (c) 2011, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/
var MD = require("node-markdown").Markdown,
    fs = require('graceful-fs'),
    noop = function() {},
    path = require('path'),
    DEFAULT_RETURN_TAGS = 'code|em|strong|span|a|pre|dl|dd|dt|ul|li|ol',
    TEMPLATE;
 
/**
* Takes the `JSON` data from the `DocParser` class, creates and parses markdown and handlebars
based templates to generate static HTML content
* @class DocBuilder
* @module yuidoc
*/
 
YUI.add('doc-builder', function(Y) {
 
    var fixType = Y.Lang.fixType,
    print = function(items) {
        var out = '<ul>';
 
        Y.each(items, function(i, k) {
            out += '<li>';
            if (Y.Lang.isObject(i)) {
                if (!i.path) {
                    out += k + '/' + print(i);
                } else {
                    out += '<a href="../files/' + i.name + '.html">' + k + '</a>';
                }
            }
            out += '</li>';
        });
 
        out += '</ul>';
        return out;
    };
 
    Y.Handlebars.registerHelper('buildFileTree', function(items, fn) {
        return print(items);
    });
 
    var DEFAULT_THEME = themeDir = path.join(__dirname, '../', 'themes', 'default');
 
    Y.DocBuilder = function(options, data) {
        this.options = options;
        Eif (options.helpers) {
            this._addHelpers(options.helpers);
        }
        Iif (options.themedir) {
            themeDir = options.themedir;
        }
 
        this.data = data;
        Y.log('Building..', 'info', 'builder');
        this.files = 0;
        var self = this;
 
        Y.Handlebars.registerHelper('crossLink', function(item, options) {
            var str = '';
            if (!item) {
                item = '';
            }
            //console.log('CrossLink:', item);
            if (item.indexOf('|') > 0) {
                var parts = item.split('|'),
                p = [];
                Y.each(parts, function(i) {
                    p.push(self._parseCrossLink.call(self, i));
                });
                str = p.join(' | ');
            } else {
                str = self._parseCrossLink.call(self, item, false, options.fn(this));
            }
            return str;
        });
 
        Y.Handlebars.registerHelper('crossLinkModule', function(item, options) {
            var str = item;
            if (self.data.modules[item]) {
	            var content = options.fn(this);
	            Eif (content === "") {
		            content = item;
	            }
                str = '<a href="../modules/' + item.replace('/', '_') +
                      '.html">' + content + '</a>';
            }
            return str;
        });
 
        Y.Handlebars.registerHelper('crossLinkRaw', function(item, fn) {
            var str = '';
            Iif (!item) {
                item = '';
            }
            Iif (item.indexOf('|') > 0) {
                var parts = item.split('|'),
                p = [];
                Y.each(parts, function(i) {
                    p.push(self._parseCrossLink.call(self, i, true));
                });
                str = p.join(' | ');
            } else {
                str = self._parseCrossLink.call(self, item, true);
            }
            return str;
        });
 
        this.cacheTemplates = true;
        Iif (options.cacheTemplates === false) {
            this.cacheTemplates = false;
        }
 
    };
 
    Y.DocBuilder.prototype = {
        /**
        * Register a `Y.Handlebars` helper method
        * @method _addHelpers
        * @param {Object} helpers Object containing a hash of names and functions
        */
        _addHelpers: function(helpers) {
            Y.log('Importing helpers: ' + helpers, 'info', 'builder');
            helpers.forEach(function(imp) {
                Iif (!Y.Files.exists(imp) || Y.Files.exists(path.join(process.cwd(), imp))) {
                   imp= path.join(process.cwd(), imp);
                }
                var h = require(imp);
                Object.keys(h).forEach(function(name) {
                    Y.Handlebars.registerHelper(name, h[name]);
                });
            });
        },
        /**
        * Wrapper around the Markdown parser so it can be normalized or even side stepped
        * @method markdown
        * @private
        * @param {String} md The Markdown string to parse
        * @param {Boolean} def Only allow default set of HTML tags
        * @param {Array} tags An array of tags to allow
        * @return {HTML} The rendered HTML
        */
        markdown: function(md, def, tags) {
            html = MD(md, def, tags);
            //Only reprocess if helpers were asked for
            Eif (this.options.helpers || (html.indexOf('{{#crossLink') > -1)) {
                //console.log('MD: ', html);
                try {
                    html = (Y.Handlebars.compile(html))({});
                } catch (hError) {
                    //Remove all the extra escapes
                    html = html.replace(/\\{/g, '{').replace(/\\}/g, '}');
                    Y.log('Failed to parse Handlebars, probably an unknown helper, skipping..', 'warn', 'builder');
                }
                //console.log('HB: ', html);
            }
            return html;
        },
        
        /**
        * Parse the item to be cross linked and return an HREF linked to the item
        * @method _parseCrossLink
        * @private
        * @param {String} item The item to crossLink
        * @param {Boolean} [raw=false] Do not wrap it in HTML
        * @param {String} [content] crossLink helper content
        */
        _parseCrossLink: function(item, raw, content) {
            var self = this;
            var base = '../',
                baseName = item,
                newWin = false,
                className = 'crosslink';
 
            item = fixType(item);
 
            item = baseItem = Y.Lang.trim(item.replace('{', '').replace('}', ''));
            //Remove Cruft
            item = item.replace('*', '').replace('[', '').replace(']', '');
            var link = false,
                href;
 
            if (self.data.classes[item]) {
                link = true;
            } else {
                Iif (self.data.classes[item.replace('.', '')]) {
                    link = true;
                    item = item.replace('.', '');
                }
            }
            Iif (self.options.externalData) {
                if (self.data.classes[item]) {
                    if (self.data.classes[item].external) {
                        href = self.data.classes[item].path;
                        base = self.options.externalData.base;
                        className += ' external';
                        newWin = true;
                        link = true;
                    }
                }
            }
 
            if (item.indexOf('/') > -1) {
                //We have a class + method to parse
                var parts = item.split('/'),
                    cls = parts[0],
                    method = parts[1],
                    type = 'method';
 
                if (method.indexOf(':') > -1) {
                    parts = method.split(':');
                    method = parts[0],
                    type = parts[1];
                    if (type.indexOf('attr') === 0) {
                        type = 'attribute';
                    }
                }
 
                Eif (cls && method) {
                    Eif (self.data.classes[cls]) {
                        self.data.classitems.forEach(function(i) {
                            if (i.itemtype === type && i.name === method && i.class === cls) {
                                link = true;
                                baseItem = method;
                                var t = type;
                                if (t === 'attribute') {
                                    t = 'attr';
                                }
                                href = path.join(base, 'classes', cls + '.html#' + t + '_' + method);
                            }
                        });
                    }
                }
 
            }
 
            if (item === 'Object' || item === 'Array') {
                link = false;
            }
            if (!href) {
                href = path.join(base, 'classes', item + '.html');
                Iif (base.match(/^https?:\/\//)) {
                    href = base + path.join('classes', item + '.html');
                }
            }
            Iif (!link && self.options.linkNatives) {
                if (self.NATIVES && self.NATIVES[item]) {
                    href = self.NATIVES_LINKER(item);
                    if (href) {
                        className += ' external';
                        newWin = true;
                        link = true;
                    }
                }
            }
            if (link) {
	            if (content !== undefined) {
	                content = content.trim();
	            }
	            Eif (!content) {
		            content = baseItem;
	            }
                item = '<a href="' + href + '" class="' + className + '"' + ((newWin) ? ' target="_blank"' : '') + '>' + content + '</a>';
            }
            return (raw) ? href : item;
        },
        /**
        * List of native types to cross link to MDN
        * @property NATIVES
        * @type Object
        */
        NATIVES: {
            'Array': 1,
            'Boolean': 1,
            'Date': 1,
            'decodeURI': 1,
            'decodeURIComponent': 1,
            'encodeURI': 1,
            'encodeURIComponent': 1,
            'eval': 1,
            'Error': 1,
            'EvalError': 1,
            'Function': 1,
            'Infinity': 1,
            'isFinite': 1,
            'isNaN': 1,
            'Math': 1,
            'NaN': 1,
            'Number': 1,
            'Object': 1,
            'parseFloat': 1,
            'parseInt': 1,
            'RangeError': 1,
            'ReferenceError': 1,
            'RegExp': 1,
            'String': 1,
            'SyntaxError': 1,
            'TypeError': 1,
            'undefined': 1,
            'URIError': 1,
            'HTMLElement': 'https:/'+'/developer.mozilla.org/en/Document_Object_Model_(DOM)/',
            'HTMLCollection': 'https:/'+'/developer.mozilla.org/en/Document_Object_Model_(DOM)/',
            'DocumentFragment': 'https:/'+'/developer.mozilla.org/en/Document_Object_Model_(DOM)/',
            'HTMLDocument': 'https:/'+'/developer.mozilla.org/en/Document_Object_Model_(DOM)/'
        },
        /**
        * Function to link an external type uses `NATIVES` object
        * @method NATIVES_LINKER
        * @private
        * @param {String} name The name of the type to link
        * @return {String} The combined URL
        */
        NATIVES_LINKER: function(name) {
            var url = 'https:/'+'/developer.mozilla.org/en/JavaScript/Reference/Global_Objects/';
            if (this.NATIVES[name] !== 1) {
                url = this.NATIVES[name];
            }
            return url + name;
        },
        /**
        * Mixes the various external data soures together into the local data, augmenting 
        * it with flags.
        * @method _mixExternal
        * @private
        */
        _mixExternal: function() {
            var self = this;
            Y.log('External data received, mixing', 'info', 'builder');
            self.options.externalData.forEach(function(exData) {
            
                ['files', 'classes', 'modules'].forEach(function(k) {
                    Y.each(exData[k], function(item, key) {
                        item.external = true;
                        var file = item.name;
                        if (!item.file) {
                            file = self.filterFileName(item.name);
                        }
                        
                        if (item.type) {
                            item.type = fixType(item.type);
                        }
 
                        item.path = exData.base + path.join(k, file + '.html');
 
                        self.data[k][key] = item;
                    });
                });
                Y.each(exData.classitems, function(item) {
                    item.external = true;
                    item.path = exData.base + path.join('files', self.filterFileName(item.file) + '.html');
                    if (item.type) {
                        item.type = fixType(item.type);
                    }
                    if (item.params) {
                        item.params.forEach(function(p) {
                            if (p.type) {
                                p.type = fixType(p.type);
                            }
                        });
                    }
                    if (item.return) {
                        item.return.type = fixType(item.return.type);
                    }
                    self.data.classitems.push(item);
                });
            });
        },
        /**
        * Fetches the remote data and fires the callback when it's all complete
        * @method mixExternal
        * @param {Callback} cb The callback to execute when complete
        * @async
        */
        mixExternal: function(cb) {
            var self = this,
                info = self.options.external;
 
            Eif (!info) {
                cb();
                return;
            }
            if (!info.merge) {
                info.merge = 'mix';
            }
            if (!info.data) {
                Y.log('External config found but no data path defined, skipping import.', 'warn', 'builder');
                cb();
                return;
            }
            if (!Y.Lang.isArray(info.data)) {
                info.data = [ info.data ];
            }
            Y.log('Importing external documentation data.', 'info', 'builder');
            
            var stack = new Y.Parallel();
            info.data.forEach(function(i) {
                var base;
                if (i.match(/^https?:\/\//)) {
                    base = i.replace('data.json', '');
                    Y.use('io-base', stack.add(function() {
                        Y.log('Fetching: ' + i, 'info', 'builder');
                        Y.io(i, {
                            on: {
                                complete: stack.add(function(id, e) {
                                    Y.log('Received: ' + i, 'info', 'builder');
                                    var data = JSON.parse(e.responseText);
                                    data.base = base;
                                    //self.options.externalData = Y.mix(self.options.externalData || {}, data);
                                    if (!self.options.externalData) {
                                        self.options.externalData = [];
                                    }
                                    self.options.externalData.push(data);
                                })
                            }
                        });
                    }));
                } else {
                    base = path.dirname(path.resolve(i));
                    var data = Y.Files.getJSON(i);
                    data.base = base;
                    //self.options.externalData = Y.mix(self.options.externalData || {}, data);
                    if (!self.options.externalData) {
                        self.options.externalData = [];
                    }
                    self.options.externalData.push(data);
                }
            });
 
            stack.done(function() {
                Y.log('Finished fetching remote data', 'info', 'builder');
                self._mixExternal();
                cb();
            });
        },
        /**
        * The default tags to use in return descriptions (for Markdown).
        * @property defaultReturnTags
        * @type String
        */
        defaultReturnTags: DEFAULT_RETURN_TAGS,
        /**
        * The default tags to use in params descriptions (for Markdown).
        * @property defaultTags
        * @type String
        */
        defaultTags: 'p|' + DEFAULT_RETURN_TAGS,
        /**
        * File counter
        * @property files
        * @type Number
        */
        files: null,
        /**
        * Holder for project meta data
        * @property _meta
        * @type Object
        * @private
        */
        _meta: null,
        /**
        * Prep the meta data to be fed to Selleck
        * @method getProjectMeta
        * @return {Object} The project metadata
        */
        getProjectMeta: function() {
            var obj = {
                meta: {
                    yuiSeedUrl: 'http://yui.yahooapis.com/3.5.0/build/yui/yui-min.js',
                    yuiGridsUrl: 'http://yui.yahooapis.com/3.5.0/build/cssgrids/cssgrids-min.css'
                }
            };
            if (!this._meta) {
                try {
                    var meta,
                        theme = path.join(themeDir, 'theme.json');
                    Eif (Y.Files.exists(theme)) {
                        Y.log('Loading theme from ' + theme, 'info', 'builder');
                        meta = Y.Files.getJSON(theme);
                    } else if (DEFAULT_THEME !== themeDir) {
                        theme = path.join(DEFAULT_THEME, 'theme.json')
                        if (Y.Files.exists(theme)) {
                            Y.log('Loading theme from ' + theme, 'info', 'builder');
                            meta = Y.Files.getJSON(theme);
                        }
                    }
 
                    Eif (meta) {
                        obj.meta = meta;
                        this._meta = meta;
                    }
                } catch (e) {
                    console.error('Error', e);
                }
            } else {
                obj.meta = this._meta;
            }
            Y.each(this.data.project, function(v, k) {
                var key = k.substring(0, 1).toUpperCase() + k.substring(1, k.length);
                obj.meta['project' + key] = v;
            });
            return obj
        },
        /**
        * Populate the meta data for classes
        * @method populateClasses
        * @param {Object} opts The original options
        * @return {Object} The modified options
        */
        populateClasses: function(opts) {
            opts.meta.classes = [];
            Y.each(this.data.classes, function(v) {
                Iif (v.external) { return }
                opts.meta.classes.push({
                    displayName: v.name,
                    name: v.name,
                    namespace: v.namespace,
                    module: v.module,
                    description: v.description,
                    access: v.access || 'public'
                });
            });
            opts.meta.classes.sort(this.nameSort);
            return opts;
        },
        /**
        * Populate the meta data for modules
        * @method populateModules
        * @param {Object} opts The original options
        * @return {Object} The modified options
        */
        populateModules: function(opts) {
            var self = this;
            opts.meta.modules = [];
            opts.meta.allModules = [];
            Y.each(this.data.modules, function(v) {
                Iif (v.external) { return }
                opts.meta.allModules.push({ displayName: v.displayName || v.name, name: self.filterFileName(v.name), description: v.description });
                if (!v.is_submodule) {
                    var o = { displayName: v.displayName || v.name, name: self.filterFileName(v.name) };
                    Eif (v.submodules) {
                        o.submodules = [];
                        Y.each(v.submodules, function(i, k) {
                            moddef = self.data.modules[k];
                            Eif (moddef) {
                                o.submodules.push({
                                    displayName: k,
                                    description: moddef.description
                                });
                            } else {
                                //Y.log('Submodule data missing: ' + k + ' for ' + v.name, 'warn', 'builder');
                            }
                        });
                        o.submodules.sort(self.nameSort);
                    }
                    opts.meta.modules.push(o);
                }
            });
            opts.meta.modules.sort(this.nameSort);
            opts.meta.allModules.sort(this.nameSort);
            return opts;
        },
        /**
        * Populate the meta data for files
        * @method populateFiles
        * @param {Object} opts The original options
        * @return {Object} The modified options
        */
        populateFiles: function(opts) {
            var self = this;
            opts.meta.files = [];
            Y.each(this.data.files, function(v) {
                Iif (v.external) { return }
                opts.meta.files.push({ displayName: v.name, name: self.filterFileName(v.name), path: v.path || v.name });
            });
 
            var tree = {};
            var files = [];
            Y.each(this.data.files, function(v) {
                Iif (v.external) { return }
                files.push(v.name);
            });
            files.sort();
            Y.each(files, function(v) {
                var p = v.split('/'),
                    par;
                p.forEach(function(i, k) {
                    if (!par) {
                        if (!tree[i]) {
                            tree[i] = {};
                        }
                        par = tree[i];
                    } else {
                        if (!par[i]) {
                            par[i] = {};
                        }
                        if (k + 1 === p.length) {
                            par[i] = {
                                path: v,
                                name: self.filterFileName(v)
                            };
                        }
                        par = par[i];
                    }
                });
            });
 
            opts.meta.fileTree = tree;
 
            return opts;
        },
        /**
        * Parses file and line number from an item object and build's an HREF
        * @method addFoundAt
        * @param {Object} a The item to parse
        * @return {String} The parsed HREF
        */
        addFoundAt: function(a) {
            var self = this;
            if (a.file && a.line && !self.options.nocode) {
                a.foundAt = '../files/' + self.filterFileName(a.file) + '.html#l' + a.line;
                Iif (a.path) {
                    a.foundAt = a.path + '#l' + a.line;   
                }
            }
            return a;
        },
        /**
        * Augments the **DocParser** meta data to provide default values for certain keys as well as parses all descriptions
        * with the `Markdown Parser`
        * @method augmentData
        * @param {Object} o The object to recurse and augment
        * @return {Object} The augmented object
        */
        augmentData: function(o) {
            var self = this;
            o = self.addFoundAt(o);
            Y.each(o, function(i, k1) {
                if (i && i.forEach) {
                    Y.each(i, function(a, k) {
                        if (!(a instanceof Object)) {
                            return;
                        }
                        if (!a.type) {
                            a.type = 'Object'; //Default type is Object
                        }
                        Iif (a.final === '') {
                            a.final = true;
                        }
                        if (!a.description) {
                            a.description = ' ';
                        } else {
                            //a.description = markdown(a.description, true, self.defaultTags);
                            a.description = self.markdown(a.description);
                        }
                        Iif (a.example) {
                            a.example = self.markdown(a.example, true, self.defaultTags);
                        }
                        a = self.addFoundAt(a);
 
                        Y.each(a, function(c, d) {
                            if (c.forEach || (c instanceof Object)) {
                                c = self.augmentData(c);
                                a[d] = c;
                            }
                        });
 
                        o[k1][k] = a;
                    });
                } else if (i instanceof Object) {
                    i = self.addFoundAt(i);
                    Y.each(i, function(v, k) {
                        Iif (k === 'final') {
                            o[k1][k] = true;
                        }
                        if (k === 'description' || k === 'example') {
                            if (k1 === 'return') {
                                o[k1][k] = self.markdown(v, true, self.defaultReturnTags);
                            } else Iif (v.forEach || (v instanceof Object)) {
                                o[k1][k] = self.augmentData(v);
                            } else {
                                //o[k1][k] = markdown(v, true, self.defaultTags);
                                o[k1][k] = self.markdown(v);
                            }
                        }
                    });
                } else if (k1 === 'description' || k1 === 'example') {
                    //o[k1] = markdown(i, true, self.defaultTags);
                    o[k1] = self.markdown(i);
                }
            });
            return o;
        },
        /**
        * Makes the default directories needed
        * @method makeDirs
        * @param {Callback} cb The callback to execute after it's completed
        */
        makeDirs: function(cb) {
            var self = this;
            var dirs = ['classes', 'modules', 'files'];
            Iif (self.options.dumpview) {
                dirs.push('json');
            }
            var writeRedirect = function(dir, file, cb) {
                Y.Files.exists(file, function(x) {
                    Eif (x) {
                        var out = path.join(dir, 'index.html');
                        fs.createReadStream(file).pipe(fs.createWriteStream(out));
                    }
                    cb();
                });
            };
            var defaultIndex = path.join(themeDir, 'assets', 'index.html');
            var stack = new Y.Parallel();
            Y.log('Making default directories: ' + dirs.join(','), 'info', 'builder');
            dirs.forEach(function(d) {
                var dir = path.join(self.options.outdir, d);
                Y.Files.exists(dir, stack.add(function(x) {
                    Eif (!x) {
                        fs.mkdir(dir, 0777, stack.add(function() {
                            writeRedirect(dir, defaultIndex, stack.add(noop));
                        }));
                    } else {
                        writeRedirect(dir, defaultIndex, stack.add(noop));
                    }
                }));
            });
            stack.done(function() {
                Eif (cb) {
                    cb();
                }
            });
        },
 
 
	_resolveUrl: function(url, opts) {
            Eif(!url) {
               return null;
            }
            if ( url.indexOf("://") >= 0 ) {
                return url;
            }
            return path.join(opts.meta.projectRoot,url);
        },
 
        /**
        * Parses `<pre><code>` tags and adds the __prettyprint__ `className` to them
        * @method _parseCode
        * @private
        * @param {HTML} html The HTML to parse
        * @return {HTML} The parsed HTML
        */
        _parseCode: function (html) {
            html = html || '';
            //html = html.replace(/<pre><code>/g, '<pre class="code"><code class="prettyprint">');
            html = html.replace(/<pre><code>/g, '<pre class="code prettyprint"><code>');
            return html;
        },
        /**
        * Ported from [Selleck](https://github.com/rgrove/selleck), this handles ```'s in fields
        that are not parsed by the **Markdown** parser.
        * @method _inlineCode
        * @private
        * @param {HTML} html The HTML to parse
        * @return {HTML} The parsed HTML
        */
        _inlineCode: function(html) {
            html = html.replace(/\\`/g, '__{{SELLECK_BACKTICK}}__');
 
            html = html.replace(/`(.+?)`/g, function (match, code) {
                return '<code>' + Y.escapeHTML(code) + '</code>';
            });
 
            html = html.replace(/__\{\{SELLECK_BACKTICK\}\}__/g, '`');
 
            return html;
        },
        /**
        * Ported from [Selleck](https://github.com/rgrove/selleck)
        Renders the handlebars templates with the default View class.
        * @method render
        * @param {HTML} source The default template to parse
        * @param {Class} view The default view handler
        * @param {HTML} [layout=null] The HTML from the layout to use.
        * @param {Object} [partials=object] List of partials to include in this template
        * @param {Callback} callback
        * @param {Error} callback.err
        * @param {HTML} callback.html The assembled template markup
        */
        render: function(source, view, layout, partials, callback) {
            var html = [];
 
            function buffer(line) {
                html.push(line);
            }
 
            // Allow callback as third or fourth param.
            Iif (typeof partials === 'function') {
                callback = partials;
                partials = {};
            } else Iif (typeof layout === 'function') {
                callback = layout;
                layout = null;
            }
            var parts = Y.merge(partials || {}, { layout_content: source });
            Y.each(parts, function(source, name) {
                Y.Handlebars.registerPartial(name, source);
            });
 
            if (!TEMPLATE || !this.cacheTemplates) {
                TEMPLATE = Y.Handlebars.compile(layout);
            }
 
 
            var _v = {};
            for (var k in view) {
                if (Y.Lang.isFunction(view[k])) {
                    _v[k] = view[k]();
                } else {
                    _v[k] = view[k];
                }
            };
            html = TEMPLATE(_v);
            //html = html.replace(/{{&#x2F;/g, '{{/');
 
            
            //html = (Y.Handlebars.compile(html))({});
 
            html = this._inlineCode(html);
            callback(null, html);
        },
        /**
        * Render the index file
        * @method renderIndex
        * @param {Function} cb The callback fired when complete
        * @param {String} cb.html The HTML to render this view
        * @param {Object} cv.view The View Data
        */
        renderIndex: function(cb) {
            var self = this;
 
            Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function(err, opts) {
                opts.meta.title = self.data.project.name;
                opts.meta.projectRoot = './';
                opts.meta.projectAssets = './assets';
                opts.meta.projectLogo = self._resolveUrl(self.data.project.logo, opts);
                opts = self.populateClasses(opts);
                opts = self.populateModules(opts);
 
                var view   = new Y.DocView(opts.meta);
                self.render('{{>index}}', view, opts.layouts.main, opts.partials, function(err, html) {
                    self.files++;
                    cb(html, view);
                });
            });
        },
        /**
        * Generates the index.html file
        * @method writeIndex
        * @param {Callback} cb The callback to execute after it's completed
        */
        writeIndex: function(cb) {
            var self = this,
                stack = new Y.Parallel();
 
            Y.log('Preparing index.html', 'info', 'builder');
            self.renderIndex(stack.add(function(html, view) {
                stack.html = html;
                stack.view = view;
                Iif (self.options.dumpview) {
                    Y.Files.writeFile(path.join(self.options.outdir, 'json', 'index.json'), JSON.stringify(view), stack.add(noop));
                }
                Y.Files.writeFile(path.join(self.options.outdir, 'index.html'), html, stack.add(noop));
            }));
 
            stack.done(function(html, view) {
                Y.log('Writing index.html', 'info', 'builder');
                cb(stack.html, stack.view);
            });
        },
        /**
        * Render a module 
        * @method renderModule
        * @param {Function} cb The callback fired when complete
        * @param {String} cb.html The HTML to render this view
        * @param {Object} cv.view The View Data
        */
        renderModule: function(cb, data, layout) {
            var self = this;
            var stack = new Y.Parallel();
 
            data.displayName = data.name;
            data.name = self.filterFileName(data.name);
            Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function(err, opts) {
                opts.meta = Y.merge(opts.meta, data);
 
                //opts.meta.htmlTitle = v.name + ': ' + self.data.project.name;
                opts.meta.title = self.data.project.name;
 
                opts.meta.moduleName = data.displayName || data.name;
                opts.meta.moduleDescription = self._parseCode(self.markdown(data.description || ' '));
                opts.meta.file = data.file;
                opts.meta.line = data.line;
                opts.meta = self.addFoundAt(opts.meta);
                opts.meta.projectRoot = '../';
                opts.meta.projectAssets = '../assets';
                opts.meta.projectLogo = self._resolveUrl(self.data.project.logo, opts);
                opts = self.populateClasses(opts);
                opts = self.populateModules(opts);
                opts = self.populateFiles(opts);
 
                if (data.classes && Object.keys(data.classes).length) {
                    opts.meta.moduleClasses = [];
                    Y.each(Object.keys(data.classes), function(name) {
                        var i = self.data.classes[name];
                        Eif (i) {
                            opts.meta.moduleClasses.push({ name: i.name, displayName: i.name });
                        }
                    });
                    opts.meta.moduleClasses.sort(self.nameSort);
                }
                if (data.example && data.example.length) {
                    Eif (data.example.forEach) {
                        var e = '';
                        data.example.forEach(function(v) {
                            e += self._parseCode(self.markdown(v));
                        });
                        data.example = e;
                    } else {
                        data.example = self._parseCode(self.markdown(i.example));
                    }
                    opts.meta.example = data.example;
                }
                if (data.submodules && Object.keys(data.submodules).length) {
                    opts.meta.subModules = [];
                    Y.each(Object.keys(data.submodules), function(name) {
                        var i = self.data.modules[name];
                        Eif (i) {
                            opts.meta.subModules.push({ name: i.name, displayName: i.name, description: i.description });
                        }
                    });
                    opts.meta.subModules.sort(self.nameSort);
                }
 
                var view   = new Y.DocView(opts.meta);
                var mainLayout = opts.layouts[layout];
                self.render('{{>module}}', view, mainLayout, opts.partials, stack.add(function(err, html) {
                    self.files++;
                    stack.html = html;
                    stack.view = view;
                }));
            });
 
            stack.done(function() {
                cb(stack.html, stack.view);
            });
 
        },
        /**
        * Generates the module files under "out"/modules/
        * @method writeModules
        * @param {Callback} cb The callback to execute after it's completed
        */
        writeModules: function(cb, layout) {
            layout = layout || 'main';
            var self = this,
                stack = new Y.Parallel();
            stack.html = [];
            stack.view = [];
            
            var counter = 0;
                Object.keys(self.data.modules).forEach(function(k) {
                    Eif (!self.data.modules[k].external) {
                        counter++;
                    }
                });
            Y.log('Rendering and writing ' + counter + ' modules pages.', 'info', 'builder');
            Y.each(self.data.modules, function(v) {
                Iif (v.external) { return }
                self.renderModule(function(html, view) {
                    stack.html.push(html);
                    stack.view.push(view);
                    Iif (self.options.dumpview) {
                        Y.Files.writeFile(path.join(self.options.outdir, 'json', 'module_' + v.name + '.json'), JSON.stringify(view), stack.add(noop));
                    }
                    Y.Files.writeFile(path.join(self.options.outdir, 'modules', v.name + '.html'), html, stack.add(noop));
                }, v, layout);
            });
            stack.done(function() {
                Y.log('Finished writing module files', 'info', 'builder');
                cb(stack.html, stack.view);
            });
        },
        /**
        * Checks an array of items (class items) to see if an item is in that list
        * @method hasProperty
        * @param {Array} a The Array of items to check
        * @param {Object} b The object to find
        * @return Boolean
        */
        hasProperty: function(a, b) {
            var other = false;
            var h = Y.some(a, function(i, k) {
                if ((i.itemtype === b.itemtype) && (i.name === b.name)) {
                    other = k;
                    return true;
                }
            });
            return other;
        },
        /**
        * Counter for stepping into merges
        * @private
        * @property _mergeCounter
        * @type Number
        */
        _mergeCounter: null,
        /**
        * Merge superclass data into a child class
        * @method mergeExtends
        * @param {Object} info The item to extend
        * @param {Array} classItems The list of items to merge in
        * @param {Boolean} first Set for the first call
        */
        mergeExtends: function(info, classItems, first) {
            var self = this;
            self._mergeCounter = (first) ? 0 : (self._mergeCounter + 1);
 
            Iif (self._mergeCounter === 100) {
                throw('YUIDoc detected a loop extending class ' + info.name);
            }
            if (info.extends || info.uses) {
                var hasItems = {};
                hasItems[info.extends] = 1;
                Iif (info.uses) {
                    info.uses.forEach(function(v) {
                        hasItems[v] = 1;
                    });
                }
                self.data.classitems.forEach(function(v) {
                    //console.error(v.class, '==', info.extends);
                    if (hasItems[v.class]) {
                        Eif (!v.static) {
                            var override = self.hasProperty(classItems, v);
                            if (override === false) {
                                //This method was extended from the parent class but not over written
                                //console.error('Merging extends from', v.class, 'onto', info.name);
                                var q = Y.merge({}, v);
                                q.extended_from = v.class;
                                classItems.push(q);
                            } else {
                                //This method was extended from the parent and overwritten in this class
                                var q = Y.merge({}, v);
                                q = self.augmentData(q);
                                classItems[override].overwritten_from = q;
                            }
                        }
                    }
                });
                if (self.data.classes[info.extends]) {
                    if (self.data.classes[info.extends].extends || self.data.classes[info.extends].uses) {
                        //console.error('Stepping down to:', self.data.classes[info.extends]);
                        classItems = self.mergeExtends(self.data.classes[info.extends], classItems);
                    }
                }
            }
            return classItems;
        },
        /**
        * Render the class file
        * @method renderClass
        * @param {Function} cb The callback fired when complete
        * @param {String} cb.html The HTML to render this view
        * @param {Object} cv.view The View Data
        */
        renderClass: function(cb, data, layout) {
            var self = this;
            var stack = new Y.Parallel();
 
            Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function(err, opts) {
                //console.log(opts);
                Iif (err) {
                    console.log(err);
                }
                opts.meta = Y.merge(opts.meta, data);
 
                opts.meta.title = self.data.project.name;
                opts.meta.moduleName = data.name;
                opts.meta.file = data.file;
                opts.meta.line = data.line;
                opts.meta = self.addFoundAt(opts.meta);
                opts.meta.projectRoot = '../';
                opts.meta.projectAssets = '../assets';
                opts.meta.projectLogo = self._resolveUrl(self.data.project.logo, opts);
 
                opts = self.populateClasses(opts);
                opts = self.populateModules(opts);
                opts = self.populateFiles(opts);
 
                opts.meta.classDescription = self._parseCode(self.markdown(data.description || ' '));
 
                opts.meta.methods = [];
                opts.meta.properties = [];
                opts.meta.attrs = [];
                opts.meta.events = [];
                opts.meta.extension_for = null;
                Iif (data.uses) {
                    opts.meta.uses = data.uses;
                }
                Iif (data.entension_for && data.extension_for.length) {
                    opts.meta.extension_for = data.extension_for;
                }
 
                if (data.extends) {
                    opts.meta.extends = data.extends;
                }
 
                var classItems = [];
                self.data.classitems.forEach(function(i) {
                    if (i.class === data.name) {
                        classItems.push(i);
                    }
                });
 
                classItems = self.mergeExtends(data, classItems, true);
 
                if (data.is_constructor) {
                    var i = Y.mix({}, data);
                    i = self.augmentData(i);
                    i.paramsList = [];
                    Iif (i.params) {
                        i.params.forEach(function(p, v) {
                            var name = p.name;
                            if (p.optional) {
                                name = '[' + name + ((p.optdefault) ? '=' + p.optdefault : '') + ']'
                            }
                            i.paramsList.push(name);
                        });
                    }
                    //i.methodDescription = self._parseCode(markdown(i.description));
                    i.hasAccessType = i.access;
                    i.hasParams = i.paramsList.length;
                    Iif (i.paramsList.length) {
                        i.paramsList = i.paramsList.join(', ');
                    } else {
                        i.paramsList = ' ';
                    }
                    i.returnType = ' ';
                    Iif (i.return) {
                        i.hasReturn = true;
                        i.returnType = i.return.type;
                    }
                    //console.error(i);
                    opts.meta.is_constructor = [i];
                    if (i.example && i.example.length) {
                        Eif (i.example.forEach) {
                            var e = '';
                            i.example.forEach(function(v) {
                                e += self._parseCode(self.markdown(v));
                            });
                            i.example = e;
                        } else {
                            i.example = self._parseCode(self.markdown(i.example));
                        }
                    }
                }
 
                classItems.forEach(function(i) {
                    switch (i.itemtype) {
                        case 'method':
                            i = self.augmentData(i);
                            i.paramsList = [];
                            if (i.params && i.params.forEach) {
                                i.params.forEach(function(p, v) {
                                    var name = p.name;
                                    if (p.optional) {
                                        name = '[' + name + ((p.optdefault) ? '=' + p.optdefault : '') + ']'
                                    }
                                    i.paramsList.push(name);
                                });
                            }
                            //i.methodDescription = self._parseCode(markdown(i.description || ''));
                            i.methodDescription = self._parseCode(i.description);
                            if (i.example && i.example.length) {
                                if (i.example.forEach) {
                                    var e = '';
                                    i.example.forEach(function(v) {
                                        e += self._parseCode(self.markdown(v));
                                    });
                                    i.example = e;
                                } else {
                                    i.example = self._parseCode(self.markdown(i.example));
                                }
                            }
                            i.hasAccessType = i.access;
                            i.hasParams = i.paramsList.length;
                            if (i.paramsList.length) {
                                i.paramsList = i.paramsList.join(', ');
                            } else {
                                i.paramsList = ' ';
                            }
                            i.returnType = ' ';
                            if (i.return) {
                                i.hasReturn = true;
                                i.returnType = i.return.type;
                            }
 
                            // If this item is provided by a module other
                            // than the module that provided the original
                            // class, add the original module name to the
                            // item's `providedBy` property so we can
                            // indicate the relationship.
                            if ((i.submodule || i.module) !== (data.submodule || data.module)) {
                                i.providedBy = (i.submodule || i.module);
                            }
 
                            opts.meta.methods.push(i);
                            break;
                        case 'property':
                            i = self.augmentData(i);
                            //i.propertyDescription = self._parseCode(markdown(i.description || ''));
                            i.propertyDescription = self._parseCode(i.description);
                            if (!i.type) {
                                i.type = 'unknown';
                            }
                            Iif (i.final === '') {
                                i.final = true;
                            }
                            Iif (i.example && i.example.length) {
                                if (i.example.forEach) {
                                    var e = '';
                                    i.example.forEach(function(v) {
                                        e += self._parseCode(self.markdown(v));
                                    });
                                    i.example = e;
                                } else {
                                    i.example = self._parseCode(self.markdown(i.example));
                                }
                            }
 
                            // If this item is provided by a module other
                            // than the module that provided the original
                            // class, add the original module name to the
                            // item's `providedBy` property so we can
                            // indicate the relationship.
                            if ((i.submodule || i.module) !== (data.submodule || data.module)) {
                                i.providedBy = (i.submodule || i.module);
                            }
 
                            opts.meta.properties.push(i);
                            break;
 
                        case 'attribute': // fallthru
                        case 'config':
                            i = self.augmentData(i);
                            //i.attrDescription = self._parseCode(markdown(i.description || ''));
                            i.attrDescription = self._parseCode(i.description);
 
                            Iif (i.itemtype === 'config') {
                                i.config = true;
                            } else {
                                i.emit = self.options.attributesEmit;
                            }
                            if (i.readonly === '') {
                                i.readonly = true;
                            }
 
                            Iif (i.example && i.example.length) {
                                if (i.example.forEach) {
                                    var e = '';
                                    i.example.forEach(function(v) {
                                        e += self._parseCode(self.markdown(v));
                                    });
                                    i.example = e;
                                } else {
                                    i.example = self._parseCode(self.markdown(i.example));
                                }
                            }
 
                            // If this item is provided by a module other
                            // than the module that provided the original
                            // class, add the original module name to the
                            // item's `providedBy` property so we can
                            // indicate the relationship.
                            Iif ((i.submodule || i.module) !== (data.submodule || data.module)) {
                                i.providedBy = (i.submodule || i.module);
                            }
 
                            opts.meta.attrs.push(i);
                            break;
                        case 'event':
                            i = self.augmentData(i);
                            //i.eventDescription = self._parseCode(markdown(i.description || ''));
                            i.eventDescription = self._parseCode(i.description);
 
                            Iif (i.example && i.example.length) {
                                if (i.example.forEach) {
                                    var e = '';
                                    i.example.forEach(function(v) {
                                        e += self._parseCode(self.markdown(v));
                                    });
                                    i.example = e;
                                } else {
                                    i.example = self._parseCode(self.markdown(i.example));
                                }
                            }
 
                            // If this item is provided by a module other
                            // than the module that provided the original
                            // class, add the original module name to the
                            // item's `providedBy` property so we can
                            // indicate the relationship.
                            Iif ((i.submodule || i.module) !== (data.submodule || data.module)) {
                                i.providedBy = (i.submodule || i.module);
                            }
 
                            opts.meta.events.push(i);
                            break;
                    }
                });
 
                opts.meta.attrs.sort(self.nameSort);
                opts.meta.events.sort(self.nameSort);
                opts.meta.methods.sort(self.nameSort);
                opts.meta.properties.sort(self.nameSort);
 
                if (!opts.meta.methods.length) {
                    delete opts.meta.methods;
                }
                if (!opts.meta.properties.length) {
                    delete opts.meta.properties;
                }
                if (!opts.meta.attrs.length) {
                    delete opts.meta.attrs;
                }
                if (!opts.meta.events.length) {
                    delete opts.meta.events;
                }
 
                var view   = new Y.DocView(opts.meta);
                var mainLayout = opts.layouts[layout];
                self.render('{{>classes}}', view, mainLayout, opts.partials, stack.add(function(err, html) {
                    self.files++;
                    stack.html = html;
                    stack.view = view;
                    stack.opts = opts;
                }));
            });
 
            stack.done(function() {
                cb(stack.html, stack.view, stack.opts);
            });
        },
        /**
        * Generates the class files under "out"/classes/
        * @method writeClasses
        * @param {Callback} cb The callback to execute after it's completed
        */
        writeClasses: function(cb, layout) {
            layout = layout || 'main';
            var self = this,
                stack = new Y.Parallel();
            stack.html = [];
            stack.view = [];
 
            var counter = 0;
                Object.keys(self.data.classes).forEach(function(k) {
                    Eif (!self.data.classes[k].external) {
                        counter++;
                    }
                });
            Y.log('Rendering and writing ' + counter + ' class pages.', 'info', 'builder');
            Y.each(self.data.classes, function(v) {
                Iif (v.external) { return }
                self.renderClass(stack.add(function(html, view) {
                    stack.html.push(html);
                    stack.view.push(view);
                    Iif (self.options.dumpview) {
                        Y.Files.writeFile(path.join(self.options.outdir, 'json', 'classes_' + v.name + '.json'), JSON.stringify(view), stack.add(noop));
                    }
                    Y.Files.writeFile(path.join(self.options.outdir, 'classes', v.name + '.html'), html, stack.add(noop));
                }), v, layout);
            });
            stack.done(function() {
                Y.log('Finished writing class files', 'info', 'builder');
                cb(stack.html, stack.view);
            });
        },
        /**
        * Sort method of array of objects with a property called __name__
        * @method nameSort
        * @param {Object} a First object to compare
        * @param {Object} b Second object to compare
        * @return {Number} 1, -1 or 0 for sorting.
        */
        nameSort: function(a, b) {
            if (!a.name || !b.name) {
                return 0;
            }
            var an = a.name.toLowerCase(),
                bn = b.name.toLowerCase(),
                ret = 0;
 
            if (an < bn) {
                ret = -1;
            }
            if (an > bn) {
                ret =  1
            }
            return ret;
        },
        /**
        * Generates the syntax files under `"out"/files/`
        * @method writeFiles
        * @param {Callback} cb The callback to execute after it's completed
        */
        writeFiles: function(cb, layout) {
            layout = layout || 'main';
            var self = this,
                stack = new Y.Parallel();
            stack.html = [];
            stack.view = [];
 
            var counter = 0;
                Object.keys(self.data.files).forEach(function(k) {
                    Eif (!self.data.files[k].external) {
                        counter++;
                    }
                });
            Y.log('Rendering and writing ' + counter + ' source files.', 'info', 'builder');
            Y.each(self.data.files, function(v) {
                Iif (v.external) { return }
                self.renderFile(stack.add(function(html, view, data) {
                    Iif (!view || !data) {
                        return;
                    }
                    stack.html.push(html);
                    stack.view.push(view);
                    Iif (self.options.dumpview) {
                        Y.Files.writeFile(path.join(self.options.outdir, 'json', 'files_' + self.filterFileName(data.name) + '.json'), JSON.stringify(view), stack.add(noop));
                    }
                    Y.Files.writeFile(path.join(self.options.outdir, 'files', self.filterFileName(data.name) + '.html'), html, stack.add(noop));
                }), v, layout);
            });
            stack.done(function() {
                Y.log('Finished writing source files', 'info', 'builder');
                cb(stack.html, stack.view);
            });
        },
        /**
        * Render the source file
        * @method renderFile
        * @param {Function} cb The callback fired when complete
        * @param {String} cb.html The HTML to render this view
        * @param {Object} cv.view The View Data
        */
        renderFile: function(cb, data, layout) {
            var self = this;
            
            Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function(err, opts) {
                Iif (err) {
                    console.log(err);
                }
                Iif (!data.name) {
                    return;
                }
 
                opts.meta = Y.merge(opts.meta, data);
 
                opts.meta.title = self.data.project.name;
                opts.meta.moduleName = data.name;
                opts.meta.projectRoot = '../';
                opts.meta.projectAssets = '../assets';
                opts.meta.projectLogo = self._resolveUrl(self.data.project.logo, opts);
 
                opts = self.populateClasses(opts);
                opts = self.populateModules(opts);
                opts = self.populateFiles(opts);
 
                opts.meta.fileName = data.name;
                fs.readFile(opts.meta.fileName, Y.charset, Y.rbind(function(err, str, opts, data) {
                    Iif (err) {
                        Y.log(err, 'error', 'builder');
                        cb(err);
                        return;
                    }
 
                    Iif (typeof self.options.tabspace === 'string') {
                        str = str.replace(/\t/g, self.options.tabspace);
                    }
                    
                    opts.meta.fileData = str;
                    var view = new Y.DocView(opts.meta, 'index');
                    var mainLayout = opts.layouts[layout];
                    self.render('{{>files}}', view, mainLayout, opts.partials, function(err, html) {
                        self.files++;
                        cb(html, view, data);
                    });
 
                }, this, opts, data));
            });
 
        },
        /**
        * Write the API meta data used for the AutoComplete widget
        * @method writeAPIMeta
        * @param {Callback} cb The callback to execute when complete
        * @async
        */
        writeAPIMeta: function(cb) {
            Y.log('Writing API Meta Data', 'info', 'builder');
            var self = this;
            this.renderAPIMeta(function(js) {
                fs.writeFile(path.join(self.options.outdir, 'api.js'), js, Y.charset, cb);
            });
        },
        /**
        * Render the API meta and return the Javascript
        * @method renderAPIMeta
        * @param {Callback} cb The callback
        * @async
        */
        renderAPIMeta: function(cb) {
 
            var opts = { meta: {} }, self = this;
            opts = this.populateClasses(opts);
            opts = this.populateModules(opts);
 
            ['classes', 'modules'].forEach(function(id) {
                opts.meta[id].forEach(function(v, k) {
                    opts.meta[id][k] = v.name;
                    if (v.submodules) {
                        v.submodules.forEach(function(s) {
                            opts.meta[id].push(s.displayName);
                        });
                    }
                });
                opts.meta[id].sort();
            });
            
            var apijs = 'YUI.add("yuidoc-meta", function(Y) {\n' +
                '   Y.YUIDoc = { meta: ' + JSON.stringify(opts.meta, null, 4) + ' };\n' +
                '});';
 
            cb(apijs);
        },
        /**
        * Normalizes a file path to a writable filename:
        *
        *    var path = 'lib/file.js';
        *    returns 'lib_file.js';
        *
        * @method filterFileName
        * @param {String} f The filename to normalize
        * @return {String} The filtered file path
        */
        filterFileName: function(f) {
            return f.replace(/[\/\\]/g, '_');
        },
        /**
        * Compiles the templates from the meta-data provided by DocParser
        * @method compile
        * @param {Callback} cb The callback to execute after it's completed
        */
        compile: function(cb) {
            var self = this;
            var starttime = (new Date()).getTime();
            Y.log('Compiling Templates', 'info', 'builder');
 
            this.mixExternal(function() {
                self.makeDirs(function() {
                    Y.log('Copying Assets', 'info', 'builder');
                    Eif (!Y.Files.isDirectory(path.join(self.options.outdir, 'assets'))) {
                        fs.mkdirSync(path.join(self.options.outdir, 'assets'), 0777);
                    }
                    Y.Files.copyAssets([path.join(DEFAULT_THEME, 'assets'), path.join(themeDir, 'assets')], path.join(self.options.outdir, 'assets'), false, function() {
                        var cstack = new Y.Parallel();
                        
                        self.writeModules(cstack.add(function() {
                            self.writeClasses(cstack.add(function() {
                                Eif (!self.options.nocode) {
                                    self.writeFiles(cstack.add(noop));
                                }
                            }));
                        }));
                        /*
                        self.writeModules(cstack.add(noop));
                        self.writeClasses(cstack.add(noop));
                        if (!self.options.nocode) {
                            self.writeFiles(cstack.add(noop));
                        }
                        */
                        self.writeIndex(cstack.add(noop));
                        self.writeAPIMeta(cstack.add(noop));
 
                        cstack.done(function() {
                            var endtime = (new Date()).getTime();
                            var timer = ((endtime - starttime) / 1000) + ' seconds';
                            Y.log('Finished writing ' + self.files + ' files in ' + timer, 'info', 'builder');
                            Eif (cb) { cb(); }
                        });
                    });
                });
            });
        }
    }
});