Repository: fhinkel/type-profile
Branch: main
Commit: cd53519a655f
Files: 6
Total size: 8.9 KB
Directory structure:
gitextract_zc5a0kj5/
├── LICENSE
├── README.md
├── demo.js
├── example.js
├── package.json
└── template.html
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017 F. Hinkelmann
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# Runtime Type Information
Collect runtime type information 😻 of your JavaScript code.
This is a demo how you could use V8's new type information feature.
V8 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.
The [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.

Compare the runtime type information with your TypeScript or Flow annotations. Or use
them to find bugs and performance issues.
For 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).
*Demo based on [@hashseed's](https://github.com/hashseed) demo for [code coverage](https://github.com/hashseed/node-coverage-demo).*
## Installation
Run `npm start`, then open [localhost:8080](http://localhost:8080).
*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/).*
================================================
FILE: demo.js
================================================
'use strict';
const inspector = require('inspector');
const http = require('http');
const query = require('querystring');
const fs = require('fs');
inspector.Session.prototype.postAsync = function(...args) {
let session = this;
return new Promise(
function(resolve, reject) {
session.post(...args,
function(error, result) {
if (error !== null) {
reject(error);
} else if (result.exceptionDetails !== undefined) {
reject(result.exceptionDetails.exception.description);
} else {
resolve(result);
}
});
});
};
async function ReadFile(file_name) {
return new Promise(
function(resolve, reject) {
fs.readFile(file_name, "utf8", function(error, result) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
// Reformat string for HTML.
function Escape(string) {
console.log(string);
return [
["&", "&"],
[" ", " "],
["<", "<"],
[">", ">"],
["\r\n", "
"],
["\n", "
"],
["\"", """],
].reduce(
function(string, [pattern, replacement]) {
return string.replace(new RegExp(pattern, "g"), replacement);
}, string);
}
async function CollectTypeProfile(source) {
// Open a new inspector session.
const session = new inspector.Session();
let typeProfile = "";
try {
session.connect();
// Enable relevant inspector domains.
await session.postAsync('Runtime.enable');
await session.postAsync('Profiler.enable');
await session.postAsync('Profiler.startTypeProfile');
// Compile script.
let { scriptId } = await session.postAsync('Runtime.compileScript', {
expression: source,
sourceURL: "test",
persistScript: true
});
// Execute script.
await session.postAsync('Runtime.runScript', { scriptId });
let { result } = await session.postAsync('Profiler.takeTypeProfile');
[{ entries: typeProfile }] = result.filter(x => x.scriptId == scriptId);
} finally {
// Close session and return.
session.disconnect();
}
return typeProfile;
}
function MarkUpCode(entries, source) {
// Sort in reverse order so we can replace entries without invalidating
// the other offsets.
entries = entries.sort((a, b) => b.offset - a.offset);
for (let entry of entries) {
source = source.slice(0, entry.offset) + typeAnnotation(entry.types) +
source.slice(entry.offset);
}
return source;
function typeAnnotation(types) {
return `/*${types.map(t => t.name).join(', ')}*/`;
}
}
async function GetPostBody(request) {
return new Promise(function(resolve) {
let body = "";
request.on('data', data => body += data);
request.on('end', end => resolve(query.parse(body)));
});
}
async function Server(request, response) {
let script = "";
let result = "";
let message_log = "";
let detailed = false;
let count = false;
if (request.method == 'POST') {
// Collect type profile on the script from input form.
try {
let post = await GetPostBody(request);
script = post.script;
let typeProfile = await CollectTypeProfile(script);
result = MarkUpCode(typeProfile, script);
} catch (e) {
console.log(e);
message_log = Escape(e.toString());
console.log(message_log);
}
} else {
// Use example file.
script = await ReadFile("example.js");
}
let template = await ReadFile("template.html");
let html = [
["SCRIPT", script],
["RESULT", result],
["CONSOLE", message_log],
].reduce(function(template, [pattern, replacement]) {
return template.replace(pattern, replacement);
}, template);
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.end(html);
}
http.createServer(Server).listen(8080);
console.log("Listening on localhost:8080");
================================================
FILE: example.js
================================================
(function() {
function foo(x) {
if (x < 2) {
return 42;
}
return "What are the return types of foo?";
}
class Rectangle {};
foo({});
foo(1);
foo(1.5);
foo("some string");
foo(new Rectangle());
})();
// Return type of the script itself.
================================================
FILE: package.json
================================================
{
"name": "type-profile",
"version": "1.0.0",
"description": "Collect runtime type information 😻 of your JavaScript code.",
"main": "demo.js",
"scripts": {
"start": "node demo.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fhinkel/type-profile.git"
},
"keywords": [
"nodejs",
"typing",
"typeprofile",
"typescript"
],
"author": "Franziska Hinkelmann",
"license": "MIT",
"bugs": {
"url": "https://github.com/fhinkel/type-profile/issues"
},
"homepage": "https://github.com/fhinkel/type-profile#readme"
}
================================================
FILE: template.html
================================================
RESULT