Skip to content

perf: improve polymorphism code generation speed #1073

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/schema/src/plugins/enhancer/delegate/index.ts
Original file line number Diff line number Diff line change
@@ -5,8 +5,8 @@ import { PrismaSchemaGenerator } from '../../prisma/schema-generator';
import path from 'path';

export async function generate(model: Model, options: PluginOptions, project: Project, outDir: string) {
const prismaGenerator = new PrismaSchemaGenerator();
await prismaGenerator.generate(model, {
const prismaGenerator = new PrismaSchemaGenerator(model);
await prismaGenerator.generate({
provider: '@internal',
schemaPath: options.schemaPath,
output: path.join(outDir, 'delegate.prisma'),
Comment on lines 5 to 12
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-13]

The use of path.join with options.schemaPath and outDir could potentially lead to path traversal vulnerabilities if user input is not properly sanitized or validated. Ensure that any user-supplied paths are rigorously checked to prevent unauthorized file system access.

- output: path.join(outDir, 'delegate.prisma'),
- overrideClientGenerationPath: path.join(outDir, '.delegate'),
+ output: sanitizePath(path.join(outDir, 'delegate.prisma')),
+ overrideClientGenerationPath: sanitizePath(path.join(outDir, '.delegate')),

Consider implementing a sanitizePath function that checks for and mitigates any path traversal patterns.

370 changes: 238 additions & 132 deletions packages/schema/src/plugins/enhancer/enhance/index.ts

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/schema/src/plugins/prisma/index.ts
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ export const name = 'Prisma';
export const description = 'Generating Prisma schema';

const run: PluginFunction = async (model, options, _dmmf, _globalOptions) => {
return new PrismaSchemaGenerator().generate(model, options);
return new PrismaSchemaGenerator(model).generate(options);
};

export default run;
45 changes: 35 additions & 10 deletions packages/schema/src/plugins/prisma/schema-generator.ts
Original file line number Diff line number Diff line change
@@ -17,6 +17,7 @@ import {
InvocationExpr,
isArrayExpr,
isDataModel,
isDataSource,
isInvocationExpr,
isLiteralExpr,
isNullExpr,
Comment on lines 17 to 23
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [707-707]

Potential security issue detected: user input is used in path.resolve within the getDefaultPrismaOutputFile function, which could lead to a path traversal vulnerability. Ensure to sanitize or validate user input before using it in path resolution functions.

- return path.resolve(path.dirname(pkgJsonPath), pkgJson.zenstack.prisma);
+ // Ensure pkgJson.zenstack.prisma is sanitized or validated before use
+ return path.resolve(path.dirname(pkgJsonPath), sanitizedInput);

@@ -79,6 +80,7 @@ import {

const MODEL_PASSTHROUGH_ATTR = '@@prisma.passthrough';
const FIELD_PASSTHROUGH_ATTR = '@prisma.passthrough';
const PROVIDERS_SUPPORTING_NAMED_CONSTRAINTS = ['postgresql', 'mysql', 'cockroachdb'];

/**
* Generates Prisma schema file
@@ -95,7 +97,9 @@ export class PrismaSchemaGenerator {

private mode: 'logical' | 'physical' = 'physical';

async generate(model: Model, options: PluginOptions) {
constructor(private readonly zmodel: Model) {}

async generate(options: PluginOptions) {
const warnings: string[] = [];
if (options.mode) {
this.mode = options.mode as 'logical' | 'physical';
@@ -110,7 +114,7 @@ export class PrismaSchemaGenerator {

const prisma = new PrismaModel();

for (const decl of model.declarations) {
for (const decl of this.zmodel.declarations) {
switch (decl.$type) {
case DataSource:
this.generateDataSource(prisma, decl as DataSource);
@@ -151,7 +155,7 @@ export class PrismaSchemaGenerator {
const generateClient = options.generateClient !== false;

if (generateClient) {
let generateCmd = `prisma generate --schema "${outFile}"`;
let generateCmd = `prisma generate --schema "${outFile}"${this.mode === 'logical' ? ' --no-engine' : ''}`;
if (typeof options.generateArgs === 'string') {
generateCmd += ` ${options.generateArgs}`;
}
@@ -452,17 +456,23 @@ export class PrismaSchemaGenerator {
new AttributeArgValue('FieldReference', new PrismaFieldReference(idField.name))
)
);
relationField.attributes.push(
new PrismaFieldAttribute('@relation', [
new PrismaAttributeArg('fields', args),
new PrismaAttributeArg('references', args),

const addedRel = new PrismaFieldAttribute('@relation', [
new PrismaAttributeArg('fields', args),
new PrismaAttributeArg('references', args),
]);

if (this.supportNamedConstraints) {
addedRel.args.push(
// generate a `map` argument for foreign key constraint disambiguation
new PrismaAttributeArg(
'map',
new PrismaAttributeArgValue('String', `${relationField.name}_fk`)
),
])
);
)
);
}

relationField.attributes.push(addedRel);
} else {
relationField.attributes.push(this.makeFieldAttribute(relAttr as DataModelFieldAttribute));
}
@@ -471,6 +481,21 @@ export class PrismaSchemaGenerator {
});
}

private get supportNamedConstraints() {
const ds = this.zmodel.declarations.find(isDataSource);
if (!ds) {
return false;
}

const provider = ds.fields.find((f) => f.name === 'provider');
if (!provider) {
return false;
}

const value = getStringLiteral(provider.value);
return value && PROVIDERS_SUPPORTING_NAMED_CONSTRAINTS.includes(value);
}

private isPrismaAttribute(attr: DataModelAttribute | DataModelFieldAttribute) {
if (!attr.decl.ref) {
return false;
26 changes: 13 additions & 13 deletions packages/schema/tests/generator/prisma-generator.test.ts
Original file line number Diff line number Diff line change
@@ -49,7 +49,7 @@ describe('Prisma generator test', () => {
}
`);

await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -90,7 +90,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -128,7 +128,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -162,7 +162,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -194,7 +194,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -230,7 +230,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -270,7 +270,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -321,7 +321,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -357,7 +357,7 @@ describe('Prisma generator test', () => {
}
`);
const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -380,7 +380,7 @@ describe('Prisma generator test', () => {
const model = await loadDocument(path.join(__dirname, './zmodel/schema.zmodel'));

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -430,7 +430,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -461,7 +461,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
@@ -496,7 +496,7 @@ describe('Prisma generator test', () => {
`);

const { name } = tmp.fileSync({ postfix: '.prisma' });
await new PrismaSchemaGenerator().generate(model, {
await new PrismaSchemaGenerator(model).generate({
name: 'Prisma',
provider: '@core/prisma',
schemaPath: 'schema.zmodel',
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { loadSchema } from '@zenstackhq/testtools';

describe('Regression tests', () => {
it('FK Constraint Ambiguity', async () => {
describe('Regression for issue 1058', () => {
it('test', async () => {
const schema = `
model User {
id String @id @default(cuid())
291 changes: 291 additions & 0 deletions tests/integration/tests/enhancements/with-delegate/issue-1064.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,291 @@
import { loadSchema } from '@zenstackhq/testtools';

describe('Regression for issue 1064', () => {
it('test', async () => {
const schema = `
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? // @db.Text
access_token String? // @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? // @db.Text
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@allow('all', auth().id == userId)
@@unique([provider, providerAccountId])
}
model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@allow('all', auth().id == userId)
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@allow('all', true)
@@unique([identifier, token])
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String
accounts Account[]
sessions Session[]
username String @unique @length(min: 4, max: 20)
about String? @length(max: 500)
location String? @length(max: 100)
role String @default("USER") @deny(operation: "update", auth().role != "ADMIN")
inserted_at DateTime @default(now())
updated_at DateTime @updatedAt() @default(now())
editComments EditComment[]
posts Post[]
rankings UserRanking[]
ratings UserRating[]
favorites UserFavorite[]
people Person[]
studios Studio[]
edits Edit[]
attachments Attachment[]
galleries Gallery[]
uploads UserUpload[]
maxUploadsPerDay Int @default(10)
maxEditsPerDay Int @default(10)
// everyone can signup, and user profile is also publicly readable
@@allow('create,read', true)
// only the user can update or delete their own profile
@@allow('update,delete', auth() == this)
}
abstract model UserEntityRelation {
entityId String?
entity Entity? @relation(fields: [entityId], references: [id], onUpdate: NoAction)
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction)
// everyone can read
@@allow('read', true)
@@allow('create,update,delete', auth().id == this.userId)
@@unique([userId,entityId])
}
model UserUpload {
timestamp DateTime @default(now())
key String @id
url String @unique
size Int
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction)
@@allow('create', auth().id == userId)
@@allow('all', auth().role == "ADMIN")
}
model Post {
id Int @id @default(autoincrement())
title String @length(max: 100)
body String @length(max: 1000)
createdAt DateTime @default(now())
authorId String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade, onUpdate: NoAction)
@@allow('read', true)
@@allow('create,update,delete', auth().id == authorId && auth().role == "ADMIN")
}
model Edit extends UserEntityRelation {
id String @id @default(cuid())
status String @default("PENDING") @allow('update', auth().role in ["ADMIN", "MODERATOR"])
type String @allow('update', false)
timestamp DateTime @default(now())
note String? @length(max: 300)
// for creates - createPayload & updates - data before diff is applied
data String?
// for updates
diff String?
comments EditComment[]
}
model EditComment {
id Int @id @default(autoincrement())
timestamp DateTime @default(now())
content String @length(max: 300)
editId String
edit Edit @relation(fields: [editId], references: [id], onUpdate: Cascade)
authorId String
author User @relation(fields: [authorId], references: [id], onUpdate: Cascade)
// everyone can read
@@allow('read', true)
@@allow('create,update,delete', auth().id == this.authorId || auth().role in ["ADMIN", "MODERATOR"])
}
model MetadataIdentifier {
id Int @default(autoincrement()) @id
identifier String
metadataSource String
MetadataSource MetadataSource @relation(fields: [metadataSource], references: [slug], onUpdate: Cascade)
entities Entity[]
@@unique([identifier, metadataSource])
@@allow('read', true)
@@allow('create,update,delete', auth().role in ["ADMIN", "MODERATOR"])
}
model MetadataSource {
slug String @id
name String @unique
identifierRegex String
desc String?
url String
icon String
identifiers MetadataIdentifier[]
@@allow('all', auth().role == "ADMIN")
}
model Attachment extends UserEntityRelation {
id String @id @default(cuid())
createdAt DateTime @default(now())
key String @unique
url String @unique
galleries Gallery[]
@@allow('delete', auth().role in ["ADMIN", "MODERATOR"])
}
model Entity {
id String @id @default(cuid())
name String
desc String?
attachments Attachment[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt @default(now())
type String
status String @default("PENDING") // PENDING ON INITIAL CREATION
verified Boolean @default(false)
edits Edit[]
userRankings UserRanking[]
userFavorites UserFavorite[]
userRatings UserRating[]
metaIdentifiers MetadataIdentifier[]
@@delegate(type)
@@allow('read', true)
@@allow('create', auth() != null)
@@allow('update', auth().role in ["ADMIN", "MODERATOR"])
@@allow('delete', auth().role == "ADMIN")
}
model Person extends Entity {
studios Studio[]
owners User[]
clips Clip[]
events Event[]
galleries Gallery[]
}
model Studio extends Entity {
people Person[]
owners User[]
clips Clip[]
events Event[]
galleries Gallery[]
}
model Clip extends Entity {
url String?
people Person[]
studios Studio[]
galleries Gallery[]
}
model UserRanking extends UserEntityRelation {
id String @id @default(cuid())
rank Int @gte(1) @lte(100)
note String? @length(max: 300)
}
model UserFavorite extends UserEntityRelation {
id String @id @default(cuid())
favoritedAt DateTime @default(now())
}
model UserRating extends UserEntityRelation {
id String @id @default(cuid())
rating Int @gte(1) @lte(5)
note String? @length(max: 500)
ratedAt DateTime @default(now())
}
model Event {
id Int @id @default(autoincrement())
name String @length(max: 100)
desc String? @length(max: 500)
location String? @length(max: 100)
date DateTime?
people Person[]
studios Studio[]
@@allow('read', true)
@@allow('create,update,delete', auth().role == "ADMIN")
}
model Gallery {
id String @id @default(cuid())
studioId String?
personId String?
timestamp DateTime @default(now())
authorId String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade, onUpdate: NoAction)
people Person[]
studios Studio[]
clips Clip[]
attachments Attachment[]
@@allow('read', true)
@@allow('create,update,delete', auth().id == this.authorId && auth().role == "ADMIN")
}
`;

await loadSchema(schema);
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { loadSchema } from '@zenstackhq/testtools';
import { PrismaErrorCode } from '@zenstackhq/runtime';
import { loadSchema, run } from '@zenstackhq/testtools';
import fs from 'fs';
import path from 'path';

describe('Polymorphism Test', () => {
const schema = `
@@ -1012,4 +1014,77 @@ model Gallery {
'groupBy with fields from base type is not supported yet'
);
});

it('typescript compilation', async () => {
const { projectDir } = await loadSchema(schema, { enhancements: ['delegate'] });
const src = `
import { PrismaClient } from '@prisma/client';
import { enhance } from '.zenstack/enhance';
const prisma = new PrismaClient();
async function main() {
await prisma.user.deleteMany();
const db = enhance(prisma);
const user1 = await db.user.create({ data: { } });
await db.ratedVideo.create({
data: {
owner: { connect: { id: user1.id } },
duration: 100,
url: 'abc',
rating: 10,
},
});
await db.image.create({
data: {
owner: { connect: { id: user1.id } },
format: 'webp',
},
});
const video = await db.video.findFirst({ include: { owner: true } });
console.log(video?.duration);
console.log(video?.viewCount);
const asset = await db.asset.findFirstOrThrow();
console.log(asset.assetType);
console.log(asset.viewCount);
if (asset.assetType === 'Video') {
console.log('Video: duration', asset.duration);
} else {
console.log('Image: format', asset.format);
}
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
`;

fs.writeFileSync(path.join(projectDir, 'script.ts'), src);
fs.writeFileSync(
path.join(projectDir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
outDir: 'dist',
strict: true,
lib: ['esnext'],
esModuleInterop: true,
},
})
);

run('npm i -D @types/node', undefined, projectDir);
run('npx tsc --noEmit --skipLibCheck script.ts', undefined, projectDir);
});
Comment on lines +1018 to +1089
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new test case for TypeScript compilation is well-structured and serves its purpose of validating the TypeScript compilation with PrismaClient operations. However, there are a few points to consider for improvement:

  1. Error Handling: The catch block in lines 1067-1071 properly logs errors and disconnects the Prisma client, which is good practice. However, it's important to ensure that any potential errors during the setup phase (e.g., writing files or installing dependencies) are also caught and handled appropriately.

  2. Dependency Installation: The command in line 1087 installs @types/node every time the test runs. Consider checking if this dependency could be included in the project's devDependencies to avoid repeated installations, which could slow down the test execution.

  3. Compiler Options: The TypeScript compiler options specified in lines 1078-1083 are focused on strict typing and modern JavaScript features. Ensure these settings align with the project's overall TypeScript configuration to maintain consistency.

  4. Script Execution: While the test verifies the TypeScript compilation (line 1088), it does not execute the compiled JavaScript. If the objective includes runtime validation, consider adding a step to execute the compiled output.

Overall, the test case is a valuable addition to the test suite, ensuring that the TypeScript code involving PrismaClient operations compiles correctly. Just ensure that the points mentioned above are considered to optimize the test execution and alignment with project standards.

- run('npm i -D @types/node', undefined, projectDir);
+ // Consider moving '@types/node' to project's devDependencies to avoid repeated installations

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
it('typescript compilation', async () => {
const { projectDir } = await loadSchema(schema, { enhancements: ['delegate'] });
const src = `
import { PrismaClient } from '@prisma/client';
import { enhance } from '.zenstack/enhance';
const prisma = new PrismaClient();
async function main() {
await prisma.user.deleteMany();
const db = enhance(prisma);
const user1 = await db.user.create({ data: { } });
await db.ratedVideo.create({
data: {
owner: { connect: { id: user1.id } },
duration: 100,
url: 'abc',
rating: 10,
},
});
await db.image.create({
data: {
owner: { connect: { id: user1.id } },
format: 'webp',
},
});
const video = await db.video.findFirst({ include: { owner: true } });
console.log(video?.duration);
console.log(video?.viewCount);
const asset = await db.asset.findFirstOrThrow();
console.log(asset.assetType);
console.log(asset.viewCount);
if (asset.assetType === 'Video') {
console.log('Video: duration', asset.duration);
} else {
console.log('Image: format', asset.format);
}
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
`;
fs.writeFileSync(path.join(projectDir, 'script.ts'), src);
fs.writeFileSync(
path.join(projectDir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
outDir: 'dist',
strict: true,
lib: ['esnext'],
esModuleInterop: true,
},
})
);
run('npm i -D @types/node', undefined, projectDir);
run('npx tsc --noEmit --skipLibCheck script.ts', undefined, projectDir);
});
it('typescript compilation', async () => {
const { projectDir } = await loadSchema(schema, { enhancements: ['delegate'] });
const src = `
import { PrismaClient } from '@prisma/client';
import { enhance } from '.zenstack/enhance';
const prisma = new PrismaClient();
async function main() {
await prisma.user.deleteMany();
const db = enhance(prisma);
const user1 = await db.user.create({ data: { } });
await db.ratedVideo.create({
data: {
owner: { connect: { id: user1.id } },
duration: 100,
url: 'abc',
rating: 10,
},
});
await db.image.create({
data: {
owner: { connect: { id: user1.id } },
format: 'webp',
},
});
const video = await db.video.findFirst({ include: { owner: true } });
console.log(video?.duration);
console.log(video?.viewCount);
const asset = await db.asset.findFirstOrThrow();
console.log(asset.assetType);
console.log(asset.viewCount);
if (asset.assetType === 'Video') {
console.log('Video: duration', asset.duration);
} else {
console.log('Image: format', asset.format);
}
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
`;
fs.writeFileSync(path.join(projectDir, 'script.ts'), src);
fs.writeFileSync(
path.join(projectDir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
outDir: 'dist',
strict: true,
lib: ['esnext'],
esModuleInterop: true,
},
})
);
// Consider moving '@types/node' to project's devDependencies to avoid repeated installations
run('npx tsc --noEmit --skipLibCheck script.ts', undefined, projectDir);
});

});