fix some lints

Many of these were fixed automatically with eslint --fix.

Some of them (e.g. adding return types to functions) were done manually.
This commit is contained in:
Johann150 2022-08-11 00:09:29 +02:00
parent 961fb0d2df
commit 6ce4b3fe2f
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1
76 changed files with 142 additions and 143 deletions

View file

@ -10,7 +10,7 @@ const urlRegexFull = /^https?:\/\/[\w\/:%#@$&?!()\[\]~.,=+\-]+$/;
export function fromHtml(html: string, hashtagNames?: string[]): string {
const dom = parse5.parseFragment(
// some AP servers like Pixelfed use br tags as well as newlines
html.replace(/<br\s?\/?>\r?\n/gi, '\n')
html.replace(/<br\s?\/?>\r?\n/gi, '\n'),
);
let text = '';

View file

@ -5,7 +5,7 @@ export type Acct = {
export function parse(acct: string): Acct {
const split = acct.split('@');
if (split[0].length == 0) {
if (split[0].length === 0) {
// there was an initial at
split.shift();
}

View file

@ -9,8 +9,8 @@ const retryDelay = 100;
const lock: (key: string, timeout?: number) => Promise<() => void>
= redisClient
? promisify(redisLock(redisClient, retryDelay))
: async () => () => { };
? promisify(redisLock(redisClient, retryDelay))
: async () => () => { };
/**
* Get AP Object lock

View file

@ -9,7 +9,7 @@ export async function verifyRecaptcha(secret: string, response: string) {
});
if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : '';
const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
throw new Error(`recaptcha-failed: ${errorCodes}`);
}
}
@ -20,7 +20,7 @@ export async function verifyHcaptcha(secret: string, response: string) {
});
if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : '';
const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
throw new Error(`hcaptcha-failed: ${errorCodes}`);
}
}

View file

@ -65,7 +65,7 @@ export async function checkHitAntenna(antenna: Antenna, note: (Note | Packed<'No
and.every(keyword =>
antenna.caseSensitive
? note.text!.includes(keyword)
: note.text!.toLowerCase().includes(keyword.toLowerCase())
: note.text!.toLowerCase().includes(keyword.toLowerCase()),
));
if (!matched) return false;
@ -83,7 +83,7 @@ export async function checkHitAntenna(antenna: Antenna, note: (Note | Packed<'No
and.every(keyword =>
antenna.caseSensitive
? note.text!.includes(keyword)
: note.text!.toLowerCase().includes(keyword.toLowerCase())
: note.text!.toLowerCase().includes(keyword.toLowerCase()),
));
if (matched) return false;

View file

@ -1,5 +1,5 @@
import { URL } from 'node:url';
import { toASCII } from 'punycode';
import { URL } from 'node:url';
import config from '@/config/index.js';
export function getFullApAccount(username: string, host: string | null): string {

View file

@ -18,7 +18,7 @@ export function createTempDir(): Promise<[string, () => void]> {
(e, path, cleanup) => {
if (e) return rej(e);
res([path, cleanup]);
}
},
);
});
}

View file

@ -1,15 +1,15 @@
import { Packed } from './schema.js';
export function isInstanceMuted(note: Packed<'Note'>, mutedInstances: Set<string>): boolean {
if (mutedInstances.has(note?.user?.host ?? '')) return true;
if (mutedInstances.has(note?.reply?.user?.host ?? '')) return true;
if (mutedInstances.has(note?.renote?.user?.host ?? '')) return true;
if (mutedInstances.has(note.user.host ?? '')) return true;
if (mutedInstances.has(note.reply?.user.host ?? '')) return true;
if (mutedInstances.has(note.renote?.user.host ?? '')) return true;
return false;
}
export function isUserFromMutedInstance(notif: Packed<'Notification'>, mutedInstances: Set<string>): boolean {
if (mutedInstances.has(notif?.user?.host ?? '')) return true;
if (mutedInstances.has(notif.user?.host ?? '')) return true;
return false;
}

View file

@ -1,7 +1,7 @@
export function isUserRelated(note: any, ids: Set<string>): boolean {
if (ids.has(note.userId)) return true; // note author is muted
if (note.mentions && note.mentions.some((user: string) => ids.has(user))) return true; // any of mentioned users are muted
if (note.reply && isUserRelated(note.reply, ids)) return true; // also check reply target
if (note.reply && isUserRelated(note.reply, ids)) return true; // also check reply target
if (note.renote && isUserRelated(note.renote, ids)) return true; // also check renote target
return false;
}

View file

@ -8,7 +8,7 @@ export function nyaize(text: string): string {
.replace(/(?<=every)one/gi, x => x === 'ONE' ? 'NYAN' : 'nyan')
// ko-KR
.replace(/[나-낳]/g, match => String.fromCharCode(
match.charCodeAt(0)! + '냐'.charCodeAt(0) - '나'.charCodeAt(0)
match.charCodeAt(0)! + '냐'.charCodeAt(0) - '나'.charCodeAt(0),
))
.replace(/(다$)|(다(?=\.))|(다(?= ))|(다(?=!))|(다(?=\?))/gm, '다냥')
.replace(/(야(?=\?))|(야$)|(야(?= ))/gm, '냥');

View file

@ -52,7 +52,7 @@ export class AbuseUserReport {
public resolved: boolean;
@Column('boolean', {
default: false
default: false,
})
public forwarded: boolean;

View file

@ -12,7 +12,7 @@ export const AppRepository = db.getRepository(App).extend({
detail?: boolean,
includeSecret?: boolean,
includeProfileImageIds?: boolean
}
},
): Promise<Packed<'App'>> {
const opts = Object.assign({
detail: false,

View file

@ -7,7 +7,7 @@ import { Apps } from '../index.js';
export const AuthSessionRepository = db.getRepository(AuthSession).extend({
async pack(
src: AuthSession['id'] | AuthSession,
me?: { id: User['id'] } | null | undefined
me?: { id: User['id'] } | null | undefined,
) {
const session = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });

View file

@ -8,7 +8,7 @@ import { Users } from '../index.js';
export const BlockingRepository = db.getRepository(Blocking).extend({
async pack(
src: Blocking['id'] | Blocking,
me?: { id: User['id'] } | null | undefined
me?: { id: User['id'] } | null | undefined,
): Promise<Packed<'Blocking'>> {
const blocking = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -24,7 +24,7 @@ export const BlockingRepository = db.getRepository(Blocking).extend({
packMany(
blockings: any[],
me: { id: User['id'] }
me: { id: User['id'] },
) {
return Promise.all(blockings.map(x => this.pack(x, me)));
},

View file

@ -9,7 +9,7 @@ export const DriveFolderRepository = db.getRepository(DriveFolder).extend({
src: DriveFolder['id'] | DriveFolder,
options?: {
detail: boolean
}
},
): Promise<Packed<'DriveFolder'>> {
const opts = Object.assign({
detail: false,

View file

@ -6,7 +6,7 @@ import { Users } from '../index.js';
export const FollowRequestRepository = db.getRepository(FollowRequest).extend({
async pack(
src: FollowRequest['id'] | FollowRequest,
me?: { id: User['id'] } | null | undefined
me?: { id: User['id'] } | null | undefined,
) {
const request = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });

View file

@ -76,7 +76,7 @@ export const FollowingRepository = db.getRepository(Following).extend({
opts?: {
populateFollowee?: boolean;
populateFollower?: boolean;
}
},
) {
return Promise.all(followings.map(x => this.pack(x, me, opts)));
},

View file

@ -5,7 +5,7 @@ import { GalleryPosts } from '../index.js';
export const GalleryLikeRepository = db.getRepository(GalleryLike).extend({
async pack(
src: GalleryLike['id'] | GalleryLike,
me?: any
me?: any,
) {
const like = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -17,7 +17,7 @@ export const GalleryLikeRepository = db.getRepository(GalleryLike).extend({
packMany(
likes: any[],
me: any
me: any,
) {
return Promise.all(likes.map(x => this.pack(x, me)));
},

View file

@ -11,7 +11,7 @@ export const MessagingMessageRepository = db.getRepository(MessagingMessage).ext
options?: {
populateRecipient?: boolean,
populateGroup?: boolean,
}
},
): Promise<Packed<'MessagingMessage'>> {
const opts = options || {
populateRecipient: true,

View file

@ -8,7 +8,7 @@ import { Users } from '../index.js';
export const MutingRepository = db.getRepository(Muting).extend({
async pack(
src: Muting['id'] | Muting,
me?: { id: User['id'] } | null | undefined
me?: { id: User['id'] } | null | undefined,
): Promise<Packed<'Muting'>> {
const muting = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -25,7 +25,7 @@ export const MutingRepository = db.getRepository(Muting).extend({
packMany(
mutings: any[],
me: { id: User['id'] }
me: { id: User['id'] },
) {
return Promise.all(mutings.map(x => this.pack(x, me)));
},

View file

@ -6,7 +6,7 @@ import { Notes } from '../index.js';
export const NoteFavoriteRepository = db.getRepository(NoteFavorite).extend({
async pack(
src: NoteFavorite['id'] | NoteFavorite,
me?: { id: User['id'] } | null | undefined
me?: { id: User['id'] } | null | undefined,
) {
const favorite = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -21,7 +21,7 @@ export const NoteFavoriteRepository = db.getRepository(NoteFavorite).extend({
packMany(
favorites: any[],
me: { id: User['id'] }
me: { id: User['id'] },
) {
return Promise.allSettled(favorites.map(x => this.pack(x, me)))
.then(promises => promises.flatMap(result => result.status === 'fulfilled' ? [result.value] : []));

View file

@ -42,5 +42,5 @@ export const NoteReactionRepository = db.getRepository(NoteReaction).extend({
// filter out rejected promises, only keep fulfilled values
return reactions.flatMap(result => result.status === 'fulfilled' ? [result.value] : []);
}
},
});

View file

@ -137,7 +137,7 @@ export const NoteRepository = db.getRepository(Note).extend({
_hint_?: {
myReactions: Map<Note['id'], NoteReaction | null>;
};
}
},
): Promise<Packed<'Note'>> {
const opts = Object.assign({
detail: true,
@ -163,7 +163,7 @@ export const NoteRepository = db.getRepository(Note).extend({
: await Channels.findOneBy({ id: note.channelId })
: null;
const reactionEmojiNames = Object.keys(note.reactions).filter(x => x?.startsWith(':')).map(x => decodeReaction(x).reaction).map(x => x.replace(/:/g, ''));
const reactionEmojiNames = Object.keys(note.reactions).filter(x => x.startsWith(':')).map(x => decodeReaction(x).reaction).map(x => x.replace(/:/g, ''));
const packed: Packed<'Note'> = await awaitAll({
id: note.id,
@ -233,7 +233,7 @@ export const NoteRepository = db.getRepository(Note).extend({
me?: { id: User['id'] } | null | undefined,
options?: {
detail?: boolean;
}
},
) {
if (notes.length === 0) return [];

View file

@ -16,7 +16,7 @@ export const NotificationRepository = db.getRepository(Notification).extend({
_hintForEachNotes_?: {
myReactions: Map<Note['id'], NoteReaction | null>;
};
}
},
): Promise<Packed<'Notification'>> {
const notification = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
const token = notification.appAccessTokenId ? await AccessTokens.findOneByOrFail({ id: notification.appAccessTokenId }) : null;
@ -85,7 +85,7 @@ export const NotificationRepository = db.getRepository(Notification).extend({
async packMany(
notifications: Notification[],
meId: User['id']
meId: User['id'],
) {
if (notifications.length === 0) return [];

View file

@ -6,7 +6,7 @@ import { Pages } from '../index.js';
export const PageLikeRepository = db.getRepository(PageLike).extend({
async pack(
src: PageLike['id'] | PageLike,
me?: { id: User['id'] } | null | undefined
me?: { id: User['id'] } | null | undefined,
) {
const like = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -18,7 +18,7 @@ export const PageLikeRepository = db.getRepository(PageLike).extend({
packMany(
likes: any[],
me: { id: User['id'] }
me: { id: User['id'] },
) {
return Promise.all(likes.map(x => this.pack(x, me)));
},

View file

@ -161,19 +161,19 @@ export const packedUserDetailedNotMeOnlySchema = {
type: 'array',
nullable: false, optional: false,
items: {
type: 'object',
nullable: false, optional: false,
properties: {
name: {
type: 'string',
nullable: false, optional: false,
},
value: {
type: 'string',
nullable: false, optional: false,
},
type: 'object',
nullable: false, optional: false,
properties: {
name: {
type: 'string',
nullable: false, optional: false,
},
maxLength: 4,
value: {
type: 'string',
nullable: false, optional: false,
},
},
maxLength: 4,
},
},
followersCount: {

View file

@ -10,7 +10,7 @@ export async function awaitAll<T>(obj: Promiseable<T>): Promise<T> {
const resolvedValues = await Promise.all(values.map(value =>
(!value || !value.constructor || value.constructor.name !== 'Object')
? value
: awaitAll(value)
: awaitAll(value),
));
for (let i = 0; i < keys.length; i++) {

View file

@ -6,12 +6,12 @@ const dateTimeIntervals = {
export function dateUTC(time: number[]): Date {
const d = time.length === 2 ? Date.UTC(time[0], time[1])
: time.length === 3 ? Date.UTC(time[0], time[1], time[2])
: time.length === 4 ? Date.UTC(time[0], time[1], time[2], time[3])
: time.length === 5 ? Date.UTC(time[0], time[1], time[2], time[3], time[4])
: time.length === 6 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5])
: time.length === 7 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5], time[6])
: null;
: time.length === 3 ? Date.UTC(time[0], time[1], time[2])
: time.length === 4 ? Date.UTC(time[0], time[1], time[2], time[3])
: time.length === 5 ? Date.UTC(time[0], time[1], time[2], time[3], time[4])
: time.length === 6 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5])
: time.length === 7 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5], time[6])
: null;
if (!d) throw new Error('wrong number of arguments');

View file

@ -21,9 +21,9 @@ import { ThinUser } from './types.js';
function renderError(e: Error): any {
return {
stack: e?.stack,
message: e?.message,
name: e?.name,
stack: e.stack,
message: e.message,
name: e.name,
};
}

View file

@ -21,7 +21,7 @@ export async function parseAudience(actor: CacheableRemoteUser, to?: ApObject, c
const limit = promiseLimit<CacheableUser | null>(2);
const mentionedUsers = (await Promise.all(
others.map(id => limit(() => resolvePerson(id, resolver).catch(() => null)))
others.map(id => limit(() => resolvePerson(id, resolver).catch(() => null))),
)).filter((x): x is CacheableUser => x != null);
if (toGroups.public.length > 0) {

View file

@ -35,7 +35,7 @@ export async function createImage(actor: CacheableRemoteUser, value: any): Promi
uri: image.url,
sensitive: image.sensitive,
isLink: !instance.cacheRemoteFiles,
comment: truncate(image.name, DB_MAX_IMAGE_COMMENT_LENGTH)
comment: truncate(image.name, DB_MAX_IMAGE_COMMENT_LENGTH),
});
if (file.isLink) {

View file

@ -196,7 +196,7 @@ export async function createNote(value: string | IObject, resolver?: Resolver =
// テキストのパース
let text: string | null = null;
if (note.source?.mediaType === 'text/x.misskeymarkdown' && typeof note.source?.content === 'string') {
if (note.source?.mediaType === 'text/x.misskeymarkdown' && typeof note.source.content === 'string') {
text = note.source.content;
} else if (typeof note._misskey_content !== 'undefined') {
text = note._misskey_content;

View file

@ -77,11 +77,11 @@ export async function renderPerson(user: ILocalUser) {
attachment: attachment.length ? attachment : undefined,
} as any;
if (profile?.birthday) {
if (profile.birthday) {
person['vcard:bday'] = profile.birthday;
}
if (profile?.location) {
if (profile.location) {
person['vcard:Address'] = profile.location;
}

View file

@ -123,7 +123,7 @@ export default class Resolver {
if (parsed.rest == null || !/^\w+$/.test(parsed.rest)) throw new Error('resolveLocal: invalid follow URI');
return Promise.all(
[parsed.id, parsed.rest].map(id => Users.findOneByOrFail({ id }))
[parsed.id, parsed.rest].map(id => Users.findOneByOrFail({ id })),
)
.then(([follower, followee]) => renderActivity(renderFollow(follower, followee, url)));
default:

View file

@ -18,7 +18,7 @@ import orderedCollection from '@/remote/activitypub/renderer/ordered-collection.
export async function readUserMessagingMessage(
userId: User['id'],
otherpartyId: User['id'],
messageIds: MessagingMessage['id'][]
messageIds: MessagingMessage['id'][],
) {
if (messageIds.length === 0) return;
@ -58,7 +58,7 @@ export async function readUserMessagingMessage(
recipientId: userId,
isRead: false,
},
take: 1
take: 1,
});
if (!count) {
@ -73,7 +73,7 @@ export async function readUserMessagingMessage(
export async function readGroupMessagingMessage(
userId: User['id'],
groupId: UserGroup['id'],
messageIds: MessagingMessage['id'][]
messageIds: MessagingMessage['id'][],
) {
if (messageIds.length === 0) return;

View file

@ -7,7 +7,7 @@ import { Notifications, Users } from '@/models/index.js';
export async function readNotification(
userId: User['id'],
notificationIds: Notification['id'][]
notificationIds: Notification['id'][],
) {
if (notificationIds.length === 0) return;
@ -27,7 +27,7 @@ export async function readNotification(
export async function readNotificationByQuery(
userId: User['id'],
query: Record<string, any>
query: Record<string, any>,
) {
const notificationIds = await Notifications.findBy({
...query,

View file

@ -64,7 +64,7 @@ export async function signup(opts: {
passphrase: undefined,
},
} as any, (err, publicKey, privateKey) =>
err ? rej(err) : res([publicKey, privateKey])
err ? rej(err) : res([publicKey, privateKey]),
));
let account!: User;

View file

@ -28,7 +28,7 @@ export const paramDef = {
// eslint-disable-next-line import/no-default-export
export default define(meta, paramDef, async () => {
const sizes = await
db.query(`
db.query(`
SELECT relname AS "table", reltuples as "count", pg_total_relation_size(C.oid) AS "size"
FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ('pg_catalog', 'information_schema')

View file

@ -25,7 +25,7 @@ export const paramDef = {
export default define(meta, paramDef, async (ps, me) => {
const [user, profile] = await Promise.all([
Users.findOneBy({ id: ps.userId }),
UserProfiles.findOneBy({ userId: ps.userId })
UserProfiles.findOneBy({ userId: ps.userId }),
]);
if (user == null || profile == null) {

View file

@ -58,7 +58,7 @@ export default define(meta, paramDef, async (ps, user) => {
}
const query = makePaginationQuery(Notes.createQueryBuilder('note'),
ps.sinceId, ps.untilId, ps.sinceDate, ps.untilDate)
ps.sinceId, ps.untilId, ps.sinceDate, ps.untilDate)
.innerJoin(AntennaNotes.metadata.targetName, 'antennaNote', 'antennaNote.noteId = note.id')
.innerJoinAndSelect('note.user', 'user')
.leftJoinAndSelect('user.avatar', 'avatar')

View file

@ -47,8 +47,8 @@ export const meta = {
type: 'object',
optional: false, nullable: false,
ref: 'UserDetailedNotMe',
}
}
},
},
},
{
type: 'object',
@ -62,9 +62,9 @@ export const meta = {
type: 'object',
optional: false, nullable: false,
ref: 'Note',
}
}
}
},
},
},
],
},
} as const;

View file

@ -47,7 +47,7 @@ export default define(meta, paramDef, async (ps, user) => {
DriveFiles.findOneBy({
id: fileId,
userId: user.id,
})
}),
))).filter((file): file is DriveFile => file != null);
if (files.length === 0) {

View file

@ -46,7 +46,7 @@ export default define(meta, paramDef, async (ps, user) => {
DriveFiles.findOneBy({
id: fileId,
userId: user.id,
})
}),
))).filter((file): file is DriveFile => file != null);
if (files.length === 0) {

View file

@ -127,7 +127,7 @@ export default define(meta, paramDef, async () => {
.andWhere('note.createdAt > :gt', { gt: new Date(now.getTime() - (interval * (i + 1))) })
.cache(60000) // 1 min
.getRawOne()
.then(x => parseInt(x.count, 10))
.then(x => parseInt(x.count, 10)),
)));
}
@ -140,7 +140,7 @@ export default define(meta, paramDef, async () => {
.andWhere('note.createdAt > :gt', { gt: new Date(now.getTime() - rangeA) })
.cache(60000 * 60) // 60 min
.getRawOne()
.then(x => parseInt(x.count, 10))
.then(x => parseInt(x.count, 10)),
));
const stats = hots.map((tag, i) => ({

View file

@ -27,7 +27,7 @@ export const meta = {
ref: 'GalleryPost',
},
},
}
},
},
} as const;

View file

@ -26,7 +26,7 @@ export const meta = {
ref: 'Page',
},
},
}
},
},
} as const;

View file

@ -57,7 +57,7 @@ export const meta = {
message: 'Invalid Regular Expression.',
code: 'INVALID_REGEXP',
id: '0d786918-10df-41cd-8f33-8dec7d9a89a5',
}
},
},
res: {
@ -77,7 +77,8 @@ export const paramDef = {
lang: { type: 'string', enum: [null, ...Object.keys(langmap)], nullable: true },
avatarId: { type: 'string', format: 'misskey:id', nullable: true },
bannerId: { type: 'string', format: 'misskey:id', nullable: true },
fields: { type: 'array',
fields: {
type: 'array',
minItems: 0,
maxItems: 16,
items: {

View file

@ -1,4 +1,4 @@
import { IsNull, MoreThan } from 'typeorm';
import { IsNull } from 'typeorm';
import config from '@/config/index.js';
import { fetchMeta } from '@/misc/fetch-meta.js';
import { Emojis, Users } from '@/models/index.js';

View file

@ -1,4 +1,3 @@
import { Brackets } from 'typeorm';
import { Notes } from '@/models/index.js';
import define from '../../define.js';
import { makePaginationQuery } from '../../common/make-pagination-query.js';

View file

@ -16,7 +16,7 @@ export class ApiError extends Error {
kind: 'server',
httpStatusCode: 500,
},
info?: any | null | undefined
info?: any | null | undefined,
) {
super(e.message);
this.message = e.message;

View file

@ -37,7 +37,7 @@ export function genOpenapiSpec() {
Bearer: {
type: 'http',
scheme: 'bearer',
}
},
},
},
};

View file

@ -55,6 +55,6 @@ export const schemas = {
},
...Object.fromEntries(
Object.entries(refs).map(([key, schema]) => [key, convertSchemaToOpenApiSchema(schema)])
Object.entries(refs).map(([key, schema]) => [key, convertSchemaToOpenApiSchema(schema)]),
),
};

View file

@ -172,7 +172,7 @@ export default async (ctx: Koa.Context) => {
body.credentialId
.replace(/-/g, '+')
.replace(/_/g, '/'),
'base64'
'base64',
).toString('hex'),
});

View file

@ -1,6 +1,6 @@
import * as http from 'node:http';
import { EventEmitter } from 'events';
import { ParsedUrlQuery } from 'querystring';
import * as http from 'node:http';
import * as websocket from 'websocket';
import { subscriber as redisClient } from '@/db/redis.js';
@ -8,13 +8,13 @@ import { Users } from '@/models/index.js';
import MainStreamConnection from './stream/index.js';
import authenticate from './authenticate.js';
export const initializeStreamingServer = (server: http.Server) => {
export const initializeStreamingServer = (server: http.Server): void => {
// Init websocket server
const ws = new websocket.server({
httpServer: server,
});
ws.on('request', async (request) => {
ws.on('request', async (request): Promise<void> => {
const q = request.resourceURL.query as ParsedUrlQuery;
const [user, app] = await authenticate(request.httpRequest.headers.authorization, q.i)

View file

@ -13,7 +13,7 @@ const nodeinfo2_0path = '/nodeinfo/2.0';
export const links = [{
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1',
href: config.url + nodeinfo2_1path
href: config.url + nodeinfo2_1path,
}, {
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
href: config.url + nodeinfo2_0path,

View file

@ -2,7 +2,7 @@ import Koa from 'koa';
import { fetchMeta } from '@/misc/fetch-meta.js';
import manifest from './manifest.json' assert { type: 'json' };
export const manifestHandler = async (ctx: Koa.Context) => {
export const manifestHandler = async (ctx: Koa.Context): Promise<void> => {
// TODO
//const res = structuredClone(manifest);
const res = JSON.parse(JSON.stringify(manifest));

View file

@ -8,7 +8,7 @@ import { getJson } from '@/misc/fetch.js';
const logger = new Logger('url-preview');
export const urlPreviewHandler = async (ctx: Koa.Context) => {
export const urlPreviewHandler = async (ctx: Koa.Context): Promise<void> => {
const url = ctx.query.url;
if (typeof url !== 'string') {
ctx.status = 400;

View file

@ -13,11 +13,11 @@ const router = new Router();
const XRD = (...x: { element: string, value?: string, attributes?: Record<string, string> }[]) =>
`<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">${x.map(({ element, value, attributes }) =>
`<${
Object.entries(typeof attributes === 'object' && attributes || {}).reduce((a, [k, v]) => `${a} ${k}="${escapeAttribute(v)}"`, element)
}${
typeof value === 'string' ? `>${escapeValue(value)}</${element}` : '/'
}>`).reduce((a, c) => a + c, '')}</XRD>`;
`<${
Object.entries(typeof attributes === 'object' && attributes || {}).reduce((a, [k, v]) => `${a} ${k}="${escapeAttribute(v)}"`, element)
}${
typeof value === 'string' ? `>${escapeValue(value)}</${element}` : '/'
}>`).reduce((a, c) => a + c, '')}</XRD>`;
const allPath = '/.well-known/(.*)';
const webFingerPath = '/.well-known/webfinger';

View file

@ -9,7 +9,7 @@ import { sendEmailNotification } from './send-email-notification.js';
export async function createNotification(
notifieeId: User['id'],
type: Notification['type'],
data: Partial<Notification>
data: Partial<Notification>,
) {
if (data.notifierId && (notifieeId === data.notifierId)) {
return null;

View file

@ -10,7 +10,7 @@ import { UsedUsername } from '@/models/entities/used-username.js';
import { db } from '@/db/postgre.js';
import generateNativeUserToken from '../server/api/common/generate-native-user-token.js';
export async function createSystemUser(username: string) {
export async function createSystemUser(username: string): Promise<User> {
const password = uuid();
// Generate hash of password

View file

@ -8,7 +8,7 @@ export async function deleteAccount(user: {
host: string | null;
}): Promise<void> {
// 物理削除する前にDelete activityを送信する
await doPostSuspend(user).catch(e => {});
await doPostSuspend(user).catch(() => {});
createDeleteAccountJob(user, {
soft: false,

View file

@ -279,7 +279,7 @@ async function upload(key: string, stream: fs.ReadStream | Buffer, _type: string
const s3 = getS3(meta);
const upload = s3.upload(params, {
partSize: s3.endpoint?.hostname === 'storage.googleapis.com' ? 500 * 1024 * 1024 : 8 * 1024 * 1024,
partSize: s3.endpoint.hostname === 'storage.googleapis.com' ? 500 * 1024 * 1024 : 8 * 1024 * 1024,
});
const result = await upload.promise();
@ -345,7 +345,7 @@ export async function addFile({
isLink = false,
url = null,
uri = null,
sensitive = null
sensitive = null,
}: AddFileArgs): Promise<DriveFile> {
const info = await getFileInfo(path);
logger.info(`${JSON.stringify(info)}`);
@ -431,10 +431,9 @@ export async function addFile({
file.blurhash = info.blurhash || null;
file.isLink = isLink;
file.isSensitive = user
? Users.isLocalUser(user) && profile!.alwaysMarkNsfw ? true :
(sensitive !== null && sensitive !== undefined)
? sensitive
: false
? Users.isLocalUser(user) && profile!.alwaysMarkNsfw
? true
: sensitive ?? false
: false;
if (url !== null) {

View file

@ -38,11 +38,11 @@ export async function convertSharpToJpeg(sharp: sharp.Sharp, width: number, heig
* Convert to WebP
* with resize, remove metadata, resolve orientation, stop animation
*/
export async function convertToWebp(path: string, width: number, height: number, quality: number = 85): Promise<IImage> {
export async function convertToWebp(path: string, width: number, height: number, quality = 85): Promise<IImage> {
return convertSharpToWebp(await sharp(path), width, height, quality);
}
export async function convertSharpToWebp(sharp: sharp.Sharp, width: number, height: number, quality: number = 85): Promise<IImage> {
export async function convertSharpToWebp(sharp: sharp.Sharp, width: number, height: number, quality = 85): Promise<IImage> {
const data = await sharp
.resize(width, height, {
fit: 'inside',

View file

@ -235,7 +235,7 @@ async function getSiteName(info: NodeInfo | null, doc: DOMWindow['document'] | n
}
if (manifest) {
return manifest?.name || manifest?.short_name;
return manifest.name || manifest.short_name;
}
return null;
@ -261,7 +261,7 @@ async function getDescription(info: NodeInfo | null, doc: DOMWindow['document']
}
if (manifest) {
return manifest?.name || manifest?.short_name;
return manifest.name || manifest.short_name;
}
return null;

View file

@ -7,12 +7,12 @@ import renderDelete from '@/remote/activitypub/renderer/delete.js';
import renderTombstone from '@/remote/activitypub/renderer/tombstone.js';
import { deliver } from '@/queue/index.js';
export async function deleteMessage(message: MessagingMessage) {
export async function deleteMessage(message: MessagingMessage): Promise<void> {
await MessagingMessages.delete(message.id);
postDeleteMessage(message);
await postDeleteMessage(message);
}
async function postDeleteMessage(message: MessagingMessage) {
async function postDeleteMessage(message: MessagingMessage): Promise<void> {
if (message.recipientId) {
const user = await Users.findOneByOrFail({ id: message.userId });
const recipient = await Users.findOneByOrFail({ id: message.recipientId });

View file

@ -679,12 +679,12 @@ async function extractMentionedUsers(user: { host: User['host']; }, tokens: mfm.
const mentions = extractMentions(tokens);
let mentionedUsers = (await Promise.all(mentions.map(m =>
resolveUser(m.username, m.host || user.host).catch(() => null)
resolveUser(m.username, m.host || user.host).catch(() => null),
))).filter(x => x != null) as User[];
// Drop duplicate users
mentionedUsers = mentionedUsers.filter((u, i, self) =>
i === self.findIndex(u2 => u.id === u2.id)
i === self.findIndex(u2 => u.id === u2.id),
);
return mentionedUsers;

View file

@ -21,7 +21,7 @@ import { deliverToRelays } from '../relay.js';
* @param user 稿
* @param note 稿
*/
export default async function(user: { id: User['id']; uri: User['uri']; host: User['host']; }, note: Note, quiet = false) {
export default async function(user: { id: User['id']; uri: User['uri']; host: User['host']; }, note: Note, quiet = false): Promise<void> {
const deletedAt = new Date();
// この投稿を除く指定したユーザーによる指定したノートのリノートが存在しないとき
@ -83,7 +83,7 @@ export default async function(user: { id: User['id']; uri: User['uri']; host: Us
});
}
async function findCascadingNotes(note: Note) {
async function findCascadingNotes(note: Note): Promise<Note[]> {
const cascadingNotes: Note[] = [];
const recursive = async (noteId: string) => {
@ -105,7 +105,7 @@ async function findCascadingNotes(note: Note) {
return cascadingNotes.filter(note => note.userHost === null); // filter out non-local users
}
async function getMentionedRemoteUsers(note: Note) {
async function getMentionedRemoteUsers(note: Note): Promise<IRemoteUser[]> {
const where = [] as any[];
// mention / reply / dm

View file

@ -6,7 +6,7 @@ import { Note } from '@/models/entities/note.js';
import { deliverToFollowers } from '@/remote/activitypub/deliver-manager.js';
import { deliverToRelays } from '../../relay.js';
export async function deliverQuestionUpdate(noteId: Note['id']) {
export async function deliverQuestionUpdate(noteId: Note['id']): Promise<void> {
const note = await Notes.findOneBy({ id: noteId });
if (note == null) throw new Error('note not found');

View file

@ -18,7 +18,7 @@ export default async function(
info?: {
following: Set<User['id']>;
followingChannels: Set<Channel['id']>;
}
},
) {
const following = info?.following ? info.following : new Set<string>((await Followings.find({
where: {

View file

@ -8,7 +8,7 @@ export async function insertNoteUnread(userId: User['id'], note: Note, params: {
// NOTE: isSpecifiedがtrueならisMentionedは必ずfalse
isSpecified: boolean;
isMentioned: boolean;
}) {
}): Promise<void> {
//#region ミュートしているなら無視
// TODO: 現在の仕様ではChannelにミュートは適用されないのでよしなにケアする
const mute = await Mutings.findBy({

View file

@ -29,7 +29,7 @@ function truncateNotification(notification: Packed<'Notification'>): any {
reply: undefined,
renote: undefined,
user: undefined as any, // 通知を受け取ったユーザーである場合が多いのでこれも捨てる
}
},
};
}

View file

@ -5,7 +5,7 @@ import Logger from './logger.js';
export const logger = new Logger('email');
export async function sendEmail(to: string, subject: string, html: string, text: string) {
export async function sendEmail(to: string, subject: string, html: string, text: string): Promise<void> {
const meta = await fetchMeta(true);
const iconUrl = `${config.url}/static-assets/mi-white.png`;

View file

@ -7,7 +7,7 @@ import { User } from '@/models/entities/user.js';
import { Users, Followings } from '@/models/index.js';
import { publishInternalEvent } from '@/services/stream.js';
export async function doPostSuspend(user: { id: User['id']; host: User['host'] }) {
export async function doPostSuspend(user: { id: User['id']; host: User['host'] }): Promise<void> {
publishInternalEvent('userChangeSuspendedState', { id: user.id, isSuspended: true });
if (Users.isLocalUser(user)) {

View file

@ -5,13 +5,13 @@ import { genId } from '@/misc/gen-id.js';
import { Hashtag } from '@/models/entities/hashtag.js';
import { normalizeForSearch } from '@/misc/normalize-for-search.js';
export async function updateHashtags(user: { id: User['id']; host: User['host']; }, tags: string[]) {
export async function updateHashtags(user: { id: User['id']; host: User['host']; }, tags: string[]): Promise<void> {
for (const tag of tags) {
await updateHashtag(user, tag);
}
}
export async function updateUsertags(user: User, tags: string[]) {
export async function updateUsertags(user: User, tags: string[]): Promise<void> {
for (const tag of tags) {
await updateHashtag(user, tag, true, true);
}
@ -21,7 +21,7 @@ export async function updateUsertags(user: User, tags: string[]) {
}
}
export async function updateHashtag(user: { id: User['id']; host: User['host']; }, _tag: string, isUserAttached = false, inc = true) {
export async function updateHashtag(user: { id: User['id']; host: User['host']; }, _tag: string, isUserAttached = false, inc = true): Promise<void> {
const tag = normalizeForSearch(_tag);
const index = await Hashtags.findOneBy({ name: tag });

View file

@ -7,7 +7,7 @@ import { genId } from '@/misc/gen-id.js';
import { fetchProxyAccount } from '@/misc/fetch-proxy-account.js';
import createFollowing from '../following/create.js';
export async function pushUserToUserList(target: User, list: UserList) {
export async function pushUserToUserList(target: User, list: UserList): Promise<void> {
await UserListJoinings.insert({
id: genId(),
createdAt: new Date(),

View file

@ -24,11 +24,11 @@ export async function validateEmailForAccount(emailAddress: string): Promise<{
return {
available,
reason: available ? null :
exist !== 0 ? 'used' :
validated.reason === 'regex' ? 'format' :
validated.reason === 'disposable' ? 'disposable' :
validated.reason === 'mx' ? 'mx' :
validated.reason === 'smtp' ? 'smtp' :
null,
exist !== 0 ? 'used' :
validated.reason === 'regex' ? 'format' :
validated.reason === 'disposable' ? 'disposable' :
validated.reason === 'mx' ? 'mx' :
validated.reason === 'smtp' ? 'smtp' :
null,
};
}