Skip to content

Commit

Permalink
chore: eslint with strict type imports
Browse files Browse the repository at this point in the history
  • Loading branch information
sylv committed Feb 12, 2024
1 parent f849e80 commit ee0c6ff
Show file tree
Hide file tree
Showing 74 changed files with 1,061 additions and 4,560 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"npm.scriptExplorerExclude": ["^((?!watch|generate:watch).)*$"],
"eslint.workingDirectories": [
{
"pattern": "./{packages,apps}/*"
"pattern": "./packages/*"
}
],
"files.associations": {
Expand Down
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ RUN npm i -g pnpm

WORKDIR /usr/src/micro

COPY patches patches
COPY pnpm-lock.yaml pnpm-workspace.yaml ./
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
pnpm fetch
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
},
"devDependencies": {
"syncpack": "^12.3.0",
"turbo": "1.11.3",
"turbo": "1.12.3",
"typescript": "^5.3.3"
},
"packageManager": "pnpm@7.0.0"
Expand Down
2 changes: 2 additions & 0 deletions packages/api/.eslintrc.js → packages/api/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ module.exports = {
},
rules: {
'unicorn/no-abusive-eslint-disable': 'off',
'unicorn/filename-case': 'off',
'import/no-default-export': 'off',
},
};
30 changes: 15 additions & 15 deletions packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,24 @@
"@mikro-orm/migrations": "^5.9.7",
"@mikro-orm/nestjs": "^5.2.3",
"@mikro-orm/postgresql": "^5.9.7",
"@nestjs/common": "^10.3.0",
"@nestjs/core": "^10.3.0",
"@nestjs/graphql": "^12.0.11",
"@nestjs/common": "^10.3.2",
"@nestjs/core": "^10.3.2",
"@nestjs/graphql": "^12.1.1",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mercurius": "^12.0.11",
"@nestjs/mercurius": "^12.1.1",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-fastify": "^10.3.0",
"@nestjs/schedule": "^4.0.0",
"@nestjs/platform-fastify": "^10.3.2",
"@nestjs/schedule": "^4.0.1",
"@ryanke/venera": "^1.0.5",
"bcryptjs": "^2.4.3",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"fastify": "^4.25.2",
"fastify": "^4.26.0",
"fluent-ffmpeg": "^2.1.2",
"graphql": "^16.8.1",
"mercurius": "^13.3.3",
"mime-types": "^2.1.35",
"nodemailer": "^6.9.8",
"nodemailer": "^6.9.9",
"otplib": "^12.0.1",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
Expand All @@ -55,15 +55,15 @@
"devDependencies": {
"@atlasbot/configs": "^10.5.15",
"@mikro-orm/cli": "^5.9.7",
"@swc/core": "^1.3.102",
"@swc/core": "^1.4.0",
"@types/bcryptjs": "^2.4.6",
"@types/bytes": "^3.1.4",
"@types/dedent": "^0.7.2",
"@types/fluent-ffmpeg": "^2.1.24",
"@types/luxon": "^3.4.0",
"@types/mime-types": "^2.1.4",
"@types/ms": "^0.7.34",
"@types/node": "^20.10.6",
"@types/node": "^20.11.17",
"@types/nodemailer": "^6.4.14",
"@types/passport-jwt": "^4.0.0",
"@types/utf-8-validate": "^5.0.2",
Expand All @@ -72,21 +72,21 @@
"content-range": "^2.0.2",
"dedent": "^1.5.1",
"escape-string-regexp": "^5.0.0",
"file-type": "^18.7.0",
"file-type": "^19.0.0",
"handlebars": "^4.7.8",
"istextorbinary": "^9.5.0",
"luxon": "^3.4.4",
"ms": "^3.0.0-canary.1",
"nanoid": "^5.0.4",
"nanoid": "^5.0.5",
"normalize-url": "^8.0.0",
"pretty-bytes": "^6.1.1",
"reflect-metadata": "^0.2.1",
"ts-node": "^10.9.2",
"tsup": "^8.0.1",
"tsup": "^8.0.2",
"typescript": "^5.3.3",
"vitest": "^1.1.3",
"vitest": "^1.2.2",
"zod": "^3.22.4",
"zod-validation-error": "^2.1.0"
"zod-validation-error": "^3.0.0"
},
"mikro-orm": {
"useTsNode": true,
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/classes/ExifTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { Transform } from 'stream';
export class ExifTransformer extends Transform {
private static readonly app1Marker = Buffer.from('ffe1', 'hex');
private static readonly exifMarker = Buffer.from('457869660000', 'hex'); // Exif\0\0
private static readonly xmpMarker = Buffer.from('http://ns.adobe.com/xap', 'utf-8');
private static readonly flirMarker = Buffer.from('FLIR', 'utf-8');
private static readonly xmpMarker = Buffer.from('http://ns.adobe.com/xap', 'utf8');
private static readonly flirMarker = Buffer.from('FLIR', 'utf8');
private static readonly maxMarkerLength = Math.max(
ExifTransformer.exifMarker.length,
ExifTransformer.xmpMarker.length,
Expand Down Expand Up @@ -48,7 +48,7 @@ export class ExifTransformer extends Transform {
// no app1 in the current pendingChunk
if (app1Start === -1) {
// if last byte is ff, wait for more
if (!atEnd && pendingChunk[pendingChunk.length - 1] === ExifTransformer.app1Marker[0]) {
if (!atEnd && pendingChunk.at(-1) === ExifTransformer.app1Marker[0]) {
if (chunk) this.pending.push(chunk);
return;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ const enhanceHost = (host: z.infer<typeof schema>['hosts'][0]) => {
};

export const config = result.data as Omit<z.infer<typeof schema>, 'hosts'>;
export const hosts = result.data.hosts.map(enhanceHost);
export const hosts = result.data.hosts.map((host) => enhanceHost(host));
export const rootHost = hosts[0];

if (rootHost.isWildcard) {
Expand All @@ -92,9 +92,9 @@ if (disallowed.has(config.secret.toLowerCase())) {
const token = randomBytes(24).toString('hex');
throw new Error(
dedent`
${c.redBright.bold('Do not use the default secret.')}
Please generate a random, secure secret or you risk anyone being able to impersonate you.
If you're lazy, here is a random secret: ${c.underline(token)}
${c.redBright.bold('Do not use the default secret.')}
Please generate a random, secure secret or you risk anyone being able to impersonate you.
If you're lazy, here is a random secret: ${c.underline(token)}
`,
);
}
2 changes: 1 addition & 1 deletion packages/api/src/helpers/expand-mime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const expandMime = (input: string | string[]) => {
if (!Array.isArray(input)) input = [input];
const output: string[] = [];
for (const mimeType of input) {
const alias = MIME_MAP.get(mimeType.replace(WILDCARD_REGEX, ''));
const alias = MIME_MAP.get(mimeType.replaceAll(WILDCARD_REGEX, ''));
if (alias) {
output.push(...alias);
continue;
Expand Down
5 changes: 2 additions & 3 deletions packages/api/src/helpers/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ export function parseCursor(cursor: string) {

export function paginate<T>(items: T[], total: number, offset: number): Paginated<T> {
const edges: Edge<T>[] = [];
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
const item = items[itemIndex];
for (const [itemIndex, item] of items.entries()) {
const cursor = createCursor(offset + itemIndex);
edges.push({
cursor: cursor,
Expand All @@ -31,7 +30,7 @@ export function paginate<T>(items: T[], total: number, offset: number): Paginate
edges: edges,
totalCount: total,
pageInfo: {
endCursor: edges[0] ? edges[edges.length - 1].cursor : undefined,
endCursor: edges[0] ? edges.at(-1)!.cursor : undefined,
startCursor: edges[0] ? edges[0].cursor : undefined,
hasPreviousPage: offset > 0,
hasNextPage: offset + items.length < total,
Expand Down
5 changes: 2 additions & 3 deletions packages/api/src/helpers/resource.entity-base.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable sonarjs/no-duplicate-string */
import type { IdentifiedReference } from '@mikro-orm/core';
import type { Ref } from '@mikro-orm/core';
import { BeforeCreate, Entity, Property, type EventArgs } from '@mikro-orm/core';
import { ObjectType } from '@nestjs/graphql';
import type { FastifyRequest } from 'fastify';
Expand All @@ -14,7 +13,7 @@ export abstract class Resource {
@Property({ nullable: true })
hostname?: string;

abstract owner?: IdentifiedReference<User>;
abstract owner?: Ref<User>;
abstract getPaths(): ResourceLocations;

getUrls() {
Expand Down
98 changes: 45 additions & 53 deletions packages/api/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,64 +11,56 @@ import { migrate } from './migrate.js';
import { AppModule } from './modules/app.module.js';
import { HostGuard } from './modules/host/host.guard.js';

async function bootstrap() {
await migrate();
await migrate();

const logger = new Logger('bootstrap');
const server = fastify({
trustProxy: process.env.TRUST_PROXY === 'true',
maxParamLength: 500,
bodyLimit: config.uploadLimit,
});

const adapter = new FastifyAdapter(server as any);
const app = await NestFactory.create<NestFastifyApplication>(AppModule, adapter);
app.useGlobalGuards(new HostGuard());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
exceptionFactory(errors) {
// without this, nestjs won't include validation errors in the graphql response,
// just a blank bad request error, which is just a little confusing. thanks nestjs!
const formattedErrors = errors.map((error) => {
if (error.constraints) {
const constraints = Object.values(error.constraints);
if (constraints[0]) return constraints.join(', ');
}
const logger = new Logger('bootstrap');
const server = fastify({
trustProxy: process.env.TRUST_PROXY === 'true',
maxParamLength: 500,
bodyLimit: config.uploadLimit,
});

return error.toString();
});
const adapter = new FastifyAdapter(server as any);
const app = await NestFactory.create<NestFastifyApplication>(AppModule, adapter);
app.useGlobalGuards(new HostGuard());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
exceptionFactory(errors) {
// without this, nestjs won't include validation errors in the graphql response,
// just a blank bad request error, which is just a little confusing. thanks nestjs!
const formattedErrors = errors.map((error) => {
if (error.constraints) {
const constraints = Object.values(error.constraints);
if (constraints[0]) return constraints.join(', ');
}

return new BadRequestException(formattedErrors.join('\n'));
},
transformOptions: {
enableImplicitConversion: true,
},
})
);
return error.toString();
});

await app.register(fastifyCookie as any);
await app.register(fastifyHelmet.default as any);
await app.register(fastifyMultipart.default as any, {
limits: {
fieldNameSize: 100,
fieldSize: 100,
fields: 0,
files: 1,
headerPairs: 20,
return new BadRequestException(formattedErrors.join('\n'));
},
});
transformOptions: {
enableImplicitConversion: true,
},
}),
);

await app.listen(8080, '0.0.0.0', (error, address) => {
if (error) throw error;
logger.log(`Listening at ${address}`);
});
}
await app.register(fastifyCookie as any);
await app.register(fastifyHelmet.default as any);
await app.register(fastifyMultipart.default as any, {
limits: {
fieldNameSize: 100,
fieldSize: 100,
fields: 0,
files: 1,
headerPairs: 20,
},
});

// top-level await is not supported by ncc
bootstrap().catch((error) => {
console.error(error);
process.exit(1);
await app.listen(8080, '0.0.0.0', (error, address) => {
if (error) throw error;
logger.log(`Listening at ${address}`);
});
4 changes: 2 additions & 2 deletions packages/api/src/modules/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import type { FastifyRequest } from 'fastify';
import { config, hosts, rootHost } from '../config.js';
import { UserId } from './auth/auth.decorators.js';
import { OptionalJWTAuthGuard } from './auth/guards/optional-jwt.guard.js';
import { UserService } from './user/user.service.js';
import { type FastifyRequest } from 'fastify';

@Controller()
export class AppController {
Expand All @@ -23,7 +23,7 @@ export class AppController {
return {
inquiries: config.inquiries,
uploadLimit: config.uploadLimit,
allowTypes: config.allowTypes ? [...config.allowTypes?.values()] : undefined,
allowTypes: config.allowTypes ? [...config.allowTypes.values()] : undefined,
email: !!config.email,
rootHost: {
url: rootHost.url,
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/modules/app.resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class AppResolver {
return {
inquiriesEmail: config.inquiries,
uploadLimit: config.uploadLimit,
allowTypes: config.allowTypes ? [...config.allowTypes?.values()] : [],
allowTypes: config.allowTypes ? [...config.allowTypes.values()] : [],
requireEmails: !!config.email,
rootHost: this.filterHost(rootHost),
currentHost: this.filterHost(currentHost),
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/modules/file/file.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
Res,
UseGuards,
} from '@nestjs/common';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { type FastifyReply, type FastifyRequest } from 'fastify';
import { rootHost } from '../../config.js';
import { UserId } from '../auth/auth.decorators.js';
import { JWTAuthGuard } from '../auth/guards/jwt.guard.js';
Expand Down
7 changes: 6 additions & 1 deletion packages/api/src/modules/file/file.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,13 @@ export class File extends Resource {
}

getDisplayName() {
if (this.name) return this.name;
const extension = this.getExtension();
return this.name ? this.name : extension ? `${this.id}.${extension}` : this.id;
if (extension) {
return `${this.id}.${extension}`;
}

return this.id;
}

getPaths() {
Expand Down
3 changes: 2 additions & 1 deletion packages/api/src/modules/file/file.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ export class FileService implements OnApplicationBootstrap {
uploadStream = uploadStream.pipe(transformer).pipe(new PassThrough());
break;
}
default:
default: {
throw new Error(`Unknown or unsupported conversion ${fromGroup} to ${toGroup}`);
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/modules/link/link.controller.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityRepository } from '@mikro-orm/postgresql';
import { Controller, Get, Param, Request, Res } from '@nestjs/common';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { type FastifyReply, type FastifyRequest } from 'fastify';
import { Link } from './link.entity.js';
import { LinkService } from './link.service.js';

@Controller()
export class LinkController {
constructor(
@InjectRepository(Link) private readonly linkRepo: EntityRepository<Link>,
private readonly linkService: LinkService
private readonly linkService: LinkService,
) {}

@Get('link/:id')
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/modules/paste/paste.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Controller, Get, Param, Req } from '@nestjs/common';
import type { FastifyRequest } from 'fastify';
import { type FastifyRequest } from 'fastify';
import { PasteService } from './paste.service.js';

@Controller('paste')
Expand Down
Loading

0 comments on commit ee0c6ff

Please sign in to comment.