Full Code of fhinkel/type-profile for AI

main cd53519a655f cached
6 files
8.9 KB
2.4k tokens
8 symbols
1 requests
Download .txt
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.

![Image of Demo](https://raw.githubusercontent.com/fhinkel/type-profile/master/images/demo.png)

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 [
    ["&", "&"],
    [" ", " "],
    ["<", "&lt;"],
    [">", "&gt;"],
    ["\r\n", "<br/>"],
    ["\n", "<br/>"],
    ["\"", "&quot;"],
  ].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 `<font color="red"><b>/*${types.map(t => t.name).join(', ')}*/</b></font>`;
  }
}

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
================================================
<html>
    <head>
        <Title>Node.js Runtime type information</Title>
    </head>
   <body>
        <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>
      <style>
         #left, #right { display: table-cell }
         #left { float: left, width: 500px }
         #right { width: 500px }
         textarea { font-size: 12px; font-family: monospace; }
         #footer {position: absolute; bottom: 0;width: 100%; height: 20px;}
      </style>
      <tt>
         <div>
            <div id="left">
               <h1>Script</h1>
               <form method="post">
                  <textarea name="script" rows="28" cols="72">SCRIPT</textarea>
                  <br/><br/>
                  <input type="submit" value="obtain type profile">
               </form>
            </div>
            <div id="right">
               <h1>Runtime type information</h1>
               <pre>RESULT
               </pre>
            </div>
         </div>
         <h1>Console</h1>
         CONSOLE
      </tt>

       <div id="footer">
           2018 <a href="https://fhinkel.rocks">fhinkel</a>
       </div>

   </body>
</html>
Download .txt
gitextract_zc5a0kj5/

├── LICENSE
├── README.md
├── demo.js
├── example.js
├── package.json
└── template.html
Download .txt
SYMBOL INDEX (8 symbols across 2 files)

FILE: demo.js
  function ReadFile (line 24) | async function ReadFile(file_name) {
  function Escape (line 38) | function Escape(string) {
  function CollectTypeProfile (line 54) | async function CollectTypeProfile(source) {
  function MarkUpCode (line 81) | function MarkUpCode(entries, source) {
  function GetPostBody (line 97) | async function GetPostBody(request) {
  function Server (line 105) | async function Server(request, response) {

FILE: example.js
  function foo (line 2) | function foo(x) {
  class Rectangle (line 9) | class Rectangle {}
Condensed preview — 6 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (10K chars).
[
  {
    "path": "LICENSE",
    "chars": 1070,
    "preview": "MIT License\n\nCopyright (c) 2017 F. Hinkelmann\n\nPermission is hereby granted, free of charge, to any person obtaining a c"
  },
  {
    "path": "README.md",
    "chars": 1696,
    "preview": "\n# Runtime Type Information\n\nCollect runtime type information 😻 of your JavaScript code.\n\nThis is a demo how you could u"
  },
  {
    "path": "demo.js",
    "chars": 3945,
    "preview": "'use strict';\nconst inspector = require('inspector');\nconst http = require('http');\nconst query = require('querystring')"
  },
  {
    "path": "example.js",
    "chars": 271,
    "preview": "(function() {\n  function foo(x) {\n    if (x < 2) {\n      return 42;\n    }\n    return \"What are the return types of foo?\""
  },
  {
    "path": "package.json",
    "chars": 641,
    "preview": "{\n  \"name\": \"type-profile\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Collect runtime type information 😻 of your JavaScrip"
  },
  {
    "path": "template.html",
    "chars": 1521,
    "preview": "<html>\n    <head>\n        <Title>Node.js Runtime type information</Title>\n    </head>\n   <body>\n        <a href=\"https:/"
  }
]

About this extraction

This page contains the full source code of the fhinkel/type-profile GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 6 files (8.9 KB), approximately 2.4k tokens, and a symbol index with 8 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!