models.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. #!/usr/bin/env node
  2. /* jshint esversion: 6 */
  3. /* eslint "no-console": off */
  4. const fs = require('fs');
  5. const path = require('path');
  6. const process = require('process');
  7. const child_process = require('child_process');
  8. const http = require('http');
  9. const https = require('https');
  10. const url = require('url');
  11. const protobuf = require('../source/protobuf');
  12. const flatbuffers = require('../source/flatbuffers');
  13. const sidebar = require('../source/view-sidebar.js');
  14. const view = require('../source/view.js');
  15. const zip = require('../source/zip');
  16. const gzip = require('../source/gzip');
  17. const tar = require('../source/tar');
  18. const base = require('../source/base');
  19. const xmldom = require('xmldom');
  20. global.Int64 = base.Int64;
  21. global.Uint64 = base.Uint64;
  22. global.protobuf = protobuf;
  23. global.flatbuffers = flatbuffers;
  24. global.DOMParser = xmldom.DOMParser;
  25. global.TextDecoder = class {
  26. constructor(encoding) {
  27. global.TextDecoder._TextDecoder = global.TextDecoder._TextDecoder || require('util').TextDecoder;
  28. if (encoding !== 'ascii') {
  29. this._textDecoder = new global.TextDecoder._TextDecoder(encoding);
  30. }
  31. }
  32. decode(data) {
  33. if (this._textDecoder) {
  34. return this._textDecoder.decode(data);
  35. }
  36. if (data.length < 32) {
  37. return String.fromCharCode.apply(null, data);
  38. }
  39. const buffer = [];
  40. let start = 0;
  41. do {
  42. let end = start + 32;
  43. if (end > data.length) {
  44. end = data.length;
  45. }
  46. buffer.push(String.fromCharCode.apply(null, data.subarray(start, end)));
  47. start = end;
  48. }
  49. while (start < data.length);
  50. return buffer.join('');
  51. }
  52. };
  53. const filter = process.argv.length > 2 ? process.argv[2] : null;
  54. const type = filter ? filter.split('/').shift() : '';
  55. const dataFolder = __dirname + '/data';
  56. const items = JSON.parse(fs.readFileSync(__dirname + '/models.json', 'utf-8'));
  57. class TestHost {
  58. constructor() {
  59. this._document = new HTMLDocument();
  60. }
  61. get document() {
  62. return this._document;
  63. }
  64. initialize(/* view */) {
  65. return Promise.resolve();
  66. }
  67. start() {
  68. }
  69. environment(name) {
  70. if (name == 'zoom') {
  71. return 'none';
  72. }
  73. return null;
  74. }
  75. screen(/* name */) {
  76. }
  77. require(id) {
  78. try {
  79. const file = path.join(path.join(__dirname, '../source'), id + '.js');
  80. return Promise.resolve(require(file));
  81. }
  82. catch (error) {
  83. return Promise.reject(error);
  84. }
  85. }
  86. request(base, file, encoding) {
  87. const pathname = path.join(base || path.join(__dirname, '../source'), file);
  88. if (!fs.existsSync(pathname)) {
  89. return Promise.reject(new Error("File not found '" + file + "'."));
  90. }
  91. return Promise.resolve(fs.readFileSync(pathname, encoding));
  92. }
  93. event(/* category, action, label, value */) {
  94. }
  95. exception(err /*, fatal */) {
  96. this._raise('exception', { exception: err });
  97. }
  98. on(event, callback) {
  99. this._events = this._events || {};
  100. this._events[event] = this._events[event] || [];
  101. this._events[event].push(callback);
  102. }
  103. _raise(event, data) {
  104. if (this._events && this._events[event]) {
  105. for (const callback of this._events[event]) {
  106. callback(this, data);
  107. }
  108. }
  109. }
  110. }
  111. class TestContext {
  112. constructor(host, folder, identifier, buffer) {
  113. this._host = host;
  114. this._folder = folder;
  115. this._identifier = identifier;
  116. this._buffer = buffer;
  117. }
  118. request(file, encoding) {
  119. return this._host.request(this._folder, file, encoding);
  120. }
  121. get identifier() {
  122. return this._identifier;
  123. }
  124. get buffer() {
  125. return this._buffer;
  126. }
  127. }
  128. class HTMLDocument {
  129. constructor() {
  130. this._elements = {};
  131. this.documentElement = new HTMLHtmlElement();
  132. this.body = new HTMLBodyElement();
  133. }
  134. createElement(/* name */) {
  135. return new HTMLElement();
  136. }
  137. createElementNS(/* namespace, name */) {
  138. return new HTMLElement();
  139. }
  140. createTextNode(/* text */) {
  141. return new HTMLElement();
  142. }
  143. getElementById(id) {
  144. let element = this._elements[id];
  145. if (!element) {
  146. element = new HTMLElement();
  147. this._elements[id] = element;
  148. }
  149. return element;
  150. }
  151. addEventListener(/* event, callback */) {
  152. }
  153. removeEventListener(/* event, callback */) {
  154. }
  155. }
  156. class HTMLElement {
  157. constructor() {
  158. this._childNodes = [];
  159. this._attributes = new Map();
  160. this._style = new CSSStyleDeclaration();
  161. }
  162. get style() {
  163. return this._style;
  164. }
  165. appendChild(node) {
  166. this._childNodes.push(node);
  167. }
  168. setAttribute(name, value) {
  169. this._attributes.set(name, value);
  170. }
  171. hasAttribute(name) {
  172. return this._attributes.has(name);
  173. }
  174. getAttribute(name) {
  175. return this._attributes.get(name);
  176. }
  177. getBBox() {
  178. return { x: 0, y: 0, width: 10, height: 10 };
  179. }
  180. getElementsByClassName(name) {
  181. let elements = [];
  182. for (const node of this._childNodes) {
  183. if (node instanceof HTMLElement) {
  184. elements = elements.concat(node.getElementsByClassName(name));
  185. if (node.hasAttribute('class') &&
  186. node.getAttribute('class').split(' ').find((text) => text === name)) {
  187. elements.push(node);
  188. }
  189. }
  190. }
  191. return elements;
  192. }
  193. addEventListener(/* event, callback */) {
  194. }
  195. removeEventListener(/* event, callback */) {
  196. }
  197. get classList() {
  198. return new DOMTokenList(this);
  199. }
  200. }
  201. class HTMLHtmlElement extends HTMLElement {
  202. }
  203. class HTMLBodyElement extends HTMLElement{
  204. }
  205. class CSSStyleDeclaration {
  206. constructor() {
  207. this._properties = new Map();
  208. }
  209. setProperty(name, value) {
  210. this._properties.set(name, value);
  211. }
  212. }
  213. class DOMTokenList {
  214. add(/* token */) {
  215. }
  216. }
  217. function makeDir(dir) {
  218. if (!fs.existsSync(dir)){
  219. fs.mkdirSync(dir, { recursive: true });
  220. }
  221. }
  222. function decompress(buffer, identifier) {
  223. let archive = null;
  224. const extension = identifier.split('.').pop().toLowerCase();
  225. if (extension == 'gz' || extension == 'tgz') {
  226. archive = new gzip.Archive(buffer);
  227. if (archive.entries.length == 1) {
  228. const entry = archive.entries[0];
  229. if (entry.name) {
  230. identifier = entry.name;
  231. }
  232. else {
  233. identifier = identifier.substring(0, identifier.lastIndexOf('.'));
  234. if (extension == 'tgz') {
  235. identifier += '.tar';
  236. }
  237. }
  238. buffer = entry.data;
  239. }
  240. }
  241. switch (identifier.split('.').pop().toLowerCase()) {
  242. case 'tar':
  243. archive = new tar.Archive(buffer);
  244. break;
  245. case 'zip':
  246. archive = new zip.Archive(buffer);
  247. break;
  248. }
  249. return archive;
  250. }
  251. function request(location, cookie) {
  252. const options = { rejectUnauthorized: false };
  253. let httpRequest = null;
  254. switch (url.parse(location).protocol) {
  255. case 'http:':
  256. httpRequest = http.request(location, options);
  257. break;
  258. case 'https:':
  259. httpRequest = https.request(location, options);
  260. break;
  261. }
  262. if (cookie && cookie.length > 0) {
  263. httpRequest.setHeader('Cookie', cookie);
  264. }
  265. return new Promise((resolve, reject) => {
  266. httpRequest.on('response', (response) => {
  267. resolve(response);
  268. });
  269. httpRequest.on('error', (error) => {
  270. reject(error);
  271. });
  272. httpRequest.end();
  273. });
  274. }
  275. function downloadFile(location, cookie) {
  276. return request(location, cookie).then((response) => {
  277. if (response.statusCode == 200 &&
  278. url.parse(location).hostname == 'drive.google.com' &&
  279. response.headers['set-cookie'].some((cookie) => cookie.startsWith('download_warning_'))) {
  280. cookie = response.headers['set-cookie'];
  281. const download = cookie.filter((cookie) => cookie.startsWith('download_warning_')).shift();
  282. const confirm = download.split(';').shift().split('=').pop();
  283. location = location + '&confirm=' + confirm;
  284. return downloadFile(location, cookie);
  285. }
  286. if (response.statusCode == 301 || response.statusCode == 302) {
  287. location = url.parse(response.headers.location).hostname ?
  288. response.headers.location :
  289. url.parse(location).protocol + '//' + url.parse(location).hostname + response.headers.location;
  290. return downloadFile(location, cookie);
  291. }
  292. if (response.statusCode != 200) {
  293. throw new Error(response.statusCode.toString() + ' ' + location);
  294. }
  295. return new Promise((resolve, reject) => {
  296. let position = 0;
  297. const data = [];
  298. const length = response.headers['content-length'] ? Number(response.headers['content-length']) : -1;
  299. response.on('data', (chunk) => {
  300. position += chunk.length;
  301. if (length >= 0) {
  302. const label = location.length > 70 ? location.substring(0, 66) + '...' : location;
  303. process.stdout.write(' (' + (' ' + Math.floor(100 * (position / length))).slice(-3) + '%) ' + label + '\r');
  304. }
  305. else {
  306. process.stdout.write(' ' + position + ' bytes\r');
  307. }
  308. data.push(chunk);
  309. });
  310. response.on('end', () => {
  311. resolve(Buffer.concat(data));
  312. });
  313. response.on('error', (error) => {
  314. reject(error);
  315. });
  316. });
  317. });
  318. }
  319. function download(folder, targets, sources) {
  320. if (targets.every((file) => fs.existsSync(folder + '/' + file))) {
  321. return Promise.resolve();
  322. }
  323. if (!sources) {
  324. return Promise.reject(new Error('Download source not specified.'));
  325. }
  326. let source = '';
  327. let sourceFiles = [];
  328. const startIndex = sources.indexOf('[');
  329. const endIndex = sources.indexOf(']');
  330. if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
  331. sourceFiles = sources.substring(startIndex + 1, endIndex).split(',').map((sourceFile) => sourceFile.trim());
  332. source = sources.substring(0, startIndex);
  333. sources = sources.substring(endIndex + 1);
  334. if (sources.startsWith(',')) {
  335. sources = sources.substring(1);
  336. }
  337. }
  338. else {
  339. const commaIndex = sources.indexOf(',');
  340. if (commaIndex != -1) {
  341. source = sources.substring(0, commaIndex);
  342. sources = sources.substring(commaIndex + 1);
  343. }
  344. else {
  345. source = sources;
  346. sources = '';
  347. }
  348. }
  349. for (const target of targets) {
  350. makeDir(path.dirname(folder + '/' + target));
  351. }
  352. return downloadFile(source).then((data) => {
  353. if (sourceFiles.length > 0) {
  354. if (process.stdout.clearLine) {
  355. process.stdout.clearLine();
  356. }
  357. process.stdout.write(' decompress...\r');
  358. const archive = decompress(data, source.split('?').shift().split('/').pop());
  359. for (const file of sourceFiles) {
  360. if (process.stdout.clearLine) {
  361. process.stdout.clearLine();
  362. }
  363. process.stdout.write(' write ' + file + '\n');
  364. const entry = archive.entries.filter((entry) => entry.name == file)[0];
  365. if (!entry) {
  366. throw new Error("Entry not found '" + file + '. Archive contains entries: ' + JSON.stringify(archive.entries.map((entry) => entry.name)) + " .");
  367. }
  368. const target = targets.shift();
  369. fs.writeFileSync(folder + '/' + target, entry.data, null);
  370. }
  371. }
  372. else {
  373. const target = targets.shift();
  374. if (process.stdout.clearLine) {
  375. process.stdout.clearLine();
  376. }
  377. process.stdout.write(' write ' + target + '\r');
  378. fs.writeFileSync(folder + '/' + target, data, null);
  379. }
  380. if (process.stdout.clearLine) {
  381. process.stdout.clearLine();
  382. }
  383. if (sources.length > 0) {
  384. return download(folder, targets, sources);
  385. }
  386. return;
  387. });
  388. }
  389. function script(folder, targets, command, args) {
  390. if (targets.every((file) => fs.existsSync(folder + '/' + file))) {
  391. return Promise.resolve();
  392. }
  393. return new Promise((resolve, reject) => {
  394. try {
  395. const comspec = process.env.COMSPEC;
  396. if (process.platform === 'win32' && process.env.SHELL) {
  397. process.env.COMSPEC = process.env.SHELL;
  398. command = '/' + command.split(':').join('').split('\\').join('/');
  399. }
  400. child_process.execSync(command + ' ' + args, { stdio: [ 0, 1 , 2] });
  401. process.env.COMSPEC = comspec;
  402. resolve();
  403. }
  404. catch (error) {
  405. reject(error);
  406. }
  407. });
  408. }
  409. function loadModel(target, item) {
  410. const host = new TestHost();
  411. const exceptions = [];
  412. host.on('exception', (_, data) => {
  413. exceptions.push(data.exception);
  414. });
  415. const folder = path.dirname(target);
  416. const identifier = path.basename(target);
  417. const size = fs.statSync(target).size;
  418. const buffer = new Uint8Array(size);
  419. const fd = fs.openSync(target, 'r');
  420. fs.readSync(fd, buffer, 0, size, 0);
  421. fs.closeSync(fd);
  422. const context = new TestContext(host, folder, identifier, buffer);
  423. const modelFactoryService = new view.ModelFactoryService(host);
  424. let opened = false;
  425. return modelFactoryService.open(context).then((model) => {
  426. if (opened) {
  427. throw new Error("Model opened more than once '" + target + "'.");
  428. }
  429. opened = true;
  430. if (!model.format || (item.format && model.format != item.format)) {
  431. throw new Error("Invalid model format '" + model.format + "'.");
  432. }
  433. if (item.producer && model.producer != item.producer) {
  434. throw new Error("Invalid producer '" + model.producer + "'.");
  435. }
  436. if (item.runtime && model.runtime != item.runtime) {
  437. throw new Error("Invalid runtime '" + model.runtime + "'.");
  438. }
  439. model.version;
  440. model.description;
  441. model.author;
  442. model.license;
  443. for (const graph of model.graphs) {
  444. for (const input of graph.inputs) {
  445. input.name.toString();
  446. input.name.length;
  447. for (const argument of input.arguments) {
  448. argument.name.toString();
  449. argument.name.length;
  450. if (argument.type) {
  451. argument.type.toString();
  452. }
  453. }
  454. }
  455. for (const output of graph.outputs) {
  456. output.name.toString();
  457. output.name.length;
  458. for (const argument of output.arguments) {
  459. argument.name.toString();
  460. argument.name.length;
  461. if (argument.type) {
  462. argument.type.toString();
  463. }
  464. }
  465. }
  466. for (const node of graph.nodes) {
  467. node.type.toString();
  468. node.type.length;
  469. if (typeof node.type != 'string') {
  470. throw new Error("Invalid node type '" + JSON.stringify(node.type) + "'.");
  471. }
  472. node.name.toString();
  473. node.name.length;
  474. node.description;
  475. const metadata = node.metadata;
  476. if (metadata !== null && metadata !== undefined && (typeof metadata !== 'object' || !metadata.name)) {
  477. throw new Error("Invalid metadata object '" + node.type + "'.");
  478. }
  479. sidebar.DocumentationSidebar.formatDocumentation(node.metadata);
  480. node.attributes.slice();
  481. for (const attribute of node.attributes) {
  482. attribute.name.toString();
  483. attribute.name.length;
  484. let value = sidebar.NodeSidebar.formatAttributeValue(attribute.value, attribute.type);
  485. if (value && value.length > 1000) {
  486. value = value.substring(0, 1000) + '...';
  487. }
  488. value = value.split('<');
  489. }
  490. for (const input of node.inputs) {
  491. input.name.toString();
  492. input.name.length;
  493. for (const argument of input.arguments) {
  494. argument.name.toString();
  495. argument.name.length;
  496. argument.description;
  497. if (argument.type) {
  498. argument.type.toString();
  499. }
  500. if (argument.initializer) {
  501. argument.initializer.toString();
  502. argument.initializer.type.toString();
  503. }
  504. }
  505. }
  506. for (const output of node.outputs) {
  507. output.name.toString();
  508. output.name.length;
  509. for (const argument of output.arguments) {
  510. argument.name.toString();
  511. argument.name.length;
  512. if (argument.type) {
  513. argument.type.toString();
  514. }
  515. }
  516. }
  517. if (node.chain) {
  518. for (const chain of node.chain) {
  519. chain.name.toString();
  520. chain.name.length;
  521. }
  522. }
  523. // new sidebar.NodeSidebar(host, node);
  524. }
  525. }
  526. if (exceptions.length > 0) {
  527. throw exceptions[0];
  528. }
  529. return model;
  530. });
  531. }
  532. function render(model) {
  533. try {
  534. const host = new TestHost();
  535. const currentView = new view.View(host);
  536. if (!currentView.showAttributes) {
  537. currentView.toggleAttributes();
  538. }
  539. if (!currentView.showInitializers) {
  540. currentView.toggleInitializers();
  541. }
  542. return currentView.renderGraph(model, model.graphs[0]);
  543. }
  544. catch (error) {
  545. return Promise.reject(error);
  546. }
  547. }
  548. function next() {
  549. if (items.length == 0) {
  550. return;
  551. }
  552. const item = items.shift();
  553. if (!item.type) {
  554. console.error("Property 'type' is required for item '" + JSON.stringify(item) + "'.");
  555. return;
  556. }
  557. if (type && item.type !== type) {
  558. next();
  559. return;
  560. }
  561. const targets = item.target.split(',');
  562. const target = targets[0];
  563. const folder = dataFolder + '/' + item.type;
  564. const name = item.type + '/' + target;
  565. if (filter && !name.startsWith(filter)) {
  566. next();
  567. return;
  568. }
  569. process.stdout.write(item.type + '/' + target + '\n');
  570. if (item.action && item.action.split(';').some((action) => action == 'skip')) {
  571. next();
  572. return;
  573. }
  574. if (process.stdout.clearLine) {
  575. process.stdout.clearLine();
  576. }
  577. let promise = null;
  578. if (item.script) {
  579. const index = item.script.search(' ');
  580. const root = path.dirname(__dirname);
  581. const command = path.resolve(root, item.script.substring(0, index));
  582. const args = item.script.substring(index + 1);
  583. promise = script(folder, targets, command, args);
  584. }
  585. else {
  586. const sources = item.source;
  587. promise = download(folder, targets, sources);
  588. }
  589. return promise.then(() => {
  590. return loadModel(folder + '/' + target, item).then((model) => {
  591. let promise = null;
  592. if (item.action && item.action.split(';').some((action) => action == 'skip-render')) {
  593. promise = Promise.resolve();
  594. }
  595. else {
  596. promise = render(model);
  597. }
  598. return promise.then(() => {
  599. if (item.error) {
  600. console.error('Expected error.');
  601. }
  602. else {
  603. return next();
  604. }
  605. });
  606. });
  607. }).catch((error) => {
  608. if (!item.error || item.error != error.message) {
  609. console.error(error);
  610. }
  611. else {
  612. return next();
  613. }
  614. });
  615. }
  616. next();