This repository was archived by the owner on May 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathcaching.ts
More file actions
68 lines (58 loc) · 2.29 KB
/
caching.ts
File metadata and controls
68 lines (58 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { UserConfigSettings, runTwoSlash } from "shiki-twoslash"
import type { TwoSlashReturn } from "@typescript/twoslash"
/**
* Keeps a cache of the JSON responses to a twoslash call in node_modules/.cache/twoslash
* which should keep CI times down (e.g. the epub vs the handbook etc) - but also during
* dev time, where it can be super useful.
*/
export const cachedTwoslashCall = (
code: string,
lang: string,
settings: UserConfigSettings
): TwoSlashReturn | undefined => {
// @ts-expect-error
const isWebWorker = typeof self !== "undefined" && typeof self.WorkerGlobalScope !== "undefined"
const isBrowser =
isWebWorker ||
(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof fetch !== "undefined")
if (isBrowser) {
// Not in Node, run un-cached
return runTwoSlash(code, lang, settings)
}
const { createHash } = require("crypto")
const { readFileSync, existsSync, mkdirSync, writeFileSync } = require("fs")
const { join } = require("path")
const shikiVersion = require('@typescript/twoslash/package.json').version
const tsVersion = require('typescript/package.json').version
const shasum = createHash("sha1")
const codeSha = shasum.update(`${code}-${shikiVersion}-${tsVersion}`).digest("hex")
const getNmCache = () => {
if (__dirname.includes("node_modules")) {
return join(__dirname.split("node_modules")[0], "node_modules", ".cache", "twoslash")
} else {
return join(__dirname, "..", "..", ".cache", "twoslash");
}
};
const getPnpCache = () => {
try {
const pnp = require("pnpapi");
return join(pnp.getPackageInformation(pnp.topLevel).packageLocation, "node_modules", ".cache", "twoslash");
} catch (error) {
return getNmCache()
}
};
const cacheRoot = process.versions.pnp
? getPnpCache()
: getNmCache();
const cachePath = join(cacheRoot, `${codeSha}.json`)
if (existsSync(cachePath)) {
if (process.env.debug)
console.log(`Using cached twoslash results from ${cachePath}`)
return JSON.parse(readFileSync(cachePath, "utf8"))
} else {
const results = runTwoSlash(code, lang, settings)
if (!existsSync(cacheRoot)) mkdirSync(cacheRoot, { recursive: true })
writeFileSync(cachePath, JSON.stringify(results), "utf8")
return results
}
}