From 1f60be519b8fba1e5d33e71c403ae86a4f03db3d Mon Sep 17 00:00:00 2001 From: Fedor Kuznetsov Date: Tue, 14 Nov 2023 22:58:25 +0500 Subject: [PATCH] Add support of ts5+ --- test/compile/compile.ts | 16 +++++++++++++++- transformer.ts | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/test/compile/compile.ts b/test/compile/compile.ts index fab715c..6570fe3 100644 --- a/test/compile/compile.ts +++ b/test/compile/compile.ts @@ -1,12 +1,26 @@ import ts from 'typescript'; import transformer from '../../transformer'; +function getDefaultModuleResolution(): ts.ModuleResolutionKind { + if('NodeJs' in ts.ModuleResolutionKind) { + return ts.ModuleResolutionKind.NodeJs; + } + + if('Node10' in ts.ModuleResolutionKind) { + // @ts-ignore forward compatibility check + return ts.ModuleResolutionKind.Node10 as ts.ModuleResolutionKind; + } + + throw new Error('Cannot choose default module resolution kind') +} + export function compile(filePaths: string[], target = ts.ScriptTarget.ES5, writeFileCallback?: ts.WriteFileCallback) { const program = ts.createProgram(filePaths, { strict: true, noEmitOnError: true, - suppressImplicitAnyIndexErrors: true, + noUncheckedIndexedAccess: false, esModuleInterop: true, + moduleResolution: getDefaultModuleResolution(), target }); const transformers: ts.CustomTransformers = { diff --git a/transformer.ts b/transformer.ts index b9640a6..8281847 100644 --- a/transformer.ts +++ b/transformer.ts @@ -1,8 +1,39 @@ import ts from 'typescript'; import path from 'path'; -const createArrayExpression = ts.factory ? ts.factory.createArrayLiteralExpression : ts.createArrayLiteral; -const createStringLiteral = ts.factory ? ts.factory.createStringLiteral : ts.createLiteral; +type ArrayFactory = ( + elements?: readonly ts.Expression[] | undefined, + multiLine?: boolean | undefined +) => ts.ArrayLiteralExpression; + +const createArrayExpression = ((): ArrayFactory => { + if (ts.factory) { + return ts.factory.createArrayLiteralExpression; + } + + if ("createArrayLiteral" in ts) { + return ts.createArrayLiteral as ArrayFactory; + } + + throw new Error("Cannot choose array literal factory"); +})(); + +type StringFactory = ( + text: string, + isSingleQuote?: boolean | undefined +) => ts.StringLiteral; + +const createStringLiteral = ((): StringFactory => { + if (ts.factory) { + return ts.factory.createStringLiteral; + } + + if ("createLiteral" in ts) { + return ts.createLiteral as StringFactory; + } + + throw new Error("Cannot choose string literal factory"); +})(); export default function transformer(program: ts.Program): ts.TransformerFactory { return (context: ts.TransformationContext) => (file: ts.SourceFile) => visitNodeAndChildren(file, program, context);