fix: restore typecheck under nodenext

This commit is contained in:
hazre committed 2026-03-29 15:39:54 +02:00
1 parent 08f0234223
commit a900bada22
10 files changed
+325 -21

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ import {
rewriteSourceImports,
} from './utils/import-rewrites.js';
/** @type {string[]} */
const tempDirs = [];
async function makeTempProject() {
+42 -1
View File
@@ -11,6 +11,11 @@ import { PrefixedLogger, createTextHelpers } from './utils/console-style.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const VERSION = '0.22.3';
/**
* @typedef {'linux-x64' | 'linux-arm64' | 'darwin-x64' | 'darwin-arm64' | 'win32-x64'} SupportedTargetKey
*/
/** @type {Record<SupportedTargetKey, string>} */
const TARGETS = {
'linux-x64': 'x86_64-unknown-linux-musl',
'linux-arm64': 'aarch64-unknown-linux-musl',
@@ -19,11 +24,19 @@ const TARGETS = {
'win32-x64': 'x86_64-pc-windows-msvc',
};
/**
* @param {string | null | undefined} output
* @returns {string | null}
*/
function parseKnopeVersion(output) {
const version = output?.trim().replace(/^knope\s+/, '');
return version || null;
}
/**
* @param {string} command
* @returns {string | null}
*/
function getKnopeVersion(command) {
const result = spawnSync(command, ['--version'], { encoding: 'utf8' });
if (result.status !== 0) {
@@ -32,17 +45,30 @@ function getKnopeVersion(command) {
return parseKnopeVersion(result.stdout);
}
/**
* @param {Buffer} buffer
* @returns {string}
*/
function readNullTerminatedString(buffer) {
const nulIndex = buffer.indexOf(0);
const end = nulIndex === -1 ? buffer.length : nulIndex;
return buffer.toString('utf8', 0, end);
}
/**
* @param {string} entryName
* @returns {string}
*/
function getTarBasename(entryName) {
const segments = entryName.split('/').filter(Boolean);
return segments.at(-1) ?? '';
}
/**
* @param {Buffer} tarBuffer
* @param {string} expectedBasename
* @returns {Buffer}
*/
function extractRegularFileFromTar(tarBuffer, expectedBasename) {
let offset = 0;
const regularEntries = [];
@@ -87,6 +113,9 @@ function extractRegularFileFromTar(tarBuffer, expectedBasename) {
);
}
/**
* @returns {string | null}
*/
function getSystemKnopePath() {
const which = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['knope'], {
encoding: 'utf8',
@@ -102,7 +131,16 @@ function getSystemKnopePath() {
);
}
/**
* @param {string} candidatePath
* @param {string} rootPath
* @returns {boolean}
*/
function isPathWithin(candidatePath, rootPath) {
/**
* @param {string} value
* @returns {string}
*/
const toComparablePath = (value) => {
const resolved = resolve(value);
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
@@ -120,7 +158,10 @@ if (process.env.GITHUB_ACTIONS && process.env.CI) {
process.exit(0);
}
const target = TARGETS[`${process.platform}-${process.arch}`];
const targetKey = `${process.platform}-${process.arch}`;
const target = Object.hasOwn(TARGETS, targetKey)
? TARGETS[/** @type {SupportedTargetKey} */ (targetKey)]
: undefined;
if (!target) {
const supported = Object.keys(TARGETS).join(', ');
logger.error(
+68
View File
@@ -19,6 +19,40 @@ import {
const MATRIX_BOUNDARY_SPECIFIER = '$types/matrix-sdk';
/**
* @typedef {{
* write: boolean;
* roots: string[];
* }} CliArgs
*/
/**
* @typedef {{
* importedName: string;
* localName: string;
* }} ImportEntry
*/
/**
* @typedef {{
* values: ImportEntry[];
* types: ImportEntry[];
* }} MatrixImportGroup
*/
/**
* @typedef {{
* start: number;
* end: number;
* original: string;
* value: string;
* }} Replacement
*/
/**
* @param {string[]} argv
* @returns {CliArgs}
*/
function parseArgs(argv) {
let write = false;
const roots = [];
@@ -55,6 +89,10 @@ function parseArgs(argv) {
};
}
/**
* @param {string} projectRoot
* @returns {import('typescript').Program}
*/
function loadProgram(projectRoot) {
const tsconfigPath = path.join(projectRoot, 'tsconfig.json');
const configResult = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
@@ -85,6 +123,11 @@ function loadProgram(projectRoot) {
});
}
/**
* @param {string} filePath
* @param {string[]} rootPaths
* @returns {boolean}
*/
function isWithinRoots(filePath, rootPaths) {
return rootPaths.some((rootPath) => {
const relativePath = path.relative(rootPath, filePath);
@@ -94,6 +137,11 @@ function isWithinRoots(filePath, rootPaths) {
});
}
/**
* @param {import('typescript').TypeChecker} checker
* @param {import('typescript').ImportSpecifier} specifier
* @returns {string | null}
*/
function getDeclarationModuleSpecifier(checker, specifier) {
const importedSymbol = checker.getSymbolAtLocation(specifier.name);
if (!importedSymbol) return null;
@@ -108,6 +156,10 @@ function getDeclarationModuleSpecifier(checker, specifier) {
return getMatrixModuleSpecifierFromDeclarationFile(declaration.getSourceFile().fileName);
}
/**
* @param {import('typescript').ImportSpecifier} specifier
* @returns {ImportEntry}
*/
function getImportEntry(specifier) {
return {
importedName: specifier.propertyName?.text ?? specifier.name.text,
@@ -115,6 +167,11 @@ function getImportEntry(specifier) {
};
}
/**
* @param {import('typescript').TypeChecker} checker
* @param {import('typescript').ImportDeclaration} importDeclaration
* @returns {string | null}
*/
function buildReplacementText(checker, importDeclaration) {
const importClause = importDeclaration.importClause;
if (
@@ -125,6 +182,7 @@ function buildReplacementText(checker, importDeclaration) {
return null;
}
/** @type {Map<string, MatrixImportGroup>} */
const groups = new Map();
for (const specifier of importClause.namedBindings.elements) {
@@ -142,9 +200,18 @@ function buildReplacementText(checker, importDeclaration) {
return renderMatrixImportGroups(groups).join('\n');
}
/**
* @param {import('typescript').SourceFile} sourceFile
* @param {import('typescript').TypeChecker} checker
* @returns {Replacement[]}
*/
function collectReplacements(sourceFile, checker) {
/** @type {Replacement[]} */
const replacements = [];
/**
* @param {import('typescript').Node} node
*/
function visit(node) {
if (
ts.isImportDeclaration(node) &&
@@ -156,6 +223,7 @@ function collectReplacements(sourceFile, checker) {
replacements.push({
start: node.getStart(sourceFile),
end: node.getEnd(),
original: '',
value: replacementText,
});
}
+20
View File
@@ -13,6 +13,25 @@ import {
toPosix,
} from './utils/import-rewrites.js';
/**
* @typedef {{
* write: boolean;
* roots: string[];
* }} CliArgs
*/
/**
* @typedef {{
* file: string;
* replacements: number;
* edits: { from: string; to: string }[];
* }} FileResult
*/
/**
* @param {string[]} argv
* @returns {CliArgs}
*/
function parseArgs(argv) {
let write = false;
const roots = [];
@@ -101,6 +120,7 @@ async function main() {
})
);
/** @type {FileResult[]} */
const changedFiles = fileResults.filter((result) => result !== null);
const filesChanged = changedFiles.length;
const importRewrites = changedFiles.reduce((total, result) => total + result.replacements, 0);
+38
View File
@@ -1,6 +1,17 @@
/* eslint-disable no-console */
import process from 'node:process';
/**
* @typedef {object} TextHelperOptions
* @property {boolean} [useColor]
*/
/**
* @typedef {TextHelperOptions & {
* prefixColor?: string;
* }} LoggerOptions
*/
export const ANSI = {
reset: '\x1b[0m',
red: '\x1b[31m',
@@ -14,16 +25,33 @@ export function shouldUseColor() {
return Boolean(process.stdout.isTTY);
}
/**
* @param {string} text
* @param {string} color
* @param {boolean} enabled
* @returns {string}
*/
export function styleText(text, color, enabled) {
if (!enabled) return text;
return `${color}${text}${ANSI.reset}`;
}
/**
* @param {TextHelperOptions} [options]
*/
export function createTextHelpers(options = {}) {
const useColor = options.useColor ?? shouldUseColor();
/**
* @param {string} text
* @param {string} color
* @returns {string}
*/
const style = (text, color) => styleText(text, color, useColor);
/** @param {string} text */
const dim = (text) => styleText(text, ANSI.dim, useColor);
/** @param {string} text */
const red = (text) => styleText(text, ANSI.red, useColor);
/** @param {string} text */
const green = (text) => styleText(text, ANSI.green, useColor);
return {
useColor,
@@ -35,20 +63,30 @@ export function createTextHelpers(options = {}) {
}
export class PrefixedLogger {
/**
* @param {string} prefix
* @param {LoggerOptions} [options]
*/
constructor(prefix, options = {}) {
this.prefix = prefix;
this.useColor = options.useColor ?? shouldUseColor();
this.prefixColor = options.prefixColor ?? ANSI.dim;
}
/**
* @param {string} message
* @returns {string}
*/
withPrefix(message) {
return `${styleText(this.prefix, this.prefixColor, this.useColor)} ${message}`;
}
/** @param {string} message */
info(message) {
console.log(this.withPrefix(message));
}
/** @param {string} message */
error(message) {
console.error(this.withPrefix(message));
}
+127 -13
View File
@@ -3,6 +3,36 @@ import path from 'node:path';
import ts from 'typescript';
/**
* @typedef {{
* alias: string;
* absolutePath: string;
* }} AliasEntry
*/
/**
* @typedef {{
* start: number;
* end: number;
* original: string;
* value: string;
* }} TextReplacement
*/
/**
* @typedef {{
* importedName: string;
* localName: string;
* }} MatrixImportSpecifier
*/
/**
* @typedef {{
* values: MatrixImportSpecifier[];
* types: MatrixImportSpecifier[];
* }} MatrixImportGroup
*/
export const DEFAULT_ROOTS = ['src'];
export const SKIP_DIRS = new Set(['.git', '.hg', '.svn', 'node_modules', 'dist', 'coverage']);
export const SOURCE_EXTENSIONS = new Set([
@@ -20,18 +50,35 @@ export const MATRIX_IMPORT_BOUNDARY_FILES = new Set([
path.normalize('src/types/matrix-sdk-events.d.ts'),
]);
/**
* @param {string} inputPath
* @returns {string}
*/
export function toPosix(inputPath) {
return inputPath.split(path.sep).join('/');
}
/**
* @param {string} pattern
* @returns {string}
*/
function normalizeAliasPattern(pattern) {
return pattern.replace(/\/\*$/, '');
}
/**
* @param {import('typescript').Diagnostic} error
* @returns {string}
*/
function getConfigErrorMessage(error) {
return ts.flattenDiagnosticMessageText(error.messageText, '\n');
}
/**
* @param {string} tsconfigPath
* @param {string} projectRoot
* @returns {Promise<AliasEntry[]>}
*/
export async function loadAliasMapFromTsconfig(tsconfigPath, projectRoot) {
const configResult = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
if (configResult.error) {
@@ -44,29 +91,35 @@ export async function loadAliasMapFromTsconfig(tsconfigPath, projectRoot) {
const baseUrl = compilerOptions.baseUrl ?? '.';
const paths = compilerOptions.paths ?? {};
const aliasMap = [
...new Map(
Object.entries(paths)
.map(([aliasPattern, targets]) => {
if (!Array.isArray(targets) || targets.length === 0) return null;
/** @type {Map<string, AliasEntry>} */
const aliasEntries = new Map();
for (const [aliasPattern, targets] of Object.entries(paths)) {
if (!Array.isArray(targets) || targets.length === 0) continue;
const alias = normalizeAliasPattern(aliasPattern);
const targetPattern = normalizeAliasPattern(targets[0]);
const absolutePath = path.resolve(projectRoot, baseUrl, targetPattern);
const alias = normalizeAliasPattern(aliasPattern);
const targetPattern = normalizeAliasPattern(targets[0]);
const absolutePath = path.resolve(projectRoot, baseUrl, targetPattern);
aliasEntries.set(`${alias}:${absolutePath}`, { alias, absolutePath });
}
return [`${alias}:${absolutePath}`, { alias, absolutePath }];
})
.filter(Boolean)
).values(),
];
const aliasMap = [...aliasEntries.values()];
aliasMap.sort((a, b) => b.absolutePath.length - a.absolutePath.length);
return aliasMap;
}
/**
* @param {string} rootDir
* @returns {Promise<string[]>}
*/
export async function collectSourceFiles(rootDir) {
/** @type {string[]} */
const files = [];
/**
* @param {string} currentDir
* @returns {Promise<void>}
*/
async function walk(currentDir) {
const entries = await fs.readdir(currentDir, { withFileTypes: true });
await Promise.all(
@@ -90,6 +143,10 @@ export async function collectSourceFiles(rootDir) {
return files;
}
/**
* @param {string} specifier
* @returns {{ bare: string; suffix: string }}
*/
function splitSpecifier(specifier) {
const match = specifier.match(/^([^?#]+)([?#].*)?$/);
if (!match) {
@@ -102,6 +159,11 @@ function splitSpecifier(specifier) {
};
}
/**
* @param {string} absoluteTargetPath
* @param {AliasEntry[]} aliases
* @returns {AliasEntry | undefined}
*/
function findMatchingAlias(absoluteTargetPath, aliases) {
return aliases.find(({ absolutePath }) => {
const rel = path.relative(absolutePath, absoluteTargetPath);
@@ -109,6 +171,13 @@ function findMatchingAlias(absoluteTargetPath, aliases) {
});
}
/**
* @param {string} filePath
* @param {string} specifier
* @param {AliasEntry[]} aliases
* @param {string} projectRoot
* @returns {string | null}
*/
function getRewrittenSpecifier(filePath, specifier, aliases, projectRoot) {
const normalizedFilePath = path.normalize(path.relative(projectRoot, filePath));
const { bare, suffix } = splitSpecifier(specifier);
@@ -135,6 +204,14 @@ function getRewrittenSpecifier(filePath, specifier, aliases, projectRoot) {
return `${aliasImport}${suffix}`;
}
/**
* @param {import('typescript').SourceFile} sourceFile
* @param {import('typescript').StringLiteral} literalNode
* @param {TextReplacement[]} replacements
* @param {AliasEntry[]} aliases
* @param {string} filePath
* @param {string} projectRoot
*/
function queueReplacement(sourceFile, literalNode, replacements, aliases, filePath, projectRoot) {
const specifier = literalNode.text;
const rewrittenSpecifier = getRewrittenSpecifier(filePath, specifier, aliases, projectRoot);
@@ -148,6 +225,11 @@ function queueReplacement(sourceFile, literalNode, replacements, aliases, filePa
});
}
/**
* @param {string} sourceCode
* @param {TextReplacement[]} replacements
* @returns {string}
*/
export function applyTextReplacements(sourceCode, replacements) {
return replacements.reduce(
(code, replacement) =>
@@ -156,10 +238,20 @@ export function applyTextReplacements(sourceCode, replacements) {
);
}
/**
* @param {string} filePath
* @param {string} sourceCode
* @param {AliasEntry[]} aliases
* @param {string} projectRoot
*/
export function rewriteSourceImports(filePath, sourceCode, aliases, projectRoot) {
const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.Latest, true);
/** @type {TextReplacement[]} */
const replacements = [];
/**
* @param {import('typescript').Node} node
*/
function visit(node) {
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
queueReplacement(
@@ -207,6 +299,7 @@ export function rewriteSourceImports(filePath, sourceCode, aliases, projectRoot)
return { changed: false, updatedCode: sourceCode, replacements: 0, edits: [] };
}
/** @type {TextReplacement[]} */
const uniqueReplacements = [
...new Map(
replacements.map((replacement) => [`${replacement.start}:${replacement.end}`, replacement])
@@ -226,6 +319,10 @@ export function rewriteSourceImports(filePath, sourceCode, aliases, projectRoot)
};
}
/**
* @param {string} relativePath
* @returns {string}
*/
function stripDeclarationExtension(relativePath) {
return relativePath
.replace(/\.d\.[cm]?ts$/i, '')
@@ -233,6 +330,10 @@ function stripDeclarationExtension(relativePath) {
.replace(/\.[cm]?js$/i, '');
}
/**
* @param {string} declarationFile
* @returns {string | null}
*/
export function getMatrixModuleSpecifierFromDeclarationFile(declarationFile) {
const normalizedFile = toPosix(declarationFile);
const marker = '/node_modules/matrix-js-sdk/';
@@ -244,17 +345,30 @@ export function getMatrixModuleSpecifierFromDeclarationFile(declarationFile) {
return `matrix-js-sdk/${stripDeclarationExtension(relativePath)}`;
}
/**
* @param {MatrixImportSpecifier[]} specifiers
* @returns {MatrixImportSpecifier[]}
*/
function sortSpecifiers(specifiers) {
return [...specifiers].toSorted((left, right) =>
left.importedName.localeCompare(right.importedName)
);
}
/**
* @param {MatrixImportSpecifier} specifier
* @returns {string}
*/
function formatSpecifier({ importedName, localName }) {
return importedName === localName ? importedName : `${importedName} as ${localName}`;
}
/**
* @param {Map<string, MatrixImportGroup>} groups
* @returns {string[]}
*/
export function renderMatrixImportGroups(groups) {
/** @type {string[]} */
const lines = [];
[...groups.entries()]
+3
View File
@@ -0,0 +1,3 @@
declare function bgColorImg(img: HTMLImageElement): string;
export default bgColorImg;
+8
View File
@@ -0,0 +1,8 @@
import type { CryptoCallbacks } from '$types/matrix-sdk';
export function storePrivateKey(keyId: string, privateKey: Uint8Array): void;
export function clearSecretStorageKeys(): void;
export const cryptoCallbacks: Pick<
CryptoCallbacks,
'getSecretStorageKey' | 'cacheSecretStorageKey'
>;
+6 -2
View File
@@ -1,17 +1,21 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"module": "NodeNext",
"lib": ["ESNext"],
"types": ["node"],
"allowJs": true,
"checkJs": true,
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"moduleResolution": "bundler",
"moduleResolution": "NodeNext",
"allowImportingTsExtensions": true,
"rewriteRelativeImportExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"composite": true,
"noEmit": true,
"tsBuildInfoFile": "./.tsbuildinfo/tsconfig.node.tsbuildinfo"
+12 -5
View File
@@ -1,14 +1,16 @@
import { defineConfig } from 'vite';
import type { ViteDevServer, PluginOption } from 'vite';
import { execSync } from 'child_process';
import type { RollupInjectOptions } from '@rollup/plugin-inject';
import react from '@vitejs/plugin-react';
import svgr from 'vite-plugin-svgr';
import { wasm } from '@rollup/plugin-wasm';
import { viteStaticCopy } from 'vite-plugin-static-copy';
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';
import inject from '@rollup/plugin-inject';
import topLevelAwait from 'vite-plugin-top-level-await';
import * as injectModule from '@rollup/plugin-inject';
import * as topLevelAwaitModule from 'vite-plugin-top-level-await';
import type { Options as TopLevelAwaitOptions } from 'vite-plugin-top-level-await';
import { VitePWA } from 'vite-plugin-pwa';
import { compression, defineAlgorithm } from 'vite-plugin-compression2';
import { constants as zlibConstants } from 'zlib';
@@ -17,7 +19,12 @@ import path from 'path';
import { cloudflare } from '@cloudflare/vite-plugin';
import { createRequire } from 'module';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import buildConfig from './build.config';
import buildConfig from './build.config.ts';
const inject = injectModule.default as unknown as (options?: RollupInjectOptions) => PluginOption;
const topLevelAwait = topLevelAwaitModule.default as unknown as (
options?: TopLevelAwaitOptions
) => PluginOption;
const packageJson = JSON.parse(
fs.readFileSync(path.resolve(__dirname, 'package.json'), 'utf8')
@@ -150,7 +157,7 @@ export default defineConfig(({ command }) => ({
// The export name of top-level await promise for each chunk module
promiseExportName: '__tla',
// The function to generate import names of top-level await promise in each chunk module
promiseImportName: (i) => `__tla_${i}`,
promiseImportName: (i: number) => `__tla_${i}`,
}),
viteStaticCopy(copyFiles),
vanillaExtractPlugin({ identifiers: 'debug' }),
@@ -237,7 +244,7 @@ export default defineConfig(({ command }) => ({
sourcemap: true,
copyPublicDir: false,
rollupOptions: {
plugins: [inject({ Buffer: ['buffer', 'Buffer'] }) as PluginOption],
plugins: [inject({ Buffer: ['buffer', 'Buffer'] })],
},
},
}));