[
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 F. Hinkelmann\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "\n# Runtime Type Information\n\nCollect runtime type information 😻 of your JavaScript code.\n\nThis is a demo how you could use V8's new type information feature.\n\nV8 can now collect type information at runtime. V8 is Google’s open source JavaScript engine. Chrome, Node.js, and many other applications use V8. This type profiler is built into the engine, the information is not statically inferred.\n\nThe [V8 inspector protocol](https://chromedevtools.github.io/devtools-protocol/v8/Profiler/#method-startTypeProfile) provides access to the type information. Since the inspector is available in Node (see [Node Documentation](https://nodejs.org/dist/latest-v8.x/docs/api/inspector.html)), it's easy to write modules that utilize type information. This repo is a very simple demo of this.\n\n![Image of Demo](https://raw.githubusercontent.com/fhinkel/type-profile/master/images/demo.png)\n\nCompare the runtime type information with your TypeScript or Flow annotations. Or use \nthem to find bugs and performance issues. \n\nFor technical details on type profile implementation in V8, see [https://chromium-review.googlesource.com/c/v8/v8/+/508588](https://chromium-review.googlesource.com/c/v8/v8/+/508588) and the [Design Doc](https://docs.google.com/document/d/1JY7pUCAk8gegyi6UkIdln6j_AeJqQucZg92advaMJY4/edit?usp=sharing).\n\n*Demo based on [@hashseed's](https://github.com/hashseed) demo for [code coverage](https://github.com/hashseed/node-coverage-demo).*\n\n## Installation \nRun `npm start`, then open [localhost:8080](http://localhost:8080). \n\n*Note: currently needs Node master, TypeProfile is not in 9.4. You can build from source or download a [nightly build](https://nodejs.org/download/nightly/).* "
  },
  {
    "path": "demo.js",
    "content": "'use strict';\nconst inspector = require('inspector');\nconst http = require('http');\nconst query = require('querystring');\nconst fs = require('fs');\n\ninspector.Session.prototype.postAsync = function(...args) {\n  let session = this;\n  return new Promise(\n    function(resolve, reject) {\n      session.post(...args,\n        function(error, result) {\n          if (error !== null) {\n            reject(error);\n          } else if (result.exceptionDetails !== undefined) {\n            reject(result.exceptionDetails.exception.description);\n          } else {\n            resolve(result);\n          }\n        });\n    });\n};\n\nasync function ReadFile(file_name) {\n  return new Promise(\n    function(resolve, reject) {\n      fs.readFile(file_name, \"utf8\", function(error, result) {\n        if (error) {\n          reject(error);\n        } else {\n          resolve(result);\n        }\n      });\n    });\n}\n\n// Reformat string for HTML.\nfunction Escape(string) {\n  console.log(string);\n  return [\n    [\"&\", \"&amp;\"],\n    [\" \", \"&nbsp;\"],\n    [\"<\", \"&lt;\"],\n    [\">\", \"&gt;\"],\n    [\"\\r\\n\", \"<br/>\"],\n    [\"\\n\", \"<br/>\"],\n    [\"\\\"\", \"&quot;\"],\n  ].reduce(\n    function(string, [pattern, replacement]) {\n      return string.replace(new RegExp(pattern, \"g\"), replacement);\n    }, string);\n}\n\nasync function CollectTypeProfile(source) {\n  // Open a new inspector session.\n  const session = new inspector.Session();\n  let typeProfile = \"\";\n  try {\n    session.connect();\n    // Enable relevant inspector domains.\n    await session.postAsync('Runtime.enable');\n    await session.postAsync('Profiler.enable');\n    await session.postAsync('Profiler.startTypeProfile');\n    // Compile script.\n    let { scriptId } = await session.postAsync('Runtime.compileScript', {\n      expression: source,\n      sourceURL: \"test\",\n      persistScript: true\n    });\n    // Execute script.\n    await session.postAsync('Runtime.runScript', { scriptId });\n    let { result } = await session.postAsync('Profiler.takeTypeProfile');\n    [{ entries: typeProfile }] = result.filter(x => x.scriptId == scriptId);   \n  } finally {\n    // Close session and return.\n    session.disconnect();\n  }\n  return typeProfile;\n}\n\nfunction MarkUpCode(entries, source) {\n  // Sort in reverse order so we can replace entries without invalidating\n  // the other offsets.\n  entries = entries.sort((a, b) => b.offset - a.offset);\n\n  for (let entry of entries) {\n    source = source.slice(0, entry.offset) + typeAnnotation(entry.types) +\n      source.slice(entry.offset);\n  }\n  return source;\n\n  function typeAnnotation(types) {\n    return `<font color=\"red\"><b>/*${types.map(t => t.name).join(', ')}*/</b></font>`;\n  }\n}\n\nasync function GetPostBody(request) {\n  return new Promise(function(resolve) {\n    let body = \"\";\n    request.on('data', data => body += data);\n    request.on('end', end => resolve(query.parse(body)));\n  });\n}\n\nasync function Server(request, response) {\n  let script = \"\";\n  let result = \"\";\n  let message_log = \"\";\n  let detailed = false;\n  let count = false;\n  if (request.method == 'POST') {\n    // Collect type profile on the script from input form.\n    try {\n      let post = await GetPostBody(request);\n      script = post.script;\n      let typeProfile = await CollectTypeProfile(script);\n      result = MarkUpCode(typeProfile, script);\n    } catch (e) {\n      console.log(e);\n      message_log = Escape(e.toString());\n      console.log(message_log);\n    }\n  } else {\n    // Use example file.\n    script = await ReadFile(\"example.js\");\n  }\n  let template = await ReadFile(\"template.html\");\n  let html = [\n    [\"SCRIPT\", script],\n    [\"RESULT\", result],\n    [\"CONSOLE\", message_log],\n  ].reduce(function(template, [pattern, replacement]) {\n    return template.replace(pattern, replacement);\n  }, template);\n  response.writeHead(200, {\n    'Content-Type': 'text/html'\n  });\n  response.end(html);\n}\n\nhttp.createServer(Server).listen(8080);\nconsole.log(\"Listening on localhost:8080\");\n\n"
  },
  {
    "path": "example.js",
    "content": "(function() {\n  function foo(x) {\n    if (x < 2) {\n      return 42;\n    }\n    return \"What are the return types of foo?\";\n  }\n\n  class Rectangle {};\n\n  foo({});\n  foo(1);\n  foo(1.5);\n  foo(\"some string\");\n  foo(new Rectangle());\n})();\n// Return type of the script itself."
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"type-profile\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Collect runtime type information 😻 of your JavaScript code.\",\n  \"main\": \"demo.js\",\n  \"scripts\": {\n\t\"start\": \"node demo.js\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/fhinkel/type-profile.git\"\n  },\n  \"keywords\": [\n    \"nodejs\",\n    \"typing\",\n    \"typeprofile\",\n    \"typescript\"\n  ],\n  \"author\": \"Franziska Hinkelmann\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/fhinkel/type-profile/issues\"\n  },\n  \"homepage\": \"https://github.com/fhinkel/type-profile#readme\"\n}\n"
  },
  {
    "path": "template.html",
    "content": "<html>\n    <head>\n        <Title>Node.js Runtime type information</Title>\n    </head>\n   <body>\n        <a href=\"https://github.com/fhinkel/type-profile\"><img style=\"position: absolute; top: 0; right: 0; border: 0;\" src=\"https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67\" alt=\"Fork me on GitHub\" data-canonical-src=\"https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png\"></a>\n      <style>\n         #left, #right { display: table-cell }\n         #left { float: left, width: 500px }\n         #right { width: 500px }\n         textarea { font-size: 12px; font-family: monospace; }\n         #footer {position: absolute; bottom: 0;width: 100%; height: 20px;}\n      </style>\n      <tt>\n         <div>\n            <div id=\"left\">\n               <h1>Script</h1>\n               <form method=\"post\">\n                  <textarea name=\"script\" rows=\"28\" cols=\"72\">SCRIPT</textarea>\n                  <br/><br/>\n                  <input type=\"submit\" value=\"obtain type profile\">\n               </form>\n            </div>\n            <div id=\"right\">\n               <h1>Runtime type information</h1>\n               <pre>RESULT\n               </pre>\n            </div>\n         </div>\n         <h1>Console</h1>\n         CONSOLE\n      </tt>\n\n       <div id=\"footer\">\n           2018 <a href=\"https://fhinkel.rocks\">fhinkel</a>\n       </div>\n\n   </body>\n</html>\n"
  }
]