|
|
|
@@ -0,0 +1,653 @@
|
|
|
|
|
import * as JSONC from "jsonc-parser";
|
|
|
|
|
import { setupTypeAcquisition } from "@typescript/ata";
|
|
|
|
|
|
|
|
|
|
import type tsNamespace from "typescript";
|
|
|
|
|
import type { JSRuntimeFS } from "@/lib/JSRuntime";
|
|
|
|
|
|
|
|
|
|
type TS = typeof tsNamespace;
|
|
|
|
|
|
|
|
|
|
export interface TypecheckProjectOptions {
|
|
|
|
|
fs: JSRuntimeFS;
|
|
|
|
|
projectPath: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface TypecheckDiagnostic {
|
|
|
|
|
/** Path relative to the project root, or undefined for global diagnostics */
|
|
|
|
|
file?: string;
|
|
|
|
|
/** 1-based line number */
|
|
|
|
|
line?: number;
|
|
|
|
|
/** 1-based column number */
|
|
|
|
|
column?: number;
|
|
|
|
|
code: number;
|
|
|
|
|
message: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface TypecheckResult {
|
|
|
|
|
errors: TypecheckDiagnostic[];
|
|
|
|
|
checkedFileCount: number;
|
|
|
|
|
/** npm packages whose type declarations could not be acquired; imports from them were not checked */
|
|
|
|
|
missingTypes: string[];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Virtual directory where TypeScript's bundled lib.*.d.ts files are mounted */
|
|
|
|
|
const LIB_DIR = "/__typescript_libs__";
|
|
|
|
|
|
|
|
|
|
/** Virtual file providing Vite-style ambient declarations for asset imports */
|
|
|
|
|
const SHIM_PATH = `${LIB_DIR}/__vite_shim__.d.ts`;
|
|
|
|
|
|
|
|
|
|
const EXCLUDED_DIRS = new Set(["node_modules", "dist", "coverage"]);
|
|
|
|
|
|
|
|
|
|
const SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
|
|
|
|
|
const JS_EXTENSIONS = [".js", ".jsx", ".mjs", ".cjs"];
|
|
|
|
|
|
|
|
|
|
/** Diagnostic codes produced when a module's declarations cannot be found */
|
|
|
|
|
const MISSING_MODULE_CODES = new Set([
|
|
|
|
|
2307, // Cannot find module 'X' or its corresponding type declarations.
|
|
|
|
|
2688, // Cannot find type definition file for 'X'.
|
|
|
|
|
7016, // Could not find a declaration file for module 'X'.
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Ambient declarations for Vite-specific imports (assets, CSS, import.meta.env).
|
|
|
|
|
* Only used when the project's `vite` types could not be acquired; mirrors a
|
|
|
|
|
* subset of `vite/client`. Lives in a .d.ts file, so `skipLibCheck` suppresses
|
|
|
|
|
* any conflicts if the real vite/client types are also present.
|
|
|
|
|
*/
|
|
|
|
|
const VITE_SHIM = `
|
|
|
|
|
declare module "*.module.css" { const classes: { readonly [key: string]: string }; export default classes; }
|
|
|
|
|
declare module "*.css" { const css: string; export default css; }
|
|
|
|
|
declare module "*.scss" { const css: string; export default css; }
|
|
|
|
|
declare module "*.sass" { const css: string; export default css; }
|
|
|
|
|
declare module "*.less" { const css: string; export default css; }
|
|
|
|
|
declare module "*.svg" { const src: string; export default src; }
|
|
|
|
|
declare module "*.png" { const src: string; export default src; }
|
|
|
|
|
declare module "*.jpg" { const src: string; export default src; }
|
|
|
|
|
declare module "*.jpeg" { const src: string; export default src; }
|
|
|
|
|
declare module "*.gif" { const src: string; export default src; }
|
|
|
|
|
declare module "*.webp" { const src: string; export default src; }
|
|
|
|
|
declare module "*.avif" { const src: string; export default src; }
|
|
|
|
|
declare module "*.ico" { const src: string; export default src; }
|
|
|
|
|
declare module "*.bmp" { const src: string; export default src; }
|
|
|
|
|
declare module "*.mp3" { const src: string; export default src; }
|
|
|
|
|
declare module "*.wav" { const src: string; export default src; }
|
|
|
|
|
declare module "*.ogg" { const src: string; export default src; }
|
|
|
|
|
declare module "*.flac" { const src: string; export default src; }
|
|
|
|
|
declare module "*.aac" { const src: string; export default src; }
|
|
|
|
|
declare module "*.mp4" { const src: string; export default src; }
|
|
|
|
|
declare module "*.webm" { const src: string; export default src; }
|
|
|
|
|
declare module "*.woff" { const src: string; export default src; }
|
|
|
|
|
declare module "*.woff2" { const src: string; export default src; }
|
|
|
|
|
declare module "*.ttf" { const src: string; export default src; }
|
|
|
|
|
declare module "*.otf" { const src: string; export default src; }
|
|
|
|
|
declare module "*.eot" { const src: string; export default src; }
|
|
|
|
|
declare module "*.wasm" { const src: string; export default src; }
|
|
|
|
|
declare module "*.pdf" { const src: string; export default src; }
|
|
|
|
|
declare module "*.txt" { const src: string; export default src; }
|
|
|
|
|
declare module "*?raw" { const content: string; export default content; }
|
|
|
|
|
declare module "*?url" { const url: string; export default url; }
|
|
|
|
|
declare module "*?inline" { const content: string; export default content; }
|
|
|
|
|
declare module "*?worker" {
|
|
|
|
|
const workerConstructor: { new (options?: { name?: string }): Worker };
|
|
|
|
|
export default workerConstructor;
|
|
|
|
|
}
|
|
|
|
|
interface ImportMeta {
|
|
|
|
|
readonly env: Record<string, any>;
|
|
|
|
|
readonly hot?: Record<string, any>;
|
|
|
|
|
glob(pattern: string | string[], options?: Record<string, unknown>): Record<string, any>;
|
|
|
|
|
}
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
interface RawTsConfig {
|
|
|
|
|
extends?: string;
|
|
|
|
|
compilerOptions?: Record<string, unknown>;
|
|
|
|
|
include?: string[];
|
|
|
|
|
exclude?: string[];
|
|
|
|
|
files?: string[];
|
|
|
|
|
references?: { path: string }[];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface ProjectPackageJson {
|
|
|
|
|
dependencies?: Record<string, string>;
|
|
|
|
|
devDependencies?: Record<string, string>;
|
|
|
|
|
peerDependencies?: Record<string, string>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface ProjectPackageLock {
|
|
|
|
|
packages?: Record<string, { version?: string } | undefined>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Run async tasks with a maximum number in flight at once. The browser fails
|
|
|
|
|
* requests with ERR_INSUFFICIENT_RESOURCES if too many start simultaneously.
|
|
|
|
|
*/
|
|
|
|
|
function createLimiter(limit: number): <T>(task: () => Promise<T>) => Promise<T> {
|
|
|
|
|
let active = 0;
|
|
|
|
|
const queue: (() => void)[] = [];
|
|
|
|
|
|
|
|
|
|
const next = () => {
|
|
|
|
|
active--;
|
|
|
|
|
queue.shift()?.();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return async (task) => {
|
|
|
|
|
if (active >= limit) {
|
|
|
|
|
await new Promise<void>((resolve) => queue.push(resolve));
|
|
|
|
|
}
|
|
|
|
|
active++;
|
|
|
|
|
try {
|
|
|
|
|
return await task();
|
|
|
|
|
} finally {
|
|
|
|
|
next();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Concurrency cap for all network activity performed during a typecheck */
|
|
|
|
|
const limit = createLimiter(16);
|
|
|
|
|
|
|
|
|
|
/** fetch wrapper passed to ATA so dependency downloads don't flood the browser */
|
|
|
|
|
const limitedFetch: typeof fetch = (input, init) => limit(() => fetch(input, init));
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Lazy loaders for TypeScript's bundled default library files. Each file
|
|
|
|
|
* becomes its own chunk, loaded on first typecheck and cached afterwards.
|
|
|
|
|
*/
|
|
|
|
|
const libFileLoaders = import.meta.glob<string>(
|
|
|
|
|
"/node_modules/typescript/lib/lib*.d.ts",
|
|
|
|
|
{ query: "?raw", import: "default" },
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let libFilesPromise: Promise<Map<string, string>> | undefined;
|
|
|
|
|
|
|
|
|
|
function loadLibFiles(): Promise<Map<string, string>> {
|
|
|
|
|
libFilesPromise ??= (async () => {
|
|
|
|
|
const entries = await Promise.all(
|
|
|
|
|
Object.entries(libFileLoaders).map(async ([path, load]) => {
|
|
|
|
|
const name = path.slice(path.lastIndexOf("/") + 1);
|
|
|
|
|
return [`${LIB_DIR}/${name}`, await limit(load)] as const;
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
return new Map(entries);
|
|
|
|
|
})();
|
|
|
|
|
return libFilesPromise;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Cache of acquired type declarations, keyed by the synthetic ATA entry source */
|
|
|
|
|
const typeAcquisitionCache = new Map<string, Promise<Map<string, string>>>();
|
|
|
|
|
|
|
|
|
|
const silentLogger = {
|
|
|
|
|
log: () => {},
|
|
|
|
|
error: () => {},
|
|
|
|
|
groupCollapsed: () => {},
|
|
|
|
|
groupEnd: () => {},
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Download type declarations for the project's npm dependencies from jsdelivr
|
|
|
|
|
* using TypeScript's Automatic Type Acquisition. Returns a map of
|
|
|
|
|
* `/node_modules/...` paths to file contents.
|
|
|
|
|
*/
|
|
|
|
|
function acquireTypes(ts: TS, entrySource: string): Promise<Map<string, string>> {
|
|
|
|
|
const cached = typeAcquisitionCache.get(entrySource);
|
|
|
|
|
if (cached) return cached;
|
|
|
|
|
|
|
|
|
|
const promise = (async () => {
|
|
|
|
|
const files = new Map<string, string>();
|
|
|
|
|
const ata = setupTypeAcquisition({
|
|
|
|
|
projectName: "shakespeare",
|
|
|
|
|
typescript: ts,
|
|
|
|
|
logger: silentLogger,
|
|
|
|
|
fetcher: limitedFetch,
|
|
|
|
|
delegate: {
|
|
|
|
|
// First write wins: version-pinned packages are requested up front, so
|
|
|
|
|
// they must not be overwritten by transitively-discovered "latest" types
|
|
|
|
|
receivedFile: (code, path) => {
|
|
|
|
|
if (!files.has(path)) files.set(path, code);
|
|
|
|
|
},
|
|
|
|
|
errorMessage: () => {},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
await ata(entrySource);
|
|
|
|
|
return files;
|
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
// Don't cache failures (e.g. network errors) so a retry can succeed
|
|
|
|
|
promise.catch(() => typeAcquisitionCache.delete(entrySource));
|
|
|
|
|
typeAcquisitionCache.set(entrySource, promise);
|
|
|
|
|
return promise;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Resolve "." and ".." segments and collapse duplicate slashes */
|
|
|
|
|
function normalizePath(path: string): string {
|
|
|
|
|
const isAbsolute = path.startsWith("/");
|
|
|
|
|
const out: string[] = [];
|
|
|
|
|
for (const part of path.split("/")) {
|
|
|
|
|
if (part === "" || part === ".") continue;
|
|
|
|
|
if (part === "..") {
|
|
|
|
|
out.pop();
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
out.push(part);
|
|
|
|
|
}
|
|
|
|
|
return (isAbsolute ? "/" : "") + out.join("/");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function extensionOf(name: string): string {
|
|
|
|
|
const dot = name.lastIndexOf(".");
|
|
|
|
|
return dot === -1 ? "" : name.slice(dot).toLowerCase();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Extract the npm package name from a bare module specifier */
|
|
|
|
|
function packageNameFromSpecifier(specifier: string): string {
|
|
|
|
|
const parts = specifier.split("/");
|
|
|
|
|
return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Prefixes from tsconfig `paths` (e.g. "@/") used to distinguish aliases from npm packages */
|
|
|
|
|
function aliasPrefixesFrom(options: tsNamespace.CompilerOptions): string[] {
|
|
|
|
|
return Object.keys(options.paths ?? {}).map((key) => key.replace(/\*.*$/, ""));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function isBareSpecifier(specifier: string, aliasPrefixes: string[]): boolean {
|
|
|
|
|
if (specifier.startsWith(".") || specifier.startsWith("/")) return false;
|
|
|
|
|
if (specifier.includes(":")) return false; // node:, https:, virtual:, etc.
|
|
|
|
|
return !aliasPrefixes.some((prefix) => prefix !== "" && specifier.startsWith(prefix));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** DefinitelyTyped package name for an npm package (e.g. "@foo/bar" -> "@types/foo__bar") */
|
|
|
|
|
function dtPackageName(name: string): string {
|
|
|
|
|
return `@types/${name.startsWith("@") ? name.slice(1).replace("/", "__") : name}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function declaredRange(packageJson: ProjectPackageJson, name: string): string | undefined {
|
|
|
|
|
return (
|
|
|
|
|
packageJson.dependencies?.[name] ??
|
|
|
|
|
packageJson.devDependencies?.[name] ??
|
|
|
|
|
packageJson.peerDependencies?.[name]
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Best version to request from jsdelivr for a package: the exact locked
|
|
|
|
|
* version if available, otherwise the package.json range with any leading
|
|
|
|
|
* operator stripped. ATA only supports exact versions or single-segment
|
|
|
|
|
* ranges like "18", so ranges such as "^18.3.1" must be reduced.
|
|
|
|
|
*/
|
|
|
|
|
function pinnedVersion(
|
|
|
|
|
packageJson: ProjectPackageJson,
|
|
|
|
|
packageLock: ProjectPackageLock,
|
|
|
|
|
name: string,
|
|
|
|
|
): string | undefined {
|
|
|
|
|
const locked = packageLock.packages?.[`node_modules/${name}`]?.version;
|
|
|
|
|
if (locked) return locked;
|
|
|
|
|
|
|
|
|
|
const range = declaredRange(packageJson, name);
|
|
|
|
|
if (!range) return undefined;
|
|
|
|
|
|
|
|
|
|
const stripped = range.replace(/^[\s~^>=<v]+/, "");
|
|
|
|
|
return /^\d/.test(stripped) ? stripped : undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Build a synthetic TypeScript source file that imports every npm package the
|
|
|
|
|
* project references, pinned via ATA's `// types: <version>` comment
|
|
|
|
|
* convention. When the project declares a matching `@types/*` package, that
|
|
|
|
|
* package is requested directly at its pinned version, because ATA's own
|
|
|
|
|
* DefinitelyTyped fallback always downloads the latest version.
|
|
|
|
|
*/
|
|
|
|
|
function buildAtaEntrySource(
|
|
|
|
|
ts: TS,
|
|
|
|
|
sourceTexts: string[],
|
|
|
|
|
packageJson: ProjectPackageJson,
|
|
|
|
|
packageLock: ProjectPackageLock,
|
|
|
|
|
aliasPrefixes: string[],
|
|
|
|
|
): string {
|
|
|
|
|
const packages = new Map<string, string | undefined>();
|
|
|
|
|
|
|
|
|
|
const add = (name: string) => {
|
|
|
|
|
if (packages.has(name)) return;
|
|
|
|
|
packages.set(name, pinnedVersion(packageJson, packageLock, name));
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
for (const text of sourceTexts) {
|
|
|
|
|
const meta = ts.preProcessFile(text, true, true);
|
|
|
|
|
const refs = [...meta.importedFiles, ...meta.typeReferenceDirectives];
|
|
|
|
|
|
|
|
|
|
for (const ref of refs) {
|
|
|
|
|
if (!isBareSpecifier(ref.fileName, aliasPrefixes)) continue;
|
|
|
|
|
const name = packageNameFromSpecifier(ref.fileName);
|
|
|
|
|
if (!name) continue;
|
|
|
|
|
|
|
|
|
|
const dtName = dtPackageName(name);
|
|
|
|
|
if (!name.startsWith("@types/") && declaredRange(packageJson, dtName)) {
|
|
|
|
|
add(dtName);
|
|
|
|
|
} else {
|
|
|
|
|
add(name);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [...packages.entries()]
|
|
|
|
|
.sort(([a], [b]) => a.localeCompare(b))
|
|
|
|
|
.map(([name, version]) => (version ? `import "${name}" // types: ${version}` : `import "${name}"`))
|
|
|
|
|
.join("\n");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Read a tsconfig file, following local `extends` chains */
|
|
|
|
|
async function readRawConfig(fs: JSRuntimeFS, path: string, depth = 0): Promise<RawTsConfig | undefined> {
|
|
|
|
|
if (depth > 5) return undefined;
|
|
|
|
|
|
|
|
|
|
let text: string;
|
|
|
|
|
try {
|
|
|
|
|
text = await fs.readFile(path, "utf8");
|
|
|
|
|
} catch {
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const config = (JSONC.parse(text) ?? {}) as RawTsConfig;
|
|
|
|
|
|
|
|
|
|
if (typeof config.extends === "string" && config.extends.startsWith(".")) {
|
|
|
|
|
const dir = path.slice(0, path.lastIndexOf("/"));
|
|
|
|
|
const extendsPath = config.extends.endsWith(".json") ? config.extends : `${config.extends}.json`;
|
|
|
|
|
const parent = await readRawConfig(fs, normalizePath(`${dir}/${extendsPath}`), depth + 1);
|
|
|
|
|
if (parent) {
|
|
|
|
|
return {
|
|
|
|
|
...parent,
|
|
|
|
|
...config,
|
|
|
|
|
compilerOptions: { ...parent.compilerOptions, ...config.compilerOptions },
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return config;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Resolve the effective tsconfig for the project. Handles Vite-style project
|
|
|
|
|
* references (tsconfig.json + tsconfig.app.json) by preferring the app config.
|
|
|
|
|
*/
|
|
|
|
|
async function resolveConfig(fs: JSRuntimeFS, projectPath: string): Promise<RawTsConfig> {
|
|
|
|
|
const root = await readRawConfig(fs, `${projectPath}/tsconfig.json`);
|
|
|
|
|
if (!root) return {};
|
|
|
|
|
|
|
|
|
|
const hasOwnScope = Boolean(root.include?.length || root.files?.length);
|
|
|
|
|
if (hasOwnScope || !root.references?.length) return root;
|
|
|
|
|
|
|
|
|
|
const candidates = [
|
|
|
|
|
"tsconfig.app.json",
|
|
|
|
|
...root.references.map((ref) => (ref.path.endsWith(".json") ? ref.path : `${ref.path}/tsconfig.json`)),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
for (const candidate of candidates) {
|
|
|
|
|
const config = await readRawConfig(fs, normalizePath(`${projectPath}/${candidate}`));
|
|
|
|
|
if (config && (config.include?.length || config.files?.length)) return config;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return root;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Recursively read all source-relevant project files into memory */
|
|
|
|
|
async function readProjectFiles(fs: JSRuntimeFS, projectPath: string): Promise<Map<string, string>> {
|
|
|
|
|
const files = new Map<string, string>();
|
|
|
|
|
const relevantExtensions = new Set([...SOURCE_EXTENSIONS, ...JS_EXTENSIONS, ".json"]);
|
|
|
|
|
|
|
|
|
|
async function walk(dir: string): Promise<void> {
|
|
|
|
|
let entries;
|
|
|
|
|
try {
|
|
|
|
|
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
|
|
|
} catch {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await Promise.all(
|
|
|
|
|
entries.map(async (entry) => {
|
|
|
|
|
const path = `${dir}/${entry.name}`;
|
|
|
|
|
if (entry.isDirectory()) {
|
|
|
|
|
if (EXCLUDED_DIRS.has(entry.name) || entry.name.startsWith(".")) return;
|
|
|
|
|
await walk(path);
|
|
|
|
|
} else if (relevantExtensions.has(extensionOf(entry.name))) {
|
|
|
|
|
try {
|
|
|
|
|
files.set(path, await fs.readFile(path, "utf8"));
|
|
|
|
|
} catch {
|
|
|
|
|
// Skip unreadable files
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await walk(projectPath);
|
|
|
|
|
return files;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Convert tsconfig include/exclude patterns to simple directory/file prefixes */
|
|
|
|
|
function patternPrefixes(patterns: string[] | undefined): string[] | undefined {
|
|
|
|
|
if (!patterns?.length) return undefined;
|
|
|
|
|
return patterns.map((pattern) => {
|
|
|
|
|
let prefix = pattern.replace(/^\.\//, "");
|
|
|
|
|
const globIndex = prefix.search(/[*?[{]/);
|
|
|
|
|
if (globIndex !== -1) {
|
|
|
|
|
prefix = prefix.slice(0, globIndex);
|
|
|
|
|
prefix = prefix.slice(0, prefix.lastIndexOf("/") + 1);
|
|
|
|
|
}
|
|
|
|
|
return prefix.replace(/\/+$/, "");
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function matchesPrefix(relativePath: string, prefixes: string[]): boolean {
|
|
|
|
|
return prefixes.some(
|
|
|
|
|
(prefix) => prefix === "" || relativePath === prefix || relativePath.startsWith(`${prefix}/`),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Select the program root files based on the tsconfig include/exclude/files settings */
|
|
|
|
|
function selectRootFiles(
|
|
|
|
|
projectFiles: Map<string, string>,
|
|
|
|
|
projectPath: string,
|
|
|
|
|
config: RawTsConfig,
|
|
|
|
|
options: tsNamespace.CompilerOptions,
|
|
|
|
|
): string[] {
|
|
|
|
|
const include = patternPrefixes(config.include);
|
|
|
|
|
const exclude = patternPrefixes(config.exclude);
|
|
|
|
|
const checkedExtensions = new Set(options.allowJs ? [...SOURCE_EXTENSIONS, ...JS_EXTENSIONS] : SOURCE_EXTENSIONS);
|
|
|
|
|
|
|
|
|
|
const rootFiles = new Set<string>();
|
|
|
|
|
|
|
|
|
|
for (const path of projectFiles.keys()) {
|
|
|
|
|
if (!checkedExtensions.has(extensionOf(path))) continue;
|
|
|
|
|
const relativePath = path.slice(projectPath.length + 1);
|
|
|
|
|
if (include && !matchesPrefix(relativePath, include)) continue;
|
|
|
|
|
if (exclude && matchesPrefix(relativePath, exclude)) continue;
|
|
|
|
|
rootFiles.add(path);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const file of config.files ?? []) {
|
|
|
|
|
const path = normalizePath(`${projectPath}/${file}`);
|
|
|
|
|
if (projectFiles.has(path)) rootFiles.add(path);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [...rootFiles].sort();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function createCompilerHost(
|
|
|
|
|
ts: TS,
|
|
|
|
|
files: Map<string, string>,
|
|
|
|
|
projectPath: string,
|
|
|
|
|
): tsNamespace.CompilerHost {
|
|
|
|
|
const directories = new Set<string>(["/"]);
|
|
|
|
|
for (const path of files.keys()) {
|
|
|
|
|
let dir = path.slice(0, path.lastIndexOf("/"));
|
|
|
|
|
while (dir && !directories.has(dir)) {
|
|
|
|
|
directories.add(dir);
|
|
|
|
|
dir = dir.slice(0, dir.lastIndexOf("/"));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const sourceFileCache = new Map<string, tsNamespace.SourceFile>();
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
fileExists: (path) => files.has(normalizePath(path)),
|
|
|
|
|
readFile: (path) => files.get(normalizePath(path)),
|
|
|
|
|
directoryExists: (path) => directories.has(normalizePath(path)),
|
|
|
|
|
getDirectories: (path) => {
|
|
|
|
|
const prefix = normalizePath(path);
|
|
|
|
|
const base = prefix === "/" ? "/" : `${prefix}/`;
|
|
|
|
|
const result = new Set<string>();
|
|
|
|
|
for (const dir of directories) {
|
|
|
|
|
if (dir.startsWith(base) && dir !== prefix) {
|
|
|
|
|
const first = dir.slice(base.length).split("/")[0];
|
|
|
|
|
if (first) result.add(first);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return [...result];
|
|
|
|
|
},
|
|
|
|
|
getSourceFile: (fileName, languageVersionOrOptions) => {
|
|
|
|
|
const path = normalizePath(fileName);
|
|
|
|
|
const cached = sourceFileCache.get(path);
|
|
|
|
|
if (cached) return cached;
|
|
|
|
|
const text = files.get(path);
|
|
|
|
|
if (text === undefined) return undefined;
|
|
|
|
|
const sourceFile = ts.createSourceFile(path, text, languageVersionOrOptions, true);
|
|
|
|
|
sourceFileCache.set(path, sourceFile);
|
|
|
|
|
return sourceFile;
|
|
|
|
|
},
|
|
|
|
|
getDefaultLibLocation: () => LIB_DIR,
|
|
|
|
|
getDefaultLibFileName: (options) => `${LIB_DIR}/${ts.getDefaultLibFileName(options)}`,
|
|
|
|
|
writeFile: () => {},
|
|
|
|
|
getCurrentDirectory: () => projectPath,
|
|
|
|
|
getCanonicalFileName: (fileName) => fileName,
|
|
|
|
|
useCaseSensitiveFileNames: () => true,
|
|
|
|
|
getNewLine: () => "\n",
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Typecheck a project in the virtual filesystem with the TypeScript compiler,
|
|
|
|
|
* equivalent to running `tsc --noEmit`. Type declarations for npm dependencies
|
|
|
|
|
* are downloaded from jsdelivr (the VFS has no node_modules) and cached for
|
|
|
|
|
* the session.
|
|
|
|
|
*/
|
|
|
|
|
export async function typecheckProject({ fs, projectPath }: TypecheckProjectOptions): Promise<TypecheckResult> {
|
|
|
|
|
const tsModule = await import("typescript");
|
|
|
|
|
const ts = (tsModule.default ?? tsModule) as TS;
|
|
|
|
|
|
|
|
|
|
const [libFiles, projectFiles, config] = await Promise.all([
|
|
|
|
|
loadLibFiles(),
|
|
|
|
|
readProjectFiles(fs, projectPath),
|
|
|
|
|
resolveConfig(fs, projectPath),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
const converted = ts.convertCompilerOptionsFromJson(
|
|
|
|
|
config.compilerOptions ?? {},
|
|
|
|
|
projectPath,
|
|
|
|
|
`${projectPath}/tsconfig.json`,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const options: tsNamespace.CompilerOptions = {
|
|
|
|
|
// Defaults for browser projects without a tsconfig; overridden by the project's config
|
|
|
|
|
target: ts.ScriptTarget.ES2020,
|
|
|
|
|
module: ts.ModuleKind.ESNext,
|
|
|
|
|
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
|
|
|
jsx: ts.JsxEmit.ReactJSX,
|
|
|
|
|
esModuleInterop: true,
|
|
|
|
|
resolveJsonModule: true,
|
|
|
|
|
...converted.options,
|
|
|
|
|
// Forced: check only, never emit; declarations acquired from the CDN are not authoritative
|
|
|
|
|
noEmit: true,
|
|
|
|
|
skipLibCheck: true,
|
|
|
|
|
incremental: false,
|
|
|
|
|
composite: false,
|
|
|
|
|
declaration: false,
|
|
|
|
|
emitDeclarationOnly: false,
|
|
|
|
|
tsBuildInfoFile: undefined,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const rootFiles = selectRootFiles(projectFiles, projectPath, config, options);
|
|
|
|
|
const aliasPrefixes = aliasPrefixesFrom(options);
|
|
|
|
|
|
|
|
|
|
// Acquire type declarations for npm dependencies referenced by the project
|
|
|
|
|
let packageJson: ProjectPackageJson = {};
|
|
|
|
|
let packageLock: ProjectPackageLock = {};
|
|
|
|
|
try {
|
|
|
|
|
packageJson = JSON.parse(projectFiles.get(`${projectPath}/package.json`) ?? "{}");
|
|
|
|
|
} catch {
|
|
|
|
|
// Malformed package.json; acquire latest types instead of pinned versions
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
packageLock = JSON.parse(projectFiles.get(`${projectPath}/package-lock.json`) ?? "{}");
|
|
|
|
|
} catch {
|
|
|
|
|
// Malformed lockfile; fall back to package.json ranges
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const rootTexts = rootFiles.map((path) => projectFiles.get(path) ?? "");
|
|
|
|
|
const entrySource = buildAtaEntrySource(ts, rootTexts, packageJson, packageLock, aliasPrefixes);
|
|
|
|
|
|
|
|
|
|
let acquiredTypes = new Map<string, string>();
|
|
|
|
|
if (entrySource) {
|
|
|
|
|
try {
|
|
|
|
|
acquiredTypes = await acquireTypes(ts, entrySource);
|
|
|
|
|
} catch {
|
|
|
|
|
// Offline or CDN failure: check what we can without external types
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Assemble the virtual filesystem for the compiler
|
|
|
|
|
const files = new Map<string, string>(libFiles);
|
|
|
|
|
for (const [path, text] of acquiredTypes) {
|
|
|
|
|
files.set(normalizePath(`${projectPath}${path}`), text);
|
|
|
|
|
}
|
|
|
|
|
for (const [path, text] of projectFiles) {
|
|
|
|
|
files.set(path, text);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Provide Vite ambient types (asset imports, import.meta.env) if the real
|
|
|
|
|
// vite/client declarations were not acquired
|
|
|
|
|
const rootNames = [...rootFiles];
|
|
|
|
|
if (!files.has(`${projectPath}/node_modules/vite/client.d.ts`)) {
|
|
|
|
|
files.set(SHIM_PATH, VITE_SHIM);
|
|
|
|
|
rootNames.push(SHIM_PATH);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const host = createCompilerHost(ts, files, projectPath);
|
|
|
|
|
const program = ts.createProgram({ rootNames, options, host });
|
|
|
|
|
const diagnostics = [...converted.errors, ...ts.getPreEmitDiagnostics(program)];
|
|
|
|
|
|
|
|
|
|
const errors: TypecheckDiagnostic[] = [];
|
|
|
|
|
const missingTypes = new Set<string>();
|
|
|
|
|
|
|
|
|
|
for (const diagnostic of diagnostics) {
|
|
|
|
|
if (diagnostic.category !== ts.DiagnosticCategory.Error) continue;
|
|
|
|
|
|
|
|
|
|
const fileName = diagnostic.file?.fileName;
|
|
|
|
|
if (fileName && (fileName.includes("/node_modules/") || fileName.startsWith(LIB_DIR))) continue;
|
|
|
|
|
|
|
|
|
|
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
|
|
|
|
|
|
|
|
|
|
// Missing declarations for npm packages are reported separately, not as
|
|
|
|
|
// errors: the CDN may simply not have types for that package
|
|
|
|
|
if (MISSING_MODULE_CODES.has(diagnostic.code)) {
|
|
|
|
|
const specifier = message.match(/'([^']+)'/)?.[1];
|
|
|
|
|
if (specifier && isBareSpecifier(specifier, aliasPrefixes)) {
|
|
|
|
|
missingTypes.add(packageNameFromSpecifier(specifier));
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const error: TypecheckDiagnostic = { code: diagnostic.code, message };
|
|
|
|
|
if (diagnostic.file && diagnostic.start !== undefined) {
|
|
|
|
|
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
|
|
|
|
|
error.file = diagnostic.file.fileName.startsWith(`${projectPath}/`)
|
|
|
|
|
? diagnostic.file.fileName.slice(projectPath.length + 1)
|
|
|
|
|
: diagnostic.file.fileName;
|
|
|
|
|
error.line = line + 1;
|
|
|
|
|
error.column = character + 1;
|
|
|
|
|
}
|
|
|
|
|
errors.push(error);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
errors,
|
|
|
|
|
checkedFileCount: rootFiles.length,
|
|
|
|
|
missingTypes: [...missingTypes].sort(),
|
|
|
|
|
};
|
|
|
|
|
}
|