Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
literate-ts
Advanced tools
Literate TS statically checks TypeScript code samples in written text (blog posts, books, etc.). It was developed and used to type check Effective TypeScript (O'Reilly 2019, 2024) as well as the companion blog, effectivetypescript.com.
For background on this, see Type-safe blogs and books with literate-ts.
$ npm install -D typescript literate-ts
$ literate-ts path/to/posts/*.md
TypeScript is a peer dependency of literate-ts, so you'll need to install it yourself. It's done this way so that you're in control of the TypeScript version. (Checking for breakages when you update TS is one of the main uses cases of literate-ts.)
Literate TS checks three sorts of things.
Expected errors. To assert the existence of an error, use a comment with a squiggly underscore in it:
let str = 'not a number';
let num: number = str;
// ~~~ Type 'string' is not assignable to type 'number'.
Literate TS will verify that this error occurs in your code sample, and no others. In other words, with no error annotations, literate-ts verifies that there are no errors.
Types. To assert that the type of an expression is what you expect, use a comment starting with "type is":
'four score'.split(' '); // type is string[]
Literate TS will verify that the type is precisely what you specify textually, ala dtslint.
You can also use twoslash syntax for type assertions:
const parts = 'four score'.split(' ');
// ^? const parts: string[]
Output. To assert the output of a code sample, give it an ID and include a paired one ending
with -output
. In Asciidoc, for example:
[[sample]]
[source,ts]
----
console.log('Hello');
----
[[sample-output]]
....
Hello
....
Literate TS will convert your code sample to JavaScript, run it through Node and diff the output. You can use this to create something like a unit test for your code samples.
You ran your code samples through the TypeScript playground when you wrote them. Why bother spending the time writing just the right set of directives and comments to get them running through literate-ts?
I wondered this myself while writing Effective TypeScript, but eventually this tool demonstrated its value many times over.
The arguments for using it are similar to those for writing tests or using TypeScript itself:
Safe refactoring editing Your code samples type checked when you wrote them. But then you,
your co-author or your editor went and changed things. Maybe you renamed a variable or function
in one sample and didn't update it in subsequent samples. Maybe you deleted the definition of a
function that you referenced later. Literate TS found a few errors the first time through
Effective TypeScript, but I can't recall a single edit I made that didn't trigger a
verification failure.
Damage control with new TypeScript releases As Anders has said, semantic versioning in TypeScript is pretty meaningless because the whole point of new releases is to break your code (or, rather, to reveal that it was already broken). When the next TypeScript release comes out, are you going to re-run all your code samples through it? With Literate TS this is easy. For reference, TypeScript 3.8 broke two of the 600 samples in Effective TypeScript. I fixed them and did a new release. Nothing broke with TypeScript 3.9. In both cases, it was a tremendous relief to know exactly what the damage was, or to know that there was no damage at all.
Completeness. You ran your code samples through TypeScript, but did you actually run all of them? Maybe you forgot one. Literate TS won't! Even the process of figuring out which code samples need to be prepended to others to form a valid compilation unit is helpful. If you can't create one, or the sequence is too elaborate, then something's probably wrong.
Practicing what you preach If you're writing a book or blog about TypeScript, you're probably already bought into the value of static analysis. Doing static analysis on your book is very much in the spirit of TypeScript!
literate-ts supports both Asciidoc and Markdown sources. The syntax used for each is slightly different.
Only fenced code blocks are supported in Markdown sources. For a source to be checked, it needs to have its language marked as "ts" or "js":
Here's a TypeScript code sample:
```ts
let num = 10; // type is number
```
To give a code sample an ID, use an HTML comment starting with a #
:
This sample has an ID of `Point`:
<!-- #Point -->
```ts
type Point = [number, number];
```
To pass a directive to the verifier, e.g. to tell it to concatenate sources, add an HTML comment
starting with verifier:
immediately before the sample. For example:
We can define a type using `interface`:
<!-- verifier:prepend-to-following -->
```ts
interface Student {
name: string;
age: number;
}
```
And then create objects of that type:
```ts
const student: Student = { name: 'Bobby Droppers', age: 12 };
```
You may also use // #id
or // verifier:directive
as an alternative form.
This is primarily useful if you want to prepend a code sample that's hidden inside an
HTML comment.
See below for a complete list of directives.
Asciidoc is a bit like Markdown, but more flexible and complicated. In particular O'Reilly uses it in their Atlas publishing system. Any recent O'Reilly book (including Effective TypeScript) is written in Asciidoc. GitHub also provides a rich display for Asciidoc source files.
In Asciidoc, code samples are marked with ----
or ....
. Samples must be marked
with [source,ts]
to be checked, or [source,js]
to be run through Node.
Code samples can be given an identifier using [[id]]
:
This sample has an ID of `point`:
[[point]]
[source,ts]
----
type Point = [number, number];
// ^? type Point = [number, number]
----
Directives begin with // verifier
. For example:
// verifier:prepend-to-following
[source,ts]
----
interface Student {
name: string;
age: number;
}
----
[source,ts]
----
const student: Student = { name: 'Bobby Droppers', age: 12 };
----
See below for a complete list of directives.
See above for how to give directive to literate-ts in your source format.
Sometimes you don't want to show the full implementation of a function. For example:
function computeSHA512(text: string): number {
// ...
}
The implementation is hidden, but unfortunately so is the return
statement, which means that
this won't type check (tsc
complains that it returns void
but is declared to return number
).
Literate TS supports this through "replacements": if you give the code sample an ID of sha512
(see above for how to do this in Markdown and Asciidoc formats) then you can put something like
this in a file called sha512.ts
:
function computeSHA512(text: string): number {
// COMPRESS
return 0;
// END
}
Obviously this isn't a real implementation but it will make the type checker happy. You tell
Literate TS about this by passing a replacements
directory via the -r
flag:
$ literate-ts -r path/to/replacements path/to/posts/*.md
The correspondence between replacements and their sources is checked and must be precise. In
addition to COMPRESS...END
, you can also use HIDE...END
to completely remove code. Of course,
be careful not to mislead the reader when you do this.
(This syntax comes from pyliterate.)
If you'd like to keep your source files self-contained, you can put the replacement in a code block and reference it with a replace-with-id
directive. See this sample file for examples.
Sometimes TypeScript's type display can be a bit opaque, particularly with keyof
expressions:
interface Point {
x: number;
y: number;
}
type T = keyof Point;
// ^? type T = keyof Point
While correct and faithful to what you see in Quick Info, this isn't very useful. You can add an "equivalent to" clause to the type assertion to get some more resolution on the type (and clarify what it is for your readers):
type T = keyof Point;
// ^? type T = keyof Point (equivalent to "x" | "y")
When it sees this sort of assertion, literate-ts will quietly insert some machinery to resolve the type and check both the raw and resolved types.
This only works for twoslash-style assertions.
literate-ts will also try to verify "program listings". These look like they've been copy/pasted from the Node REPL:
> 1 + 2
3
When it sees one of these, literate-ts will run the lines starting with >
through Node and verify that the response lines come back out. If you have prepend directives active when literate-ts hits a program listing, the compiled JS for those will be run through Node as a "preamble".
This is only supported for Asciidoc. Here's what it looks like:
++++
<pre data-type="programlisting">> <strong>x = {}</strong>
{}
> <strong>x[[1, 2, 3]] = 2</strong>
2
> <strong>x</strong>
{ '1,2,3': 2 }
</pre>
++++
If you fill out a "prettier"
section in your package.json
, literate-ts will enforce a maximum line length on your code samples:
{
"prettier": {
"printWidth": 81
}
}
--help
: Show help.--version
: Show version numbers for literate-ts
and typescript
.-f
/--filter
: Only check IDs with the given prefix. This is either the ID you explicitly give the sample, or file-line
, e.g. explicit-id-1234
or filename-no-ext-1234
. (The exact IDs are in the "detailed logs".)-r
/--replacements
: If specified, load **/*.{ts,js,txt}
under this directory as additional sources.--playground
: If specified, output a JSON file containing TypeScript playground URLs for all code samples. See the effective-typescript repo for an example of how this can be used.--alsologtostderr
: Log to stderr in addition to a log file.--nocache
: Disable reading and writing from on-disk cache. If this results in different behavior, please file an issue. The cache is in node_modules/.cache/literate-ts
. Delete this directory to clear the cache.It's extremely convenient to run literate-ts as a task in VS Code since it will show errors inline in your document. You need to set up a task with an appropriate problemMatcher
to make this work. Add the following to your tasks.json
(change yarn
to another package manager as needed):
{
"label": "Run file through literate-ts",
"command": "yarn",
"args": [
"literate-ts",
"${file}",
],
"presentation": {
"echo": true,
"reveal": "never",
"revealProblems": "onProblem",
"close": true,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"problemMatcher": [
{
"owner": "literate-ts",
"fileLocation": "absolute",
"pattern": [
{
"regexp": "^💥 (.*?):(\\d+):(\\d+)-(\\d+): (.*)$",
"file": 1,
"line": 2,
"column": 3,
"endColumn": 4,
"message": 5,
}
]
},
{
"owner": "literate-ts",
"fileLocation": "absolute",
"pattern": {
"regexp": "^💥 (.*?):(\\d+): (.*)$",
"file": 1,
"line": 2,
"message": 3
}
}
]
}
Quickstart:
$ yarn
$ yarn run check examples/asciidoc/sample.asciidoc
Logging details to /var/folders/st/8n5l6s0139x5dwpxfhl0xs3w0000gn/T/tmp-96270LdwL51L23N9D/log.txt
Verifying with TypeScript 3.6.2
examples/asciidoc/sample.asciidoc 5/5 passed
✓ sample-6
✓ sample-17
✓ sample-25
✓ sample-32
✓ sample-41
✓ All samples passed!
✨ Done in 9.24s.
Publish a new version:
$ vim package.json # update version
$ yarn test
$ tsc
$ npm publish
Update all baselines:
$ yarn baselines:update
Update one baseline:
$ yarn baselines:update -t 'filename.asciidoc'
FAQs
Code samples that scale
We found that literate-ts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.