Initial (dirty) port from the internal JavaScript version to TypeScript.

Might (should...) contain bugs.