Skip to content

Commit

Permalink
update node types and prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs committed Oct 22, 2024
1 parent 92a53c2 commit 65cc7c2
Show file tree
Hide file tree
Showing 47 changed files with 382 additions and 578 deletions.
440 changes: 120 additions & 320 deletions package-lock.json

Large diffs are not rendered by default.

11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
},
"scripts": {
"prepare": "tshy",
"format": "prettier --write . --loglevel warn --cache",
"format": "prettier --write . --log-level warn --cache",
"pretest": "npm run prepare",
"presnap": "npm run prepare",
"snap": "tap",
Expand All @@ -58,19 +58,19 @@
"foreground-child": "^3.1.1",
"mkdirp": "^3.0.1",
"pirates": "^4.0.6",
"rimraf": "^5.0.5",
"rimraf": "^6.0.1",
"signal-exit": "^4.1.0",
"sock-daemon": "^1.4.2",
"walk-up-path": "^3.0.1"
"walk-up-path": "^4.0.0"
},
"peerDependencies": {
"typescript": "^5.1.0"
},
"devDependencies": {
"@swc-node/register": "^1.10.9",
"@types/node": "^20.8.4",
"@types/node": "^22.7.8",
"chalk": "^5.3.0",
"prettier": "^2.8.8",
"prettier": "^3.3.3",
"swc": "^1.0.11",
"tap": "^21.0.1",
"ts-node": "^10.9.1",
Expand All @@ -80,6 +80,7 @@
"typescript": "^5.6.3"
},
"prettier": {
"experimentalTernaries": true,
"semi": false,
"printWidth": 70,
"tabWidth": 2,
Expand Down
17 changes: 8 additions & 9 deletions src/bin.mts
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,20 @@ const [sMajor, sMinor] = process.versions.node.split('.')
/* c8 ignore start */
if (!sMajor || !sMinor) {
throw new Error(
'could not determine node version: ' + process.versions.node
'could not determine node version: ' + process.versions.node,
)
}

const useImport = typeof Module.register === 'function'
const importScript = String(
new URL('./hooks/import.mjs', import.meta.url)
new URL('./hooks/import.mjs', import.meta.url),
)
const loaderScript = String(
new URL('./hooks/legacy-loader.mjs', import.meta.url)
new URL('./hooks/legacy-loader.mjs', import.meta.url),
)
/* c8 ignore start */
const addArg = useImport
? `--import=${importScript}`
: `--loader=${loaderScript}`
const addArg =
useImport ? `--import=${importScript}` : `--loader=${loaderScript}`
/* c8 ignore stop */

const usage = () =>
Expand Down Expand Up @@ -98,17 +97,17 @@ const log = async () => {
await readFile('.tsimp/daemon/log', 'utf8').catch(
e =>
'log could not be read: ' +
(e as NodeJS.ErrnoException).code
(e as NodeJS.ErrnoException).code,
)
).trimEnd()
).trimEnd(),
)
}

const compile = async (src: string) => {
const { DaemonClient } = await import('./client.js')
const start = performance.now()
const { fileName, diagnostics } = await new DaemonClient().compile(
src
src,
)
const duration =
Math.floor((performance.now() - start) * 1000) / 1000
Expand Down
9 changes: 6 additions & 3 deletions src/classify-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@ const readPJType = cachedMtime(
}
const t = JSON.parse(contents).type
return isPackageJsonType(t) ? t : 'commonjs'
})
}),
)

export const classifyModule = (fileName: string): PackageJsonType | 'json' => {
export const classifyModule = (
fileName: string,
): PackageJsonType | 'json' => {
if (fileName.endsWith('.json')) {
return 'json'
} if (fileName.endsWith('.cts') || fileName.endsWith('.cjs')) {
}
if (fileName.endsWith('.cts') || fileName.endsWith('.cjs')) {
return 'commonjs'
} else if (fileName.endsWith('.mts') || fileName.endsWith('.mjs')) {
return 'module'
Expand Down
4 changes: 2 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {

export const serviceName = 'tsimp' as const
export const daemonScript = fileURLToPath(
getUrl('./service/daemon.mjs')
getUrl('./service/daemon.mjs'),
)

/**
Expand Down Expand Up @@ -65,7 +65,7 @@ export class DaemonClient extends SockDaemonClient<
async compile(
inputFile: string,
diagMode: DiagMode = getDiagMode(),
pretty: boolean = !!process.stderr.isTTY
pretty: boolean = !!process.stderr.isTTY,
): Promise<CompileResult> {
inputFile = resolve(inputFile)
const { fileName, diagnostics } = (await this.request({
Expand Down
2 changes: 1 addition & 1 deletion src/diagnostic-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const getDiagMode = (): DiagMode => {
if (!isDiagMode(d))
throw new Error(
`Invalid TSIMP_DIAG environment variable: ${d}. Must be one of: ` +
`'ignore', 'warn', or 'error'`
`'ignore', 'warn', or 'error'`,
)
return d
}
2 changes: 1 addition & 1 deletion src/equivalents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const isExt = (e: any): e is TSExt | JSExt =>

export const equivalents = (
path: string,
extensionless = false
extensionless = false,
): string[] => {
const { ext } = parse(path)
const stem = path.substring(0, path.length - ext.length)
Expand Down
25 changes: 13 additions & 12 deletions src/hooks/hooks.mts
Original file line number Diff line number Diff line change
Expand Up @@ -52,29 +52,30 @@ export const initialize: InitializeHook = ({
export const resolve: ResolveHook = async (
url,
context,
nextResolve
nextResolve,
) => {
const { parentURL } = context
const target =
/* c8 ignore start */
parentURL && (url.startsWith('./') || url.startsWith('../'))
? /* c8 ignore stop */
String(new URL(url, parentURL))
: url
parentURL && (url.startsWith('./') || url.startsWith('../')) ?
/* c8 ignore stop */
String(new URL(url, parentURL))
: url
return nextResolve(
target.startsWith('file://') && !startsWithCS(target, nm)
? await getClient().resolve(url, parentURL)
: url,
context
target.startsWith('file://') && !startsWithCS(target, nm) ?
await getClient().resolve(url, parentURL)
: url,
context,
)
}

// case (in-)sensitive String.startsWith
const cs =
process.platform !== 'win32' && process.platform !== 'darwin'
/* c8 ignore start */
const startsWithCS = cs
? (haystack: string, needle: string) => haystack.startsWith(needle)
const startsWithCS =
cs ?
(haystack: string, needle: string) => haystack.startsWith(needle)
: (haystack: string, needle: string) =>
haystack.toUpperCase().startsWith(needle.toUpperCase())
/* c8 ignore stop */
Expand All @@ -90,7 +91,7 @@ export const load: LoadHook = async (url, context, nextLoad) => {
const { fileName, diagnostics } = await getClient().compile(
inputFile,
diagMode,
pretty
pretty,
)
for (const d of diagnostics) consoleError(d)
if (!fileName) {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/require.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ if (typeof Module.register !== 'function') {
}
return (file ? readFile(file) : code) || code
},
{ exts: ['.ts', '.cts'], ignoreNodeModules: true }
{ exts: ['.ts', '.cts'], ignoreNodeModules: true },
)
}
/* c8 ignore stop */
6 changes: 3 additions & 3 deletions src/require-commonjs-load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const req = createRequire(import.meta.url)

export const requireCommonJSLoad = () =>
req(
inDist
? resolve(__dirname, '../commonjs/service/load.js')
: resolve(__dirname, '../dist/commonjs/service/load.js')
inDist ?
resolve(__dirname, '../commonjs/service/load.js')
: resolve(__dirname, '../dist/commonjs/service/load.js'),
) as typeof import('./service/load.js')
15 changes: 7 additions & 8 deletions src/service/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,20 @@ import {
export const compile = (
code: string,
fileName: string,
typeCheck = true
typeCheck = true,
) => {
const normalizedFileName: string = normalizeSlashes(fileName)
const classification = classifyModule(normalizedFileName)
const getOutput = typeCheck
? getOutputTypeCheck
: getOutputTranspileOnly
const getOutput =
typeCheck ? getOutputTypeCheck : getOutputTranspileOnly
const forceOutput =
classification === 'commonjs'
? getOutputForceCommonJS
: getOutputForceESM
classification === 'commonjs' ?
getOutputForceCommonJS
: getOutputForceESM

let { outputText, diagnostics } = getOutput(
code,
normalizedFileName
normalizedFileName,
)

return {
Expand Down
2 changes: 1 addition & 1 deletion src/service/create-mode-aware-cache-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ResolutionMode } from 'typescript'

export function createModeAwareCacheKey(
specifier: string,
mode?: ResolutionMode
mode?: ResolutionMode,
) {
return mode === undefined ? specifier : `${mode}|${specifier}`
}
6 changes: 3 additions & 3 deletions src/service/daemon.mts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ const cwd = process.cwd()
/* c8 ignore start */
const home = (process.env.HOME ?? '').replace(/[\\\/]$/, '')
const d =
home && cwd.startsWith(home)
? `~${cwd.substring(home.length)}`
: cwd
home && cwd.startsWith(home) ?
`~${cwd.substring(home.length)}`
: cwd
/* c8 ignore stop */
process.title = 'tsimp daemon ' + d
new DaemonServer().listen()
Expand Down
10 changes: 5 additions & 5 deletions src/service/diagnostic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const cwd = process.cwd()
// anyway.
export const reportAll = (
diagnostics: Diagnostic[],
pretty?: boolean
pretty?: boolean,
) =>
diagnostics.filter(d => d.code !== 6059).map(d => report(d, pretty))

Expand All @@ -21,8 +21,8 @@ const host = {

export const report = (
diagnostic: Diagnostic,
pretty = !!process.stderr.isTTY
pretty = !!process.stderr.isTTY,
): string =>
pretty
? ts.formatDiagnosticsWithColorAndContext([diagnostic], host)
: ts.formatDiagnostic(diagnostic, host)
pretty ?
ts.formatDiagnosticsWithColorAndContext([diagnostic], host)
: ts.formatDiagnostic(diagnostic, host)
4 changes: 2 additions & 2 deletions src/service/file-versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ export const fileContents = new Map<string, string>()

let projectVersionNum = 0
export const fileVersions = new Map<string, number>(
[...rootFileNames()].map(fileName => [fileName, 0])
[...rootFileNames()].map(fileName => [fileName, 0]),
)
export const projectVersion = () => String(projectVersionNum)
export const incProjectVersion = () => String(++projectVersionNum)

export const updateFileVersion = (
fileName: string,
contents: string
contents: string,
) => {
const previousVersion = fileVersions.get(fileName) ?? 0
const previousContents = fileContents.get(fileName)
Expand Down
5 changes: 3 additions & 2 deletions src/service/get-canonical-filename.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import ts from 'typescript'
const fileNameLowerCaseRegExp =
/[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g
export const getCanonicalFileName = !ts.sys.useCaseSensitiveFileNames
? (x: string) =>
export const getCanonicalFileName =
!ts.sys.useCaseSensitiveFileNames ?
(x: string) =>
x.replace(fileNameLowerCaseRegExp, s => s.toLowerCase())
: (x: string) => x
4 changes: 2 additions & 2 deletions src/service/get-output-typecheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { markFileNameInternal } from './resolve-module-name-literals.js'
const cwd = process.cwd()
export const getOutputTypeCheck = (
code: string,
fileName: string
fileName: string,
): {
outputText: string | undefined
diagnostics: ts.Diagnostic[]
Expand Down Expand Up @@ -68,7 +68,7 @@ export const getOutputTypeCheck = (
`Unable to require file: ${relative(cwd, fileName)}\n` +
'This is usually the result of a faulty configuration or import. ' +
'Make sure there is a `.js`, `.json` or other executable ' +
'extension with loader attached before `tsimp` available.'
'extension with loader attached before `tsimp` available.',
)
}
/* c8 ignore stop */
Expand Down
8 changes: 4 additions & 4 deletions src/service/language-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const getLanguageService = (): LanguageServiceWithHost => {
getScriptVersion: (fileName: string) =>
String(fileVersions.get(fileName)),
getScriptSnapshot: (
fileName: string
fileName: string,
): ts.IScriptSnapshot | undefined => {
let contents = fileContents.get(fileName)

Expand All @@ -99,22 +99,22 @@ export const getLanguageService = (): LanguageServiceWithHost => {
resolveTypeReferenceDirectiveReferences:
getResolveTypeReferenceDirectiveReferences(
host,
getModuleResolutionCache()
getModuleResolutionCache(),
),
resolveModuleNameLiterals: getResolveModuleNameLiterals(host),
getModuleResolutionCache,
})

const registry = ts.createDocumentRegistry(
ts.sys.useCaseSensitiveFileNames,
getCurrentDirectory()
getCurrentDirectory(),
)

lastService = Object.assign(
ts.createLanguageService(hostWithResModNameLit, registry),
{
getHost: () => hostWithResModNameLit,
}
},
)
const duration =
Math.floor((performance.now() - start) * 1000) / 1000
Expand Down
2 changes: 1 addition & 1 deletion src/service/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ let didMkdirp = false
export const load = (
fileName: string,
typeCheck = true,
pretty = true
pretty = true,
): CompileResult => {
fileName = resolve(fileName)
const config = tsconfig()
Expand Down
Loading

0 comments on commit 65cc7c2

Please sign in to comment.