Skip to content

Commit

Permalink
fix: добавлено удаление зависимых импортов в cjs и ускорен ts-morph
Browse files Browse the repository at this point in the history
  • Loading branch information
LorexIQ committed Nov 15, 2024
1 parent b957a15 commit 24925ba
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 21 deletions.
7 changes: 3 additions & 4 deletions src/runtime/autoImport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@ import type {
} from './types';
import defineConnector from './composables/defineConnector';
import loadTsModule from './helpers/loadTsModule';
import getTsMorphProject from './helpers/getTsMorphProject';
import tsMorphProject from './helpers/tsMorphProject';
import pathRelativeMove from './helpers/pathRelativeMove';
import logger from './helpers/logger';

export class Module {
private readonly rootDir: string;
private readonly debugEnabled: boolean;
private readonly project = getTsMorphProject();

private readonly config: ModuleOptionsExtend;
private readonly typeGeneratorListFunc: ModuleConnectorTypeGenerator[] = [];
Expand Down Expand Up @@ -56,8 +55,8 @@ export class Module {

if (!fs.existsSync(definesDir)) fs.mkdirSync(definesDir);

const parsedConnector = this.project.createSourceFile(`${name}.${Date.now()}.temp.ts`, content);
const sourceFile = this.project.createSourceFile(definePath, '', { overwrite: true });
const parsedConnector = tsMorphProject.createSourceFile(`${name}.temp.ts`, content, { overwrite: true });
const sourceFile = tsMorphProject.createSourceFile(definePath, '', { overwrite: true });

sourceFile.addImportDeclaration({
moduleSpecifier: '../types',
Expand Down
10 changes: 0 additions & 10 deletions src/runtime/helpers/getTsMorphProject.ts

This file was deleted.

41 changes: 37 additions & 4 deletions src/runtime/helpers/loadTsModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,55 @@ import path from 'node:path';
import fs from 'node:fs';
import { pathToFileURL } from 'node:url';
import esbuild from 'esbuild';
import { resolveAlias } from '@nuxt/kit';
import type { SourceFile } from 'ts-morph';
import tsMorphProject from './tsMorphProject';

export default async function (modulePath: string) {
function clearTemp(tempPath: string, file?: SourceFile) {
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
file && tsMorphProject.removeSourceFile(file);
}

function getImportPath(ctxPath: string, p: string) {
const asAliasResolve = resolveAlias(p);
const asPathResolve = path.resolve(ctxPath, p);
const isAliasPath = asAliasResolve !== p;
const isRelativePath = p.startsWith('.') || p.startsWith('/');
const importPath = isRelativePath ? asPathResolve : asAliasResolve;

if (isAliasPath || isRelativePath) {
if (fs.existsSync(importPath + '.ts')) return importPath + '.ts';
else if (fs.existsSync(importPath + '\\index.ts')) return importPath + '\\index.ts';
else return undefined;
} else {
return undefined;
}
}

export default async function loadTsModule(modulePath: string) {
const fullPath = path.resolve(modulePath);
const parsedPath = path.parse(fullPath);
const tempTsFilePath = fullPath.replace(/\.ts$/, `.${Date.now()}.temp.ts`);
const tempJsFilePath = fullPath.replace(/\.ts$/, `.${Date.now()}.temp.js`);
let sourceFile: SourceFile | undefined = undefined;

try {
const tsCode = fs.readFileSync(fullPath, 'utf8');
const { code } = await esbuild.transform(tsCode, { loader: 'ts' });
sourceFile = tsMorphProject.createSourceFile(tempTsFilePath, tsCode, { overwrite: true });

await Promise.all(sourceFile.getImportDeclarations().map(async (imp) => {
const importPath = getImportPath(parsedPath.dir, imp.getStructure().moduleSpecifier);
if (importPath) imp.remove();
}));
const { code } = await esbuild.transform(sourceFile.getFullText(), { loader: 'ts' });

fs.writeFileSync(tempJsFilePath, code, 'utf8');
const module = await import(pathToFileURL(tempJsFilePath).href);
fs.unlinkSync(tempJsFilePath);
clearTemp(tempJsFilePath, sourceFile);

return module;
} catch {
if (fs.existsSync(tempJsFilePath)) fs.unlinkSync(tempJsFilePath);
clearTemp(tempJsFilePath, sourceFile);
return undefined;
}
}
10 changes: 10 additions & 0 deletions src/runtime/helpers/tsMorphProject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { IndentationText, Project } from 'ts-morph';

const tsMorphProject = new Project({
tsConfigFilePath: './tsconfig.json',
manipulationSettings: {
indentationText: IndentationText.TwoSpaces
}
});

export default tsMorphProject;
5 changes: 2 additions & 3 deletions src/runtime/helpers/typeGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'node:path';
import fs from 'node:fs';
import type { WriterFunction } from 'ts-morph';
import getTsMorphProject from './getTsMorphProject';
import tsMorphProject from './tsMorphProject';

export default function (typesDir: string, typeName: string, content: string | WriterFunction, tryRead = false) {
if (typeName.length === 0) return;
Expand All @@ -12,8 +12,7 @@ export default function (typesDir: string, typeName: string, content: string | W

if (tryRead && fs.existsSync(filePath)) return filePath;

const project = getTsMorphProject();
const file = project.createSourceFile(filePath, '', { overwrite: true });
const file = tsMorphProject.createSourceFile(filePath, '', { overwrite: true });

file.addStatements((writer) => {
writer.write('declare global').block(() => {
Expand Down

0 comments on commit 24925ba

Please sign in to comment.