diff --git a/packages/authorization/src/constants.ts b/packages/authorization/src/constants.ts index 69b89ed6c..85689260b 100644 --- a/packages/authorization/src/constants.ts +++ b/packages/authorization/src/constants.ts @@ -6,7 +6,8 @@ export const CALLBACK_BLANK = 'https://oauth.vk.com/blank.html'; /** * User-Agent for standalone auth */ -export const DESKTOP_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'; +export const DESKTOP_USER_AGENT = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'; /** * Auth error codes @@ -20,7 +21,7 @@ export enum AuthErrorCode { USERNAME_OR_PASSWORD_IS_INCORRECT = 'USERNAME_OR_PASSWORD_IS_INCORRECT', TOO_MUCH_TRIES = 'TOO_MUCH_TRIES', WRONG_OTP = 'WRONG_OTP', - OTP_FORMAT_IS_INCORRECT = 'OTP_FORMAT_IS_INCORRECT' + OTP_FORMAT_IS_INCORRECT = 'OTP_FORMAT_IS_INCORRECT', } /** diff --git a/packages/authorization/src/errors/authorization.ts b/packages/authorization/src/errors/authorization.ts index 892abbafd..4d0467ef1 100644 --- a/packages/authorization/src/errors/authorization.ts +++ b/packages/authorization/src/errors/authorization.ts @@ -23,8 +23,6 @@ export class AuthorizationError extends VKError { public constructor({ message, code, pageHtml }: IAuthorizationErrorOptions) { super({ message, code }); - this.pageHtml = isDebug - ? pageHtml - : undefined; + this.pageHtml = isDebug ? pageHtml : undefined; } } diff --git a/packages/authorization/src/fetch-cookie.ts b/packages/authorization/src/fetch-cookie.ts index 3a3a200c1..1fcf07f10 100644 --- a/packages/authorization/src/fetch-cookie.ts +++ b/packages/authorization/src/fetch-cookie.ts @@ -1,27 +1,13 @@ import createDebug from 'debug'; import { CookieJar } from 'tough-cookie'; -import { - fetch, - - RequestInfo, - RequestInit, - Response, -} from './fetch'; +import { RequestInfo, RequestInit, Response, fetch } from './fetch'; export type Headers = Record; -export type FetchWrapper = ( - url: RequestInfo, - options?: RequestInit -) => Promise; +export type FetchWrapper = (url: RequestInfo, options?: RequestInit) => Promise; -export { - CookieJar, - RequestInfo, - RequestInit, - Response, -}; +export { CookieJar, RequestInfo, RequestInit, Response }; const debug = createDebug('vk-io:util:fetch-cookie'); @@ -34,8 +20,7 @@ const findUserAgent = (headers?: Headers): string | undefined => { return undefined; } - const key = Object.keys(headers) - .find((header): boolean => userAgentRe.test(header)); + const key = Object.keys(headers).find((header): boolean => userAgentRe.test(header)); if (!key) { return undefined; @@ -44,11 +29,8 @@ const findUserAgent = (headers?: Headers): string | undefined => { return headers[key]; }; -export const fetchCookieDecorator = (jar = new CookieJar()): FetchWrapper => ( - async function fetchCookie( - url: RequestInfo, - options: RequestInit = {}, - ): Promise { +export const fetchCookieDecorator = (jar = new CookieJar()): FetchWrapper => + async function fetchCookie(url: RequestInfo, options: RequestInit = {}): Promise { const previousCookie = await jar.getCookieString(String(url)); const { headers = {} } = options as { @@ -73,21 +55,15 @@ export const fetchCookieDecorator = (jar = new CookieJar()): FetchWrapper => ( return response; } - await Promise.all(cookies.map((cookie: string): Promise => ( - jar.setCookie(cookie, response.url) - ))); + await Promise.all(cookies.map((cookie: string): Promise => jar.setCookie(cookie, response.url))); return response; - } -); + }; export const fetchCookieFollowRedirectsDecorator = (jar?: CookieJar): FetchWrapper => { const fetchCookie = fetchCookieDecorator(jar); - return async function fetchCookieFollowRedirects( - url: RequestInfo, - options: RequestInit = {}, - ): Promise { + return async function fetchCookieFollowRedirects(url: RequestInfo, options: RequestInit = {}): Promise { const response = await fetchCookie(url, { ...options, @@ -112,9 +88,7 @@ export const fetchCookieFollowRedirectsDecorator = (jar?: CookieJar): FetchWrapp const userAgent = findUserAgent(options.headers as Headers); - const headers: Headers = userAgent !== undefined - ? { 'User-Agent': userAgent } - : {}; + const headers: Headers = userAgent !== undefined ? { 'User-Agent': userAgent } : {}; const redirectResponse = await fetchCookieFollowRedirects(location, { method: 'GET', diff --git a/packages/authorization/src/fetch.ts b/packages/authorization/src/fetch.ts index 98a12b9a8..9d29297fc 100644 --- a/packages/authorization/src/fetch.ts +++ b/packages/authorization/src/fetch.ts @@ -9,6 +9,5 @@ export type RequestInfo = import('node-fetch').RequestInfo | URL; export type RequestInit = import('node-fetch').RequestInit; export type Response = import('node-fetch').Response; -export const fetch = (url: RequestInfo, init?: RequestInit): Promise => ( - Promise.resolve(fetchPromise).then(fn => fn(url as string, init)) -); +export const fetch = (url: RequestInfo, init?: RequestInit): Promise => + Promise.resolve(fetchPromise).then(fn => fn(url as string, init)); diff --git a/packages/authorization/src/helpers.ts b/packages/authorization/src/helpers.ts index 3da51cfad..2c2bf3433 100644 --- a/packages/authorization/src/helpers.ts +++ b/packages/authorization/src/helpers.ts @@ -1,7 +1,7 @@ import type { load as cheerioLoad } from 'cheerio'; +import { groupScopes, userScopes } from './constants'; import type { Response } from './fetch-cookie'; -import { userScopes, groupScopes } from './constants'; export type CheerioStatic = ReturnType; @@ -9,9 +9,7 @@ export type CheerioStatic = ReturnType; * Returns the bit mask of the user permission by name */ export const getUserPermissionsByName = (rawScope: string | string[]): number => { - const scope = !Array.isArray(rawScope) - ? rawScope.split(/,\s*/) - : rawScope; + const scope = !Array.isArray(rawScope) ? rawScope.split(/,\s*/) : rawScope; let bitMask = 0; @@ -30,9 +28,7 @@ export const getUserPermissionsByName = (rawScope: string | string[]): number => * Returns the bit mask of the group permission by name */ export const getGroupPermissionsByName = (rawScope: string | string[]): number => { - const scope = !Array.isArray(rawScope) - ? rawScope.split(/,\s*/) - : rawScope; + const scope = !Array.isArray(rawScope) ? rawScope.split(/,\s*/) : rawScope; let bitMask = 0; @@ -47,18 +43,16 @@ export const getGroupPermissionsByName = (rawScope: string | string[]): number = return bitMask; }; -export const getAllUserPermissions = (): number => ( - getUserPermissionsByName([...userScopes.keys()]) -); +export const getAllUserPermissions = (): number => getUserPermissionsByName([...userScopes.keys()]); -export const getAllGroupPermissions = (): number => ( - getGroupPermissionsByName([...groupScopes.keys()]) -); +export const getAllGroupPermissions = (): number => getGroupPermissionsByName([...groupScopes.keys()]); /** * Parse form */ -export const parseFormField = ($: unknown): { +export const parseFormField = ( + $: unknown, +): { action: string; fields: Record; } => { diff --git a/packages/authorization/src/index.ts b/packages/authorization/src/index.ts index e84ac8630..e5d7ddd34 100644 --- a/packages/authorization/src/index.ts +++ b/packages/authorization/src/index.ts @@ -5,7 +5,6 @@ export * from './open-api'; export { AuthErrorCode, officialAppCredentials, - userScopes, groupScopes, } from './constants'; diff --git a/packages/authorization/src/open-api.ts b/packages/authorization/src/open-api.ts index 911006be3..1e2875f74 100644 --- a/packages/authorization/src/open-api.ts +++ b/packages/authorization/src/open-api.ts @@ -1,34 +1,27 @@ import { createHash } from 'crypto'; -const openAPIProperties = [ - 'expire', - 'secret', - 'mid', - 'sid', -]; +const openAPIProperties = ['expire', 'secret', 'mid', 'sid']; export interface IUserAuthorizedThroughOpenAPIOptions { clientSecret: string; - params: Record<'expire' | 'mid' | 'secret' | 'sid' | 'sig', string> + params: Record<'expire' | 'mid' | 'secret' | 'sid' | 'sig', string>; } export const userAuthorizedThroughOpenAPI = ({ clientSecret, params, -}: IUserAuthorizedThroughOpenAPIOptions):Promise<{ authorized: boolean }> => { +}: IUserAuthorizedThroughOpenAPIOptions): Promise<{ authorized: boolean }> => { let sign = ([...openAPIProperties] as (keyof typeof params)[]) .sort() .map(key => `${key}=${params[key]}`) .join(''); sign += clientSecret; - sign = createHash('md5') - .update(sign) - .digest('hex'); + sign = createHash('md5').update(sign).digest('hex'); const expire = Number(params.expire); - const isExpired = Number.isNaN(expire) || expire < (Date.now() / 1000); + const isExpired = Number.isNaN(expire) || expire < Date.now() / 1000; const authorized = params.sig === sign && !isExpired; return Promise.resolve({ authorized }); diff --git a/packages/authorization/src/providers/account-verification.ts b/packages/authorization/src/providers/account-verification.ts index 427856dc4..671098879 100644 --- a/packages/authorization/src/providers/account-verification.ts +++ b/packages/authorization/src/providers/account-verification.ts @@ -1,33 +1,26 @@ -import createDebug from 'debug'; -import { load as cheerioLoad } from 'cheerio'; import { AbortController } from 'abort-controller'; +import { load as cheerioLoad } from 'cheerio'; +import createDebug from 'debug'; -import { CaptchaType, type ICallbackServiceValidate, type CallbackService } from 'vk-io'; +import { type CallbackService, CaptchaType, type ICallbackServiceValidate } from 'vk-io'; import type { Agent } from 'https'; +import { AuthErrorCode, CALLBACK_BLANK, DESKTOP_USER_AGENT } from '../constants'; import { AuthorizationError } from '../errors'; -import { type CheerioStatic, parseFormField, getFullURL } from '../helpers'; import { CookieJar, - type FetchWrapper, type RequestInfo, type RequestInit, type Response, - fetchCookieFollowRedirectsDecorator, } from '../fetch-cookie'; -import { DESKTOP_USER_AGENT, CALLBACK_BLANK, AuthErrorCode } from '../constants'; +import { type CheerioStatic, getFullURL, parseFormField } from '../helpers'; const debug = createDebug('vk-io:authorization:account-verification'); -const { - INVALID_PHONE_NUMBER, - AUTHORIZATION_FAILED, - FAILED_PASSED_CAPTCHA, - FAILED_PASSED_TWO_FACTOR, -} = AuthErrorCode; +const { INVALID_PHONE_NUMBER, AUTHORIZATION_FAILED, FAILED_PASSED_CAPTCHA, FAILED_PASSED_TWO_FACTOR } = AuthErrorCode; /** * Two-factor auth check action @@ -226,11 +219,13 @@ export class AccountVerification { debug('process two-factor handle'); if (this.twoFactorValidate) { - this.twoFactorValidate.reject(new AuthorizationError({ - message: 'Incorrect two-factor code', - code: FAILED_PASSED_TWO_FACTOR, - pageHtml: $.html(), - })); + this.twoFactorValidate.reject( + new AuthorizationError({ + message: 'Incorrect two-factor code', + code: FAILED_PASSED_TWO_FACTOR, + pageHtml: $.html(), + }), + ); this.twoFactorAttempts += 1; } @@ -341,10 +336,12 @@ export class AccountVerification { */ protected async processCaptchaForm(response: Response, $: CheerioStatic): Promise { if (this.captchaValidate !== undefined) { - this.captchaValidate.reject(new AuthorizationError({ - message: 'Incorrect captcha code', - code: FAILED_PASSED_CAPTCHA, - })); + this.captchaValidate.reject( + new AuthorizationError({ + message: 'Incorrect captcha code', + code: FAILED_PASSED_CAPTCHA, + }), + ); this.captchaValidate = undefined; diff --git a/packages/authorization/src/providers/direct.ts b/packages/authorization/src/providers/direct.ts index c4d15cd0e..7111292aa 100644 --- a/packages/authorization/src/providers/direct.ts +++ b/packages/authorization/src/providers/direct.ts @@ -1,30 +1,27 @@ -import createDebug from 'debug'; -import { load as cheerioLoad } from 'cheerio'; import { AbortController } from 'abort-controller'; +import { load as cheerioLoad } from 'cheerio'; +import createDebug from 'debug'; -import { CaptchaType, type ICallbackServiceValidate, type CallbackService } from 'vk-io'; +import { type CallbackService, CaptchaType, type ICallbackServiceValidate } from 'vk-io'; import type { Agent } from 'https'; +import { AuthErrorCode, DESKTOP_USER_AGENT } from '../constants'; import { AuthorizationError } from '../errors'; -import { DESKTOP_USER_AGENT, AuthErrorCode } from '../constants'; import { type CookieJar, - type FetchWrapper, type RequestInfo, type RequestInit, type Response, - fetchCookieFollowRedirectsDecorator, } from '../fetch-cookie'; import { type CheerioStatic, - + getAllUserPermissions, getFullURL, - parseFormField, getUserPermissionsByName, - getAllUserPermissions, + parseFormField, } from '../helpers'; const debug = createDebug('vk-io:authorization:direct'); @@ -122,10 +119,7 @@ export class DirectAuthorization { /** * Executes the HTTP request */ - protected fetch( - url: RequestInfo, - options: RequestInit = {}, - ): Promise { + protected fetch(url: RequestInfo, options: RequestInit = {}): Promise { const { agent, timeout } = this.options; const controller = new AbortController(); @@ -160,14 +154,7 @@ export class DirectAuthorization { debug('auth scope %s', scope); - const { - clientId, - clientSecret, - login, - phone, - password, - apiVersion, - } = this.options; + const { clientId, clientSecret, login, phone, password, apiVersion } = this.options; if (!password) { throw new AuthorizationError({ @@ -232,23 +219,14 @@ export class DirectAuthorization { if (isJSON) { if (text.access_token !== undefined) { - const { - email, - user_id: user, - expires_in: expires, - access_token: token, - } = text; + const { email, user_id: user, expires_in: expires, access_token: token } = text; return { email, - user: user !== undefined - ? Number(user) - : 0, + user: user !== undefined ? Number(user) : 0, token, - expires: expires - ? Number(expires) - : 0, + expires: expires ? Number(expires) : 0, }; } @@ -268,20 +246,24 @@ export class DirectAuthorization { } if (text.error === 'need_captcha') { - response = await this.processCaptcha(text as { - captcha_sid: string; - captcha_img: string; - }); + response = await this.processCaptcha( + text as { + captcha_sid: string; + captcha_img: string; + }, + ); continue; } if (text.error === 'need_validation') { if (text.validation_type !== undefined) { - response = await this.processTwoFactor(text as { - validation_type: string; - phone_mask: string; - }); + response = await this.processTwoFactor( + text as { + validation_type: string; + phone_mask: string; + }, + ); continue; } @@ -335,19 +317,22 @@ export class DirectAuthorization { /** * Process captcha */ - protected async processCaptcha( - { captcha_sid: sid, captcha_img: src }: { - captcha_sid: string; - captcha_img: string; - }, - ): Promise { + protected async processCaptcha({ + captcha_sid: sid, + captcha_img: src, + }: { + captcha_sid: string; + captcha_img: string; + }): Promise { debug('captcha process'); if (this.captchaValidate !== undefined) { - this.captchaValidate.reject(new AuthorizationError({ - message: 'Incorrect captcha code', - code: FAILED_PASSED_CAPTCHA, - })); + this.captchaValidate.reject( + new AuthorizationError({ + message: 'Incorrect captcha code', + code: FAILED_PASSED_CAPTCHA, + }), + ); this.captchaValidate = undefined; @@ -380,19 +365,22 @@ export class DirectAuthorization { /** * Process two-factor */ - protected async processTwoFactor( - { validation_type: validationType, phone_mask: phoneMask }: { - validation_type: string; - phone_mask: string; - }, - ): Promise { + protected async processTwoFactor({ + validation_type: validationType, + phone_mask: phoneMask, + }: { + validation_type: string; + phone_mask: string; + }): Promise { debug('process two-factor handle'); if (this.twoFactorValidate !== undefined) { - this.twoFactorValidate.reject(new AuthorizationError({ - message: 'Incorrect two-factor code', - code: FAILED_PASSED_TWO_FACTOR, - })); + this.twoFactorValidate.reject( + new AuthorizationError({ + message: 'Incorrect two-factor code', + code: FAILED_PASSED_TWO_FACTOR, + }), + ); this.twoFactorValidate = undefined; @@ -408,9 +396,7 @@ export class DirectAuthorization { const { code, validate } = await this.options.callbackService.processingTwoFactor({ phoneMask, - type: validationType === '2fa_app' - ? 'app' - : 'sms', + type: validationType === '2fa_app' ? 'app' : 'sms', }); this.twoFactorValidate = validate; diff --git a/packages/authorization/src/providers/implicit-flow-groups.ts b/packages/authorization/src/providers/implicit-flow-groups.ts index 2c4acecaa..748f8e88b 100644 --- a/packages/authorization/src/providers/implicit-flow-groups.ts +++ b/packages/authorization/src/providers/implicit-flow-groups.ts @@ -1,11 +1,11 @@ import createDebug from 'debug'; -import { ImplicitFlow, type IImplicitFlowOptions } from './implicit-flow'; +import { type IImplicitFlowOptions, ImplicitFlow } from './implicit-flow'; -import type { Response } from '../fetch-cookie'; +import { AuthErrorCode, CALLBACK_BLANK } from '../constants'; import { AuthorizationError } from '../errors'; -import { getGroupPermissionsByName, getAllGroupPermissions } from '../helpers'; -import { CALLBACK_BLANK, AuthErrorCode } from '../constants'; +import type { Response } from '../fetch-cookie'; +import { getAllGroupPermissions, getGroupPermissionsByName } from '../helpers'; const debug = createDebug('vk-io:authorization:implicit-flow-user'); @@ -30,7 +30,7 @@ export class ImplicitFlowGroups extends ImplicitFlow { groupIds = [groupIds]; } - this.groupIds = groupIds.map((rawGroupId) => { + this.groupIds = groupIds.map(rawGroupId => { const groupId = Number(rawGroupId); return Math.abs(groupId); diff --git a/packages/authorization/src/providers/implicit-flow-user.ts b/packages/authorization/src/providers/implicit-flow-user.ts index 99b498239..6f7132f04 100644 --- a/packages/authorization/src/providers/implicit-flow-user.ts +++ b/packages/authorization/src/providers/implicit-flow-user.ts @@ -1,11 +1,11 @@ import createDebug from 'debug'; -import { ImplicitFlow } from './implicit-flow'; import { AuthorizationError } from '../errors'; +import { ImplicitFlow } from './implicit-flow'; +import { AuthErrorCode, CALLBACK_BLANK } from '../constants'; import type { Response } from '../fetch-cookie'; -import { getUserPermissionsByName, getAllUserPermissions } from '../helpers'; -import { CALLBACK_BLANK, AuthErrorCode } from '../constants'; +import { getAllUserPermissions, getUserPermissionsByName } from '../helpers'; const debug = createDebug('vk-io:authorization:implicit-flow-user'); @@ -86,14 +86,10 @@ export class ImplicitFlowUser extends ImplicitFlow { return { email: params.get('email') || undefined, - userId: userId !== null - ? Number(userId) - : undefined, + userId: userId !== null ? Number(userId) : undefined, token: accessToken, - expires: expires !== null - ? Number(expires) - : undefined, + expires: expires !== null ? Number(expires) : undefined, }; } } diff --git a/packages/authorization/src/providers/implicit-flow.ts b/packages/authorization/src/providers/implicit-flow.ts index 199f7fc11..89e166289 100644 --- a/packages/authorization/src/providers/implicit-flow.ts +++ b/packages/authorization/src/providers/implicit-flow.ts @@ -1,34 +1,27 @@ -import createDebug from 'debug'; -import { load as cheerioLoad } from 'cheerio'; import { AbortController } from 'abort-controller'; +import { load as cheerioLoad } from 'cheerio'; +import createDebug from 'debug'; -import { CaptchaType, type ICallbackServiceValidate, type CallbackService } from 'vk-io'; +import { type CallbackService, CaptchaType, type ICallbackServiceValidate } from 'vk-io'; import type { Agent } from 'https'; +import { AuthErrorCode, CALLBACK_BLANK, DESKTOP_USER_AGENT } from '../constants'; import { AuthorizationError } from '../errors'; -import { parseFormField, getFullURL, type CheerioStatic } from '../helpers'; import { CookieJar, - type FetchWrapper, type RequestInfo, type RequestInit, type Response, - fetchCookieFollowRedirectsDecorator, } from '../fetch-cookie'; -import { DESKTOP_USER_AGENT, CALLBACK_BLANK, AuthErrorCode } from '../constants'; +import { type CheerioStatic, getFullURL, parseFormField } from '../helpers'; const debug = createDebug('vk-io:authorization:implicit-flow'); -const { - PAGE_BLOCKED, - INVALID_PHONE_NUMBER, - AUTHORIZATION_FAILED, - FAILED_PASSED_CAPTCHA, - FAILED_PASSED_TWO_FACTOR, -} = AuthErrorCode; +const { PAGE_BLOCKED, INVALID_PHONE_NUMBER, AUTHORIZATION_FAILED, FAILED_PASSED_CAPTCHA, FAILED_PASSED_TWO_FACTOR } = + AuthErrorCode; /** * Blocked action @@ -161,10 +154,7 @@ export abstract class ImplicitFlow { /** * Executes the HTTP request */ - protected fetch( - url: RequestInfo, - options: RequestInit = {}, - ): Promise { + protected fetch(url: RequestInfo, options: RequestInit = {}): Promise { const { agent, timeout } = this.options; const { headers = {} } = options; @@ -252,9 +242,7 @@ export abstract class ImplicitFlow { const isError = $error.length !== 0; if (this.captchaValidate === undefined && (isError || $service.length !== 0)) { - const errorText = isError - ? $error.text() - : $service.text(); + const errorText = isError ? $error.text() : $service.text(); throw new AuthorizationError({ message: `Auth form error: ${errorText}`, @@ -318,11 +306,13 @@ export abstract class ImplicitFlow { debug('process login handle'); if (this.captchaValidate) { - this.captchaValidate.reject(new AuthorizationError({ - message: 'Incorrect captcha code', - code: FAILED_PASSED_CAPTCHA, - pageHtml: $.html(), - })); + this.captchaValidate.reject( + new AuthorizationError({ + message: 'Incorrect captcha code', + code: FAILED_PASSED_CAPTCHA, + pageHtml: $.html(), + }), + ); this.captchaValidate = undefined; @@ -385,11 +375,13 @@ export abstract class ImplicitFlow { debug('process two-factor handle'); if (this.twoFactorValidate !== undefined) { - this.twoFactorValidate.reject(new AuthorizationError({ - message: 'Incorrect two-factor code', - code: FAILED_PASSED_TWO_FACTOR, - pageHtml: $.html(), - })); + this.twoFactorValidate.reject( + new AuthorizationError({ + message: 'Incorrect two-factor code', + code: FAILED_PASSED_TWO_FACTOR, + pageHtml: $.html(), + }), + ); this.twoFactorAttempts += 1; } @@ -441,10 +433,7 @@ export abstract class ImplicitFlow { }); } - const { - key, - validate: captchaValidate, - } = await this.options.callbackService.processingCaptcha({ + const { key, validate: captchaValidate } = await this.options.callbackService.processingCaptcha({ type: CaptchaType.IMPLICIT_FLOW_AUTH, sid: fields.captcha_sid, src: `https://api.vk.com/${src}`, diff --git a/packages/hear/src/hear-manager.ts b/packages/hear/src/hear-manager.ts index 5165e1ffe..c0fe6644c 100644 --- a/packages/hear/src/hear-manager.ts +++ b/packages/hear/src/hear-manager.ts @@ -1,14 +1,9 @@ -import { type Context, Composer } from 'vk-io'; -import { - type Middleware, - type MiddlewareReturn, - type NextMiddleware, - skipMiddleware, -} from 'middleware-io'; +import { type Middleware, type MiddlewareReturn, type NextMiddleware, skipMiddleware } from 'middleware-io'; +import { Composer, type Context } from 'vk-io'; import type { HearConditions, HearFunctionCondition } from './types'; -import { splitPath, unifyCondition, getObjectValue } from './helpers'; +import { getObjectValue, splitPath, unifyCondition } from './helpers'; export class HearManager { private composer = Composer.builder(); @@ -24,18 +19,11 @@ export class HearManager { return this.composer.length; } public get middleware(): Middleware { - return (context: C, next: NextMiddleware): unknown => ( - this.composed(context, next) - ); + return (context: C, next: NextMiddleware): unknown => this.composed(context, next); } - public hear( - hearConditions: HearConditions, - handler: Middleware, - ): this { - const rawConditions = !Array.isArray(hearConditions) - ? [hearConditions] - : hearConditions; + public hear(hearConditions: HearConditions, handler: Middleware): this { + const rawConditions = !Array.isArray(hearConditions) ? [hearConditions] : hearConditions; const hasConditions = rawConditions.every(Boolean); @@ -53,17 +41,19 @@ export class HearManager { if (typeof condition === 'object' && !(condition instanceof RegExp)) { functionCondtion = true; - const entries = Object.entries(condition).map(([path, value]): [string[], HearFunctionCondition] => ( - [splitPath(path), unifyCondition(value)] - )); + const entries = Object.entries(condition).map( + ([path, value]): [string[], HearFunctionCondition] => [ + splitPath(path), + unifyCondition(value), + ], + ); - return (text, context) => ( + return (text, context) => entries.every(([selectors, callback]): boolean => { const value = getObjectValue(context, selectors); return callback(value, context); - }) - ); + }); } if (typeof condition === 'function') { @@ -90,7 +80,7 @@ export class HearManager { const stringCondition = String(condition); - return (text) => text === stringCondition; + return text => text === stringCondition; }); const needText = textCondition && functionCondtion === false; @@ -102,13 +92,9 @@ export class HearManager { return next(); } - const hasSome = conditions.some((condition): boolean => ( - condition(text, context) - )); + const hasSome = conditions.some((condition): boolean => condition(text, context)); - return hasSome - ? handler(context, next) - : next(); + return hasSome ? handler(context, next) : next(); }); this.recompose(); @@ -128,8 +114,6 @@ export class HearManager { } private recompose(): void { - this.composed = this.composer.clone() - .use(this.fallbackHandler) - .compose(); + this.composed = this.composer.clone().use(this.fallbackHandler).compose(); } } diff --git a/packages/hear/src/helpers.ts b/packages/hear/src/helpers.ts index c7ad415ae..621f8da5b 100644 --- a/packages/hear/src/helpers.ts +++ b/packages/hear/src/helpers.ts @@ -1,50 +1,42 @@ import type { HearFunctionCondition } from './types'; -export const splitPath = (path: string): string[] => ( - path - .replace(/\[([^[\]]*)\]/g, '.$1.') - .split('.') - .filter(Boolean) -); +export const splitPath = (path: string): string[] => + path + .replace(/\[([^[\]]*)\]/g, '.$1.') + .split('.') + .filter(Boolean); export const getObjectValue = (source: Record, selectors: string[]): any => { - let link = source; + let link = source; - for (const selector of selectors) { - if (!link[selector]) { - return undefined; - } + for (const selector of selectors) { + if (!link[selector]) { + return undefined; + } - link = link[selector]; - } + link = link[selector]; + } - return link; + return link; }; export const unifyCondition = (condition: unknown): HearFunctionCondition => { - if (typeof condition === 'function') { - return condition as HearFunctionCondition; - } - - if (condition instanceof RegExp) { - return (text) => ( - condition.test(text as string) - ); - } - - if (Array.isArray(condition)) { - const arrayConditions = condition.map(unifyCondition); - - return (value, context) => ( - Array.isArray(value) - ? arrayConditions.every((cond): boolean => ( - value.some((val): boolean => cond(val, context)) - )) - : arrayConditions.some((cond): boolean => ( - cond(value, context) - )) - ); - } - - return (value) => value === condition; + if (typeof condition === 'function') { + return condition as HearFunctionCondition; + } + + if (condition instanceof RegExp) { + return text => condition.test(text as string); + } + + if (Array.isArray(condition)) { + const arrayConditions = condition.map(unifyCondition); + + return (value, context) => + Array.isArray(value) + ? arrayConditions.every((cond): boolean => value.some((val): boolean => cond(val, context))) + : arrayConditions.some((cond): boolean => cond(value, context)); + } + + return value => value === condition; }; diff --git a/packages/hear/src/types.ts b/packages/hear/src/types.ts index 3a59e10c9..88305e03a 100644 --- a/packages/hear/src/types.ts +++ b/packages/hear/src/types.ts @@ -4,13 +4,10 @@ export type HearFunctionCondition = (value: V, context: T) => boolean; export type HearCondition = HearFunctionCondition | RegExp | string | number | boolean; -export type HearObjectCondition> = -Record>> -& { +export type HearObjectCondition> = Record>> & { [P in keyof T]?: AllowArray>; }; -export type HearConditions> = ( - AllowArray> - | AllowArray> -); +export type HearConditions> = + | AllowArray> + | AllowArray>; diff --git a/packages/scenes/src/cache-repository.ts b/packages/scenes/src/cache-repository.ts index fb3a2e010..4b02e1304 100644 --- a/packages/scenes/src/cache-repository.ts +++ b/packages/scenes/src/cache-repository.ts @@ -9,7 +9,9 @@ export class CacheRepository { protected sortingValues?: CacheRepositorySortingValues; - public constructor({ sortingValues }: { + public constructor({ + sortingValues, + }: { sortingValues?: CacheRepositorySortingValues; } = {}) { this.sortingValues = sortingValues; diff --git a/packages/scenes/src/contexts/scene.ts b/packages/scenes/src/contexts/scene.ts index 07c64b02d..547c6b937 100644 --- a/packages/scenes/src/contexts/scene.ts +++ b/packages/scenes/src/contexts/scene.ts @@ -1,12 +1,11 @@ +import type { IScene } from '../scenes'; import type { ISessionContext } from '../types'; import { - type ISceneContextOptions, type ISceneContextEnterOptions, type ISceneContextLeaveOptions, - + type ISceneContextOptions, LastAction, } from './scene.types'; -import type { IScene } from '../scenes'; export class SceneContext> { /** diff --git a/packages/scenes/src/contexts/scene.types.ts b/packages/scenes/src/contexts/scene.types.ts index 4864f4fc4..9528665aa 100644 --- a/packages/scenes/src/contexts/scene.types.ts +++ b/packages/scenes/src/contexts/scene.types.ts @@ -1,5 +1,5 @@ -import type { IContext } from '../types'; import type { SceneRepository } from '../scene-manager.types'; +import type { IContext } from '../types'; export interface ISceneContextOptions { context: IContext; @@ -36,5 +36,5 @@ export interface ISceneContextLeaveOptions { export enum LastAction { NONE = 'none', ENTER = 'enter', - LEAVE = 'leave' + LEAVE = 'leave', } diff --git a/packages/scenes/src/contexts/step.ts b/packages/scenes/src/contexts/step.ts index e3e756a1a..133880ff6 100644 --- a/packages/scenes/src/contexts/step.ts +++ b/packages/scenes/src/contexts/step.ts @@ -1,6 +1,6 @@ -import type { IStepContextOptions, IStepContextGoOptions } from './step.types'; import type { StepSceneHandler } from '../scenes/step.types'; import { LastAction } from './scene.types'; +import type { IStepContextGoOptions, IStepContextOptions } from './step.types'; export class StepSceneContext> { private context: IStepContextOptions['context']; diff --git a/packages/scenes/src/scene-manager.ts b/packages/scenes/src/scene-manager.ts index 671cb5958..fcd2712b8 100644 --- a/packages/scenes/src/scene-manager.ts +++ b/packages/scenes/src/scene-manager.ts @@ -1,9 +1,9 @@ import type { IScene } from './scenes/scene'; -import type { IContext, Middleware } from './types'; -import { SceneContext } from './contexts'; import { CacheRepository } from './cache-repository'; -import type { SceneRepository, ISceneManagerOptions } from './scene-manager.types'; +import { SceneContext } from './contexts'; +import type { ISceneManagerOptions, SceneRepository } from './scene-manager.types'; +import type { IContext, Middleware } from './types'; export class SceneManager { private repository: SceneRepository = new CacheRepository(); diff --git a/packages/scenes/src/scene-manager.types.ts b/packages/scenes/src/scene-manager.types.ts index e754ccdab..c94519a8d 100644 --- a/packages/scenes/src/scene-manager.types.ts +++ b/packages/scenes/src/scene-manager.types.ts @@ -1,5 +1,5 @@ -import type { IScene } from './scenes/scene'; import type { CacheRepository } from './cache-repository'; +import type { IScene } from './scenes/scene'; export type SceneRepository = CacheRepository; diff --git a/packages/scenes/src/scenes/step.ts b/packages/scenes/src/scenes/step.ts index b58b17560..2c8c3b07d 100644 --- a/packages/scenes/src/scenes/step.ts +++ b/packages/scenes/src/scenes/step.ts @@ -4,12 +4,11 @@ import type { IScene } from './scene'; import { StepSceneContext } from '../contexts'; import { LastAction } from '../contexts/scene.types'; -import type { StepSceneHandler, IStepContext, IStepSceneOptions } from './step.types'; +import type { IStepContext, IStepSceneOptions, StepSceneHandler } from './step.types'; -export class StepScene< - T = MessageContext, - S extends Record = Record -> implements IScene { +export class StepScene = Record> + implements IScene +{ public slug: string; private steps: StepSceneHandler[]; @@ -19,9 +18,7 @@ export class StepScene< private onLeaveHandler: NonNullable['leaveHandler']>; public constructor(slug: string, rawOptions: IStepSceneOptions | StepSceneHandler[]) { - const options = Array.isArray(rawOptions) - ? { steps: rawOptions } - : rawOptions; + const options = Array.isArray(rawOptions) ? { steps: rawOptions } : rawOptions; this.slug = slug; diff --git a/packages/scenes/src/scenes/step.types.ts b/packages/scenes/src/scenes/step.types.ts index ed7ca2996..b40c3ca74 100644 --- a/packages/scenes/src/scenes/step.types.ts +++ b/packages/scenes/src/scenes/step.types.ts @@ -1,5 +1,5 @@ -import type { IContext } from '../types'; import type { SceneContext, StepSceneContext } from '../contexts'; +import type { IContext } from '../types'; export interface IStepContext> extends IContext { scene: SceneContext & { @@ -10,10 +10,9 @@ export interface IStepContext> extends IContex }; } -export type StepSceneHandler< - T = object, - S extends Record = Record -> = (context: IStepContext & T) => unknown; +export type StepSceneHandler = Record> = ( + context: IStepContext & T, +) => unknown; export interface IStepSceneOptions> { steps: StepSceneHandler[]; diff --git a/packages/scenes/src/types.ts b/packages/scenes/src/types.ts index e1e152eba..fb3e3a3ac 100644 --- a/packages/scenes/src/types.ts +++ b/packages/scenes/src/types.ts @@ -8,9 +8,7 @@ export type ISessionContext = Record & { current: string; }; -export interface IContext< - S extends Record = Record -> extends Context { +export interface IContext = Record> extends Context { /** * Scene control context */ diff --git a/packages/session/src/session-manager.ts b/packages/session/src/session-manager.ts index 3fb506347..bf3930f0f 100644 --- a/packages/session/src/session-manager.ts +++ b/packages/session/src/session-manager.ts @@ -1,12 +1,6 @@ import { MemoryStorage } from './storages'; -import type { - IContext, - ISessionContext, - ISessionManagerOptions, - - Middleware, -} from './types'; +import type { IContext, ISessionContext, ISessionManagerOptions, Middleware } from './types'; export class SessionManager { protected storage: ISessionManagerOptions['storage']; @@ -16,15 +10,11 @@ export class SessionManager { protected getStorageKey: ISessionManagerOptions['getStorageKey']; public constructor(options: Partial> = {}) { - this.storage = options.storage || ( - new MemoryStorage() - ); + this.storage = options.storage || new MemoryStorage(); this.contextKey = options.contextKey || 'session'; - this.getStorageKey = options.getStorageKey || ((context): string => ( - String(context.senderId || context.userId) - )); + this.getStorageKey = options.getStorageKey || ((context): string => String(context.senderId || context.userId)); } /** @@ -37,24 +27,26 @@ export class SessionManager { const storageKey = getStorageKey(context); let changed = false; - const wrapSession = (targetRaw: object): ISessionContext => ( - new Proxy({ ...targetRaw, $forceUpdate }, { - set: (target, prop: string, value): boolean => { - changed = true; + const wrapSession = (targetRaw: object): ISessionContext => + new Proxy( + { ...targetRaw, $forceUpdate }, + { + set: (target, prop: string, value): boolean => { + changed = true; - target[prop] = value; + target[prop] = value; - return true; - }, - deleteProperty: (target, prop: string): boolean => { - changed = true; + return true; + }, + deleteProperty: (target, prop: string): boolean => { + changed = true; - delete target[prop]; + delete target[prop]; - return true; + return true; + }, }, - }) - ); + ); const $forceUpdate = (): Promise => { if (Object.keys(session).length > 1) { @@ -65,7 +57,7 @@ export class SessionManager { return storage.delete(storageKey); }; - const initialSession = await storage.get(storageKey) || {}; + const initialSession = (await storage.get(storageKey)) || {}; let session = wrapSession(initialSession); diff --git a/packages/stateless-prompt/src/identifier.ts b/packages/stateless-prompt/src/identifier.ts index 8f4e32f7a..5f0de3d94 100644 --- a/packages/stateless-prompt/src/identifier.ts +++ b/packages/stateless-prompt/src/identifier.ts @@ -1,9 +1,8 @@ import { createHash } from 'crypto'; -export const getDataHash = (data: string): string => ( +export const getDataHash = (data: string): string => createHash('shake256', { outputLength: 2, }) .update(data) - .digest('hex') -); + .digest('hex'); diff --git a/packages/stateless-prompt/src/stateless-prompt-manager.ts b/packages/stateless-prompt/src/stateless-prompt-manager.ts index 393bd8506..8d9910083 100644 --- a/packages/stateless-prompt/src/stateless-prompt-manager.ts +++ b/packages/stateless-prompt/src/stateless-prompt-manager.ts @@ -1,7 +1,7 @@ import { getDataHash } from './identifier'; -import type { MessageContext, Middleware, HandlerMiddleware } from './types'; import type { IStatelessPromptManagerOptions } from './stateless-prompt.types'; +import type { HandlerMiddleware, MessageContext, Middleware } from './types'; export class StatelessPromptManager { protected slug: string; diff --git a/packages/streaming/src/contexts/streaming.ts b/packages/streaming/src/contexts/streaming.ts index a979568b4..77fd89a55 100644 --- a/packages/streaming/src/contexts/streaming.ts +++ b/packages/streaming/src/contexts/streaming.ts @@ -1,14 +1,11 @@ import { + Attachmentable, Context, + type ContextDefaultState, type ContextFactoryOptions, - - Attachmentable, - - transformAttachments, - kSerializeData, - applyMixins, - type ContextDefaultState, + kSerializeData, + transformAttachments, } from 'vk-io'; import { copyParams } from '../helpers'; @@ -44,11 +41,9 @@ export interface IStreamingContextPayload { }; } -export type StreamingContextOptions = - ContextFactoryOptions; +export type StreamingContextOptions = ContextFactoryOptions; -class StreamingContext - extends Context { +class StreamingContext extends Context { public constructor(options: StreamingContextOptions) { const { action, event_type: type } = options.payload; @@ -56,11 +51,7 @@ class StreamingContext ...options, type: 'publication', - subTypes: [ - `publication_${type}`, - `${action}_publication`, - `${action}_publication_${type}`, - ], + subTypes: [`publication_${type}`, `${action}_publication`, `${action}_publication_${type}`], }); this.attachments = transformAttachments(this.payload.attachments || [], this.api); @@ -273,17 +264,13 @@ class StreamingContext 'isComment', ]; - const filtredEmptyProperties = properties.filter(property => ( - this[property] !== undefined - )) as (keyof this)[]; + const filtredEmptyProperties = properties.filter(property => this[property] !== undefined) as (keyof this)[]; return copyParams(this, filtredEmptyProperties); } } interface StreamingContext extends Attachmentable {} -applyMixins(StreamingContext, [ - Attachmentable, -]); +applyMixins(StreamingContext, [Attachmentable]); export { StreamingContext }; diff --git a/packages/streaming/src/fetch.ts b/packages/streaming/src/fetch.ts index 98a12b9a8..9d29297fc 100644 --- a/packages/streaming/src/fetch.ts +++ b/packages/streaming/src/fetch.ts @@ -9,6 +9,5 @@ export type RequestInfo = import('node-fetch').RequestInfo | URL; export type RequestInit = import('node-fetch').RequestInit; export type Response = import('node-fetch').Response; -export const fetch = (url: RequestInfo, init?: RequestInit): Promise => ( - Promise.resolve(fetchPromise).then(fn => fn(url as string, init)) -); +export const fetch = (url: RequestInfo, init?: RequestInit): Promise => + Promise.resolve(fetchPromise).then(fn => fn(url as string, init)); diff --git a/packages/streaming/src/helpers.ts b/packages/streaming/src/helpers.ts index 0fe98fcc4..303ce00db 100644 --- a/packages/streaming/src/helpers.ts +++ b/packages/streaming/src/helpers.ts @@ -1,10 +1,7 @@ /** * Copies object params to new object */ -export const copyParams = < - T, - K extends keyof T ->(params: T, properties: K[]): Pick => { +export const copyParams = (params: T, properties: K[]): Pick => { const copies = {} as Pick; for (const property of properties) { diff --git a/packages/streaming/src/streaming.ts b/packages/streaming/src/streaming.ts index 2a0c7425d..91eddb634 100644 --- a/packages/streaming/src/streaming.ts +++ b/packages/streaming/src/streaming.ts @@ -1,15 +1,15 @@ -import WebSocket from 'ws'; import createDebug from 'debug'; import { inspectable } from 'inspectable'; +import WebSocket from 'ws'; -import { type API, type Updates, UpdateSource, VKError } from 'vk-io'; +import { type API, UpdateSource, type Updates, VKError } from 'vk-io'; import { type Agent, globalAgent } from 'https'; -import { fetch } from './fetch'; +import { type IStreamingContextPayload, StreamingContext } from './contexts'; import { StreamingRuleError } from './errors'; -import { StreamingContext, type IStreamingContextPayload } from './contexts'; import type { IStreamingRuleErrorOptions } from './errors/streaming-rule'; +import { fetch } from './fetch'; const debug = createDebug('vk-io:streaming'); @@ -44,11 +44,7 @@ export class StreamingAPI { /** * Constructor */ - public constructor({ - api, - updates, - ...options - }: Partial & { api: API; updates: Updates }) { + public constructor({ api, updates, ...options }: Partial & { api: API; updates: Updates }) { this.api = api; this.updates = updates; @@ -113,9 +109,11 @@ export class StreamingAPI { } case 300: { - await this.handleServiceMessage(message.service_message as { - service_code: number; - }); + await this.handleServiceMessage( + message.service_message as { + service_code: number; + }, + ); break; } @@ -152,9 +150,7 @@ export class StreamingAPI { /** * Processes server messages */ - public async handleServiceMessage( - { service_code: code }: { service_code: number }, - ): Promise { + public async handleServiceMessage({ service_code: code }: { service_code: number }): Promise { if ([3000, 3001].includes(code)) { await this.stop(); await this.startWebSocket(); @@ -189,7 +185,7 @@ export class StreamingAPI { if (!this.key) { throw new VKError({ message: 'You should start websocket before call fetchRules', - code: 0 + code: 0, }); } @@ -209,7 +205,7 @@ export class StreamingAPI { 'content-type': 'application/json', }, }); - const result = await response.json() as any; + const result = (await response.json()) as any; if (result.error !== undefined) { throw new StreamingRuleError(result.error as IStreamingRuleErrorOptions); @@ -245,9 +241,7 @@ export class StreamingAPI { * Adds a list of rules */ public async addRules(rules: IStreamingRule[]): Promise { - await Promise.all(rules.map(rule => ( - this.addRule(rule) - ))); + await Promise.all(rules.map(rule => this.addRule(rule))); } /** @@ -256,9 +250,7 @@ export class StreamingAPI { public async deleteRules(): Promise { const rules = await this.getRules(); - await Promise.all(rules.map(({ tag }) => ( - this.deleteRule(tag) - ))); + await Promise.all(rules.map(({ tag }) => this.deleteRule(tag))); } } diff --git a/packages/vk-io/src/api/api.ts b/packages/vk-io/src/api/api.ts index a30146554..0d953b707 100644 --- a/packages/vk-io/src/api/api.ts +++ b/packages/vk-io/src/api/api.ts @@ -4,18 +4,13 @@ import { type Agent, globalAgent } from 'https'; import type { APIMethods } from './schemas/methods'; -import { - type APIWorker, - SequentialWorker, - ParallelWorker, - ParallelSelectedWorker, -} from './workers'; +import { type APIWorker, ParallelSelectedWorker, ParallelWorker, SequentialWorker } from './workers'; -import { APIRequest } from './request'; +import { type ExecuteError, VKError } from '../errors'; import type { Constructor } from '../types'; -import { VKError, type ExecuteError } from '../errors'; import type { CallbackService } from '../utils/callback-service'; import { MINIMUM_TIME_INTERVAL_API } from '../utils/constants'; +import { APIRequest } from './request'; // @ts-expect-error assert's not supported yet import { version } from '../../package.json'; @@ -226,7 +221,7 @@ class API { /** * Constructor */ - public constructor(options: Partial & { token: string; }) { + public constructor(options: Partial & { token: string }) { this.options = { agent: globalAgent, language: undefined, @@ -265,13 +260,16 @@ class API { for (const group of groupMethods) { // @ts-ignore this[group] = new Proxy(Object.create(null), { - get: (obj, prop: string) => (params: object): Promise => ( - this.callWithRequest(new APIRequest({ - api: this, - method: `${group}.${prop}`, - params, - })) - ), + get: + (obj, prop: string) => + (params: object): Promise => + this.callWithRequest( + new APIRequest({ + api: this, + method: `${group}.${prop}`, + params, + }), + ), }); } @@ -288,9 +286,7 @@ class API { /** * Call execute method */ - public execute( - params: Record & { code: string }, - ): Promise> { + public execute(params: Record & { code: string }): Promise> { return this.call('execute', params); } @@ -305,12 +301,14 @@ class API { * Call raw method */ public call(method: string, params: object): Promise { - return this.callWithRequest(new APIRequest({ - method, - params, - - api: this, - })); + return this.callWithRequest( + new APIRequest({ + method, + params, + + api: this, + }), + ); } /** @@ -349,10 +347,7 @@ class API { // @ts-expect-error private property newWorker.queue = [...this.worker.queue]; - setTimeout( - () => newWorker.resume(), - MINIMUM_TIME_INTERVAL_API, - ); + setTimeout(() => newWorker.resume(), MINIMUM_TIME_INTERVAL_API); } this.worker = newWorker; @@ -361,9 +356,7 @@ class API { inspectable(API, { serialize: ({ options }) => ({ options: { - token: options.token - ? '[set]' - : '[none]', + token: options.token ? '[set]' : '[none]', }, }), }); diff --git a/packages/vk-io/src/api/request.ts b/packages/vk-io/src/api/request.ts index cfff04533..f21bc00ba 100644 --- a/packages/vk-io/src/api/request.ts +++ b/packages/vk-io/src/api/request.ts @@ -2,10 +2,10 @@ import { AbortController } from 'abort-controller'; import { inspectable } from 'inspectable'; -import type { API } from './api'; +import type { ICallbackServiceValidate } from '../utils/callback-service'; import { fetch } from '../utils/fetch'; import { getExecuteMethod } from '../utils/helpers'; -import type { ICallbackServiceValidate } from '../utils/callback-service'; +import type { API } from './api'; export interface IAPIRequestOptions { api: API; @@ -90,10 +90,7 @@ export class APIRequest { connection: 'keep-alive', }, - body: new URLSearchParams( - Object.entries(params) - .filter(({ 1: value }) => value !== undefined), - ), + body: new URLSearchParams(Object.entries(params).filter(({ 1: value }) => value !== undefined)), }); const result = await response.json(); diff --git a/packages/vk-io/src/api/workers/parallel-selected.ts b/packages/vk-io/src/api/workers/parallel-selected.ts index 9738a33c4..740984949 100644 --- a/packages/vk-io/src/api/workers/parallel-selected.ts +++ b/packages/vk-io/src/api/workers/parallel-selected.ts @@ -2,7 +2,6 @@ import { ParallelWorker } from './parallel'; export class ParallelSelectedWorker extends ParallelWorker { protected skipMethod(method: string): boolean { - return super.skipMethod(method) - || !this.api.options.apiExecuteMethods.includes(method); + return super.skipMethod(method) || !this.api.options.apiExecuteMethods.includes(method); } } diff --git a/packages/vk-io/src/api/workers/parallel.ts b/packages/vk-io/src/api/workers/parallel.ts index 0591779de..e32123d94 100644 --- a/packages/vk-io/src/api/workers/parallel.ts +++ b/packages/vk-io/src/api/workers/parallel.ts @@ -22,9 +22,7 @@ export class ParallelWorker extends SequentialWorker { continue; } - tasks.push( - queue.splice(i, 1)[0], - ); + tasks.push(queue.splice(i, 1)[0]); i -= 1; @@ -48,10 +46,13 @@ export class ParallelWorker extends SequentialWorker { void super.execute(request); try { - resolveExecuteTask(tasks, await request.promise as { - errors: object[]; - response: (object | false)[]; - }); + resolveExecuteTask( + tasks, + (await request.promise) as { + errors: object[]; + response: (object | false)[]; + }, + ); } catch (error) { for (const task of tasks) { task.reject(error); @@ -59,7 +60,6 @@ export class ParallelWorker extends SequentialWorker { } } protected skipMethod(method: string): boolean { - return method.startsWith('execute') - || this.api.options.apiExecuteUnsupportedMethods.includes(method); + return method.startsWith('execute') || this.api.options.apiExecuteUnsupportedMethods.includes(method); } } diff --git a/packages/vk-io/src/api/workers/sequential.ts b/packages/vk-io/src/api/workers/sequential.ts index 38deac0cc..56dbe9228 100644 --- a/packages/vk-io/src/api/workers/sequential.ts +++ b/packages/vk-io/src/api/workers/sequential.ts @@ -2,17 +2,9 @@ import createDebug from 'debug'; import { APIWorker } from './worker'; -import type { APIRequest } from '../request'; +import { APIError, APIErrorCode, ExecuteError, type IAPIErrorOptions, type IExecuteErrorOptions } from '../../errors'; import { delay } from '../../utils/helpers'; -import { - type IExecuteErrorOptions, - - APIError, - ExecuteError, - - APIErrorCode, - type IAPIErrorOptions, -} from '../../errors'; +import type { APIRequest } from '../request'; import { CaptchaType, MINIMUM_TIME_INTERVAL_API } from '../../utils/constants'; @@ -68,9 +60,9 @@ export class SequentialWorker extends APIWorker { if (method.startsWith('execute')) { request.resolve({ response: response.response, - errors: ((response.execute_errors || []) as IExecuteErrorOptions[]).map((error) => ( - new ExecuteError(error) - )), + errors: ((response.execute_errors || []) as IExecuteErrorOptions[]).map( + error => new ExecuteError(error), + ), }); return; @@ -105,10 +97,7 @@ export class SequentialWorker extends APIWorker { request.captchaValidate?.reject(error); - if ( - code !== APIErrorCode.CAPTCHA - || !this.api.options.callbackService?.hasCaptchaHandler - ) { + if (code !== APIErrorCode.CAPTCHA || !this.api.options.callbackService?.hasCaptchaHandler) { request.reject(error); return; diff --git a/packages/vk-io/src/api/workers/worker.ts b/packages/vk-io/src/api/workers/worker.ts index bcd8d43d1..7a0d33ce5 100644 --- a/packages/vk-io/src/api/workers/worker.ts +++ b/packages/vk-io/src/api/workers/worker.ts @@ -1,6 +1,6 @@ +import { MINIMUM_TIME_INTERVAL_API } from '../../utils/constants'; import type { API } from '../api'; import type { APIRequest } from '../request'; -import { MINIMUM_TIME_INTERVAL_API } from '../../utils/constants'; export abstract class APIWorker { public busy = false; @@ -54,14 +54,11 @@ export abstract class APIWorker { if (this.api.options.apiRequestMode === 'sequential') { this.execute(); - setTimeout( - () => { - this.busy = false; + setTimeout(() => { + this.busy = false; - this.immediateHeat(); - }, - this.intervalPerRequests, - ); + this.immediateHeat(); + }, this.intervalPerRequests); return; } @@ -74,7 +71,7 @@ export abstract class APIWorker { this.execute(); } - const interval = Math.ceil(MINIMUM_TIME_INTERVAL_API - (limit * this.intervalPerRequests)); + const interval = Math.ceil(MINIMUM_TIME_INTERVAL_API - limit * this.intervalPerRequests); setTimeout( () => { @@ -82,9 +79,7 @@ export abstract class APIWorker { this.immediateHeat(); }, - interval <= 0 - ? MINIMUM_TIME_INTERVAL_API - : interval, + interval <= 0 ? MINIMUM_TIME_INTERVAL_API : interval, ); } diff --git a/packages/vk-io/src/collect/chain.ts b/packages/vk-io/src/collect/chain.ts index d95f0b6da..c5d7d7d05 100644 --- a/packages/vk-io/src/collect/chain.ts +++ b/packages/vk-io/src/collect/chain.ts @@ -36,10 +36,12 @@ export class Chain { */ public append(method: string, params: object): Promise { if (this.started) { - return Promise.reject(new VKError({ - message: 'Chain already started', - code: 'ALREADY_STARTED', - })); + return Promise.reject( + new VKError({ + message: 'Chain already started', + code: 'ALREADY_STARTED', + }), + ); } const request = new APIRequest({ diff --git a/packages/vk-io/src/collect/execute-code.ts b/packages/vk-io/src/collect/execute-code.ts index f38b003fa..784905ab7 100644 --- a/packages/vk-io/src/collect/execute-code.ts +++ b/packages/vk-io/src/collect/execute-code.ts @@ -5,8 +5,7 @@ export interface IExecuteCodeOptions { params: Record; } -export const getExecuteCode = ({ method, params }: IExecuteCodeOptions): string => ( - ` +export const getExecuteCode = ({ method, params }: IExecuteCodeOptions): string => ` var params = ${getExecuteParams(params)}; params.offset = parseInt(Args.offset); @@ -47,5 +46,4 @@ export const getExecuteCode = ({ method, params }: IExecuteCodeOptions): string profiles: profiles, groups: groups }; - ` -); + `; diff --git a/packages/vk-io/src/collect/executes.ts b/packages/vk-io/src/collect/executes.ts index f6db685f6..92563b840 100644 --- a/packages/vk-io/src/collect/executes.ts +++ b/packages/vk-io/src/collect/executes.ts @@ -15,10 +15,7 @@ export interface IExecutesOptions { queue: Record[]; } -export const executeRequests = async ( - api: API, - queue: APIRequest[], -): Promise => { +export const executeRequests = async (api: API, queue: APIRequest[]): Promise => { const out: IExecutesPayload = { response: [], errors: [], @@ -50,16 +47,15 @@ export const executeRequests = async ( return out; }; -export const executes = ({ - api, - method, - queue, -}: IExecutesOptions): Promise => ( - executeRequests(api, queue.map(params => ( - new APIRequest({ - api, - method, - params, - }) - ))) -); +export const executes = ({ api, method, queue }: IExecutesOptions): Promise => + executeRequests( + api, + queue.map( + params => + new APIRequest({ + api, + method, + params, + }), + ), + ); diff --git a/packages/vk-io/src/collect/iterator.ts b/packages/vk-io/src/collect/iterator.ts index 6d90ef371..8199afedc 100644 --- a/packages/vk-io/src/collect/iterator.ts +++ b/packages/vk-io/src/collect/iterator.ts @@ -1,13 +1,7 @@ import createDebug from 'debug'; import type { API, Objects } from '../api'; -import { - type APIError, - CollectError, - - APIErrorCode, - CollectErrorCode, -} from '../errors'; +import { type APIError, APIErrorCode, CollectError, CollectErrorCode } from '../errors'; import { getExecuteCode } from './execute-code'; @@ -15,7 +9,7 @@ const debug = createDebug('api-io:collect'); export interface ICollectPaginateResponse { count: number; - items: T[] + items: T[]; groups?: Objects.GroupsGroupFull[]; profiles?: Objects.UsersUserFull[]; } @@ -69,10 +63,7 @@ export async function* createCollectIterator({ const code = getExecuteCode({ method, params }); - const { - count: desiredCount = Number.POSITIVE_INFINITY, - offset: ignoredOffset = 0, - } = rawParams; + const { count: desiredCount = Number.POSITIVE_INFINITY, offset: ignoredOffset = 0 } = rawParams; let total: number | undefined = Math.min(maxCount, desiredCount); if (!Number.isFinite(total)) { diff --git a/packages/vk-io/src/errors/api.ts b/packages/vk-io/src/errors/api.ts index 083cd4828..e9a61c26b 100644 --- a/packages/vk-io/src/errors/api.ts +++ b/packages/vk-io/src/errors/api.ts @@ -1,5 +1,5 @@ -import { VKError } from './error'; import { APIErrorCode } from '../api/schemas/constants'; +import { VKError } from './error'; export interface IAPIErrorParam { key: string; diff --git a/packages/vk-io/src/index.ts b/packages/vk-io/src/index.ts index aa945ad78..eeecd9c49 100644 --- a/packages/vk-io/src/index.ts +++ b/packages/vk-io/src/index.ts @@ -18,7 +18,6 @@ export { MessageSource, AttachmentType, AttachmentTypeString, - kSerializeData, } from './utils/constants'; diff --git a/packages/vk-io/src/structures/attachments/attachment.ts b/packages/vk-io/src/structures/attachments/attachment.ts index 162538dc2..6cce975a6 100644 --- a/packages/vk-io/src/structures/attachments/attachment.ts +++ b/packages/vk-io/src/structures/attachments/attachment.ts @@ -1,7 +1,7 @@ import { inspectable } from 'inspectable'; import type { API } from '../../api'; -import { kSerializeData, type AttachmentType } from '../../utils/constants'; +import { type AttachmentType, kSerializeData } from '../../utils/constants'; /** * Parse attachments @@ -21,8 +21,7 @@ export interface IAttachmentOptions { payload: Partial & P; } -export type AttachmentFactoryOptions

= - Omit, 'type'>; +export type AttachmentFactoryOptions

= Omit, 'type'>; export class Attachment

{ public type: Type; @@ -106,24 +105,16 @@ export class Attachment

instance.toJSON(), - stringify: (instance, payload, context): string => ( - `${context.stylize(instance.constructor.name, 'special')} <${context.stylize(String(instance), 'string')}> ${context.inspect(payload)}` - ), + serialize: instance => instance.toJSON(), + stringify: (instance, payload, context): string => + `${context.stylize(instance.constructor.name, 'special')} <${context.stylize( + String(instance), + 'string', + )}> ${context.inspect(payload)}`, }); diff --git a/packages/vk-io/src/structures/attachments/audio-message.ts b/packages/vk-io/src/structures/attachments/audio-message.ts index b66ba55d5..c14437fec 100644 --- a/packages/vk-io/src/structures/attachments/audio-message.ts +++ b/packages/vk-io/src/structures/attachments/audio-message.ts @@ -1,7 +1,7 @@ import { Attachment, type AttachmentFactoryOptions } from './attachment'; -import { pickProperties } from '../../utils/helpers'; import { AttachmentType, kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export interface IAudioMessageAttachmentPayload { id: number; @@ -17,11 +17,12 @@ export interface IAudioMessageAttachmentPayload { transcript_state?: 'done' | undefined; } -export type AudioMessageAttachmentOptions = - AttachmentFactoryOptions; +export type AudioMessageAttachmentOptions = AttachmentFactoryOptions; -export class AudioMessageAttachment - extends Attachment { +export class AudioMessageAttachment extends Attachment< + IAudioMessageAttachmentPayload, + AttachmentType.AUDIO_MESSAGE | 'audio_message' +> { /** * Constructor */ diff --git a/packages/vk-io/src/structures/attachments/audio.ts b/packages/vk-io/src/structures/attachments/audio.ts index de86e4eb2..de8a312fb 100644 --- a/packages/vk-io/src/structures/attachments/audio.ts +++ b/packages/vk-io/src/structures/attachments/audio.ts @@ -1,7 +1,7 @@ import { Attachment, type AttachmentFactoryOptions } from './attachment'; -import { pickProperties } from '../../utils/helpers'; import { AttachmentType, kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export interface IAudioAttachmentPayload { id: number; @@ -19,8 +19,7 @@ export interface IAudioAttachmentPayload { url?: string; } -export type AudioAttachmentOptions = - AttachmentFactoryOptions; +export type AudioAttachmentOptions = AttachmentFactoryOptions; export class AudioAttachment extends Attachment { /** @@ -44,8 +43,10 @@ export class AudioAttachment extends Attachment; +export type DocumentAttachmentOptions = AttachmentFactoryOptions; -export class DocumentAttachment - extends Attachment { +export class DocumentAttachment extends Attachment { /** * Constructor */ @@ -242,12 +240,6 @@ export class DocumentAttachment * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'title', - 'typeId', - 'createdAt', - 'extension', - 'url', - ]); + return pickProperties(this, ['title', 'typeId', 'createdAt', 'extension', 'url']); } } diff --git a/packages/vk-io/src/structures/attachments/external.ts b/packages/vk-io/src/structures/attachments/external.ts index bfa31df12..e60e8bb33 100644 --- a/packages/vk-io/src/structures/attachments/external.ts +++ b/packages/vk-io/src/structures/attachments/external.ts @@ -1,12 +1,11 @@ import { inspectable } from 'inspectable'; import type { API } from '../../api'; -import type { IAttachmentOptions, AttachmentFactoryOptions } from './attachment'; +import type { AttachmentFactoryOptions, IAttachmentOptions } from './attachment'; -import { kSerializeData, type AttachmentType } from '../../utils/constants'; +import { type AttachmentType, kSerializeData } from '../../utils/constants'; -export type IExternalAttachmentOptions = -IAttachmentOptions; +export type IExternalAttachmentOptions = IAttachmentOptions; export type ExternalAttachmentFactoryOptions

= AttachmentFactoryOptions

; @@ -72,7 +71,6 @@ export class ExternalAttachment

instance.toJSON(), - stringify: (instance, payload, context): string => ( - `${context.stylize(instance.constructor.name, 'special')} ${context.inspect(payload)}` - ), + stringify: (instance, payload, context): string => + `${context.stylize(instance.constructor.name, 'special')} ${context.inspect(payload)}`, }); diff --git a/packages/vk-io/src/structures/attachments/gift.ts b/packages/vk-io/src/structures/attachments/gift.ts index fce37c58d..0fefafd84 100644 --- a/packages/vk-io/src/structures/attachments/gift.ts +++ b/packages/vk-io/src/structures/attachments/gift.ts @@ -6,11 +6,9 @@ export interface IGiftAttachmentPayload { id: number; } -export type GiftAttachmentOptions = - ExternalAttachmentFactoryOptions; +export type GiftAttachmentOptions = ExternalAttachmentFactoryOptions; -export class GiftAttachment - extends ExternalAttachment { +export class GiftAttachment extends ExternalAttachment { /** * Constructor */ diff --git a/packages/vk-io/src/structures/attachments/graffiti.ts b/packages/vk-io/src/structures/attachments/graffiti.ts index bca274a95..b98d71d32 100644 --- a/packages/vk-io/src/structures/attachments/graffiti.ts +++ b/packages/vk-io/src/structures/attachments/graffiti.ts @@ -1,7 +1,7 @@ import { Attachment, type AttachmentFactoryOptions } from './attachment'; -import { pickProperties } from '../../utils/helpers'; import { AttachmentType, kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export interface IGraffitiAttachmentPayload { id: number; @@ -13,11 +13,9 @@ export interface IGraffitiAttachmentPayload { url?: string; } -export type GraffitiAttachmentOptions = - AttachmentFactoryOptions; +export type GraffitiAttachmentOptions = AttachmentFactoryOptions; -export class GraffitiAttachment - extends Attachment { +export class GraffitiAttachment extends Attachment { /** * Constructor */ @@ -73,10 +71,6 @@ export class GraffitiAttachment * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'height', - 'width', - 'url', - ]); + return pickProperties(this, ['height', 'width', 'url']); } } diff --git a/packages/vk-io/src/structures/attachments/helpers.ts b/packages/vk-io/src/structures/attachments/helpers.ts index 8734bfec4..7bcfb8862 100644 --- a/packages/vk-io/src/structures/attachments/helpers.ts +++ b/packages/vk-io/src/structures/attachments/helpers.ts @@ -1,22 +1,21 @@ import { type Attachment, + AudioAttachment, + AudioMessageAttachment, + DocumentAttachment, type ExternalAttachment, - - PollAttachment, GiftAttachment, - WallAttachment, + GraffitiAttachment, LinkAttachment, + MarketAlbumAttachment, + MarketAttachment, PhotoAttachment, - AudioAttachment, + PollAttachment, + StickerAttachment, StoryAttachment, VideoAttachment, - MarketAttachment, - StickerAttachment, - GraffitiAttachment, - DocumentAttachment, + WallAttachment, WallReplyAttachment, - MarketAlbumAttachment, - AudioMessageAttachment, } from '.'; import type { API } from '../../api'; @@ -47,10 +46,7 @@ const attachmentsTypes = { /** * Transform raw attachments to wrapper */ -export const transformAttachments = ( - rawAttachments: any[], - api: API, -): (Attachment | ExternalAttachment)[] => { +export const transformAttachments = (rawAttachments: any[], api: API): (Attachment | ExternalAttachment)[] => { const attachments: (Attachment | ExternalAttachment)[] = []; for (const rawAttachment of rawAttachments) { diff --git a/packages/vk-io/src/structures/attachments/link.ts b/packages/vk-io/src/structures/attachments/link.ts index 0597ca0f6..1c8e19ec4 100644 --- a/packages/vk-io/src/structures/attachments/link.ts +++ b/packages/vk-io/src/structures/attachments/link.ts @@ -1,8 +1,8 @@ import { ExternalAttachment, type ExternalAttachmentFactoryOptions } from './external'; -import { pickProperties } from '../../utils/helpers'; -import { PhotoAttachment, type IPhotoAttachmentPayload } from './photo'; import { AttachmentType, kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; +import { type IPhotoAttachmentPayload, PhotoAttachment } from './photo'; const kPhoto = Symbol('kPhoto'); @@ -24,11 +24,9 @@ export interface ILinkAttachmentPayload { photo?: IPhotoAttachmentPayload; } -export type LinkAttachmentOptions = - ExternalAttachmentFactoryOptions; +export type LinkAttachmentOptions = ExternalAttachmentFactoryOptions; -export class LinkAttachment - extends ExternalAttachment { +export class LinkAttachment extends ExternalAttachment { protected [kPhoto]: PhotoAttachment | undefined; /** @@ -109,14 +107,6 @@ export class LinkAttachment * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'title', - 'caption', - 'description', - 'url', - 'product', - 'button', - 'photo', - ]); + return pickProperties(this, ['title', 'caption', 'description', 'url', 'product', 'button', 'photo']); } } diff --git a/packages/vk-io/src/structures/attachments/market-album.ts b/packages/vk-io/src/structures/attachments/market-album.ts index f62156ecc..ec829bbf7 100644 --- a/packages/vk-io/src/structures/attachments/market-album.ts +++ b/packages/vk-io/src/structures/attachments/market-album.ts @@ -1,7 +1,7 @@ import { Attachment, type AttachmentFactoryOptions } from './attachment'; import { AttachmentType } from '../../utils/constants'; -import { PhotoAttachment, type IPhotoAttachmentPayload } from './photo'; +import { type IPhotoAttachmentPayload, PhotoAttachment } from './photo'; export interface IMarketAlbumAttachmentPayload { id: number; @@ -13,11 +13,12 @@ export interface IMarketAlbumAttachmentPayload { count?: number; updated_time?: number; } -export type MarketAlbumAttachmentOptions = - AttachmentFactoryOptions; +export type MarketAlbumAttachmentOptions = AttachmentFactoryOptions; -export class MarketAlbumAttachment - extends Attachment { +export class MarketAlbumAttachment extends Attachment< + IMarketAlbumAttachmentPayload, + AttachmentType.MARKET_ALBUM | 'market_album' +> { public photo?: PhotoAttachment; /** diff --git a/packages/vk-io/src/structures/attachments/market.ts b/packages/vk-io/src/structures/attachments/market.ts index 6725ea405..0f5a19935 100644 --- a/packages/vk-io/src/structures/attachments/market.ts +++ b/packages/vk-io/src/structures/attachments/market.ts @@ -49,11 +49,9 @@ export interface IMarketAttachmentPayload { button_title?: string; } -export type MarketAttachmentOptions = - AttachmentFactoryOptions; +export type MarketAttachmentOptions = AttachmentFactoryOptions; -export class MarketAttachment - extends Attachment { +export class MarketAttachment extends Attachment { public photos?: PhotoAttachment[]; /** @@ -219,12 +217,13 @@ export class MarketAttachment this.payload = payload; if (this.payload.photos) { - this.photos = this.payload.photos.map(photo => ( - new PhotoAttachment({ - api: this.api, - payload: photo, - }) - )); + this.photos = this.payload.photos.map( + photo => + new PhotoAttachment({ + api: this.api, + payload: photo, + }), + ); } } } diff --git a/packages/vk-io/src/structures/attachments/photo.ts b/packages/vk-io/src/structures/attachments/photo.ts index 6b4d3cf19..9fce3108b 100644 --- a/packages/vk-io/src/structures/attachments/photo.ts +++ b/packages/vk-io/src/structures/attachments/photo.ts @@ -1,7 +1,7 @@ import { Attachment, type AttachmentFactoryOptions } from './attachment'; -import { pickProperties } from '../../utils/helpers'; import { AttachmentType, kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; const SMALL_SIZES = ['m', 's']; const MEDIUM_SIZES = ['y', 'r', 'q', 'p', ...SMALL_SIZES]; @@ -28,8 +28,7 @@ export interface IPhotoAttachmentPayload { height?: number; } -export type PhotoAttachmentOptions = - AttachmentFactoryOptions; +export type PhotoAttachmentOptions = AttachmentFactoryOptions; export class PhotoAttachment extends Attachment { /** @@ -58,7 +57,7 @@ export class PhotoAttachment extends Attachment ( - sizes.find((size): boolean => size.type === sizeType) - )) + .map((sizeType): IPhotoSize | undefined => sizes.find((size): boolean => size.type === sizeType)) .filter(Boolean) as IPhotoSize[]; } diff --git a/packages/vk-io/src/structures/attachments/poll.ts b/packages/vk-io/src/structures/attachments/poll.ts index 576f15571..9cd75302d 100644 --- a/packages/vk-io/src/structures/attachments/poll.ts +++ b/packages/vk-io/src/structures/attachments/poll.ts @@ -1,8 +1,8 @@ import { Attachment, type AttachmentFactoryOptions } from './attachment'; -import { pickProperties } from '../../utils/helpers'; import { AttachmentType, kSerializeData } from '../../utils/constants'; -import { PhotoAttachment, type IPhotoAttachmentPayload } from './photo'; +import { pickProperties } from '../../utils/helpers'; +import { type IPhotoAttachmentPayload, PhotoAttachment } from './photo'; export interface IPollAttachmentPayload { id: number; @@ -46,8 +46,7 @@ export interface IPollAttachmentPayload { photo?: IPhotoAttachmentPayload; } -export type PollAttachmentOptions = - AttachmentFactoryOptions; +export type PollAttachmentOptions = AttachmentFactoryOptions; export class PollAttachment extends Attachment { public photo?: PhotoAttachment; @@ -85,7 +84,7 @@ export class PollAttachment extends Attachment; +export type StickerAttachmentOptions = ExternalAttachmentFactoryOptions; -export class StickerAttachment - extends ExternalAttachment { +export class StickerAttachment extends ExternalAttachment< + IStickerAttachmentPayload, + AttachmentType.STICKER | 'sticker' +> { /** * Constructor */ @@ -64,11 +65,6 @@ export class StickerAttachment * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'id', - 'productId', - 'images', - 'imagesWithBackground', - ]); + return pickProperties(this, ['id', 'productId', 'images', 'imagesWithBackground']); } } diff --git a/packages/vk-io/src/structures/attachments/story.ts b/packages/vk-io/src/structures/attachments/story.ts index a2beac06a..0bff68bb2 100644 --- a/packages/vk-io/src/structures/attachments/story.ts +++ b/packages/vk-io/src/structures/attachments/story.ts @@ -1,9 +1,9 @@ import { Attachment, type AttachmentFactoryOptions } from './attachment'; -import { pickProperties } from '../../utils/helpers'; import { AttachmentType, kSerializeData } from '../../utils/constants'; -import { PhotoAttachment, type IPhotoAttachmentPayload } from './photo'; -import { VideoAttachment, type IVideoAttachmentPayload } from './video'; +import { pickProperties } from '../../utils/helpers'; +import { type IPhotoAttachmentPayload, PhotoAttachment } from './photo'; +import { type IVideoAttachmentPayload, VideoAttachment } from './video'; export interface IStoryAttachmentPayload { id: number; @@ -65,8 +65,7 @@ const kPhoto = Symbol('photo'); const kParentStory = Symbol('parentStory'); -export type StoryAttachmentOptions = - AttachmentFactoryOptions; +export type StoryAttachmentOptions = AttachmentFactoryOptions; export class StoryAttachment extends Attachment { protected [kPhoto]: PhotoAttachment | undefined; @@ -98,7 +97,9 @@ export class StoryAttachment extends Attachment; +export type VideoAttachmentOptions = AttachmentFactoryOptions; export class VideoAttachment extends Attachment { /** diff --git a/packages/vk-io/src/structures/attachments/wall-reply.ts b/packages/vk-io/src/structures/attachments/wall-reply.ts index ff3438b87..dddca1016 100644 --- a/packages/vk-io/src/structures/attachments/wall-reply.ts +++ b/packages/vk-io/src/structures/attachments/wall-reply.ts @@ -26,10 +26,12 @@ export interface IWallReplyAttachmentPayload { }; } -export type WallReplyAttachmentOptions = - ExternalAttachmentFactoryOptions; +export type WallReplyAttachmentOptions = ExternalAttachmentFactoryOptions; -export class WallReplyAttachment extends ExternalAttachment { +export class WallReplyAttachment extends ExternalAttachment< + IWallReplyAttachmentPayload, + AttachmentType.WALL_REPLY | 'wall_reply' +> { public attachments: (Attachment | ExternalAttachment)[]; /** diff --git a/packages/vk-io/src/structures/attachments/wall.ts b/packages/vk-io/src/structures/attachments/wall.ts index 59a16732a..32b0ff2f2 100644 --- a/packages/vk-io/src/structures/attachments/wall.ts +++ b/packages/vk-io/src/structures/attachments/wall.ts @@ -1,10 +1,10 @@ +import { Attachmentable } from '../shared'; import { Attachment, type AttachmentFactoryOptions } from './attachment'; import type { ExternalAttachment } from './external'; -import { Attachmentable } from '../shared'; -import { transformAttachments } from './helpers'; import { AttachmentType, kSerializeData } from '../../utils/constants'; -import { pickProperties, applyMixins } from '../../utils/helpers'; +import { applyMixins, pickProperties } from '../../utils/helpers'; +import { transformAttachments } from './helpers'; const kAttachments = Symbol('attachments'); const kCopyHistoryAttachments = Symbol('copyHistoryAttachments'); @@ -81,8 +81,7 @@ export interface IWallAttachmentPayload { postponed_id?: number; } -export type WallAttachmentOptions = - AttachmentFactoryOptions; +export type WallAttachmentOptions = AttachmentFactoryOptions; // biome-ignore lint/suspicious/noUnsafeDeclarationMerging: apply mixins class WallAttachment extends Attachment { protected [kAttachments]!: (Attachment | ExternalAttachment)[]; @@ -112,7 +111,9 @@ class WallAttachment extends Attachment 0 - : undefined; + return commentsCount !== undefined ? commentsCount > 0 : undefined; } /** @@ -452,12 +451,13 @@ class WallAttachment extends Attachment ( - new WallAttachment({ - api: this.api, - payload: history, - }) - )); + this[kCopyHistoryAttachments] = (payload.copy_history || []).map( + (history): WallAttachment => + new WallAttachment({ + api: this.api, + payload: history, + }), + ); } /** diff --git a/packages/vk-io/src/structures/contexts/comment.ts b/packages/vk-io/src/structures/contexts/comment.ts index 7fd48d558..de4dd22ae 100644 --- a/packages/vk-io/src/structures/contexts/comment.ts +++ b/packages/vk-io/src/structures/contexts/comment.ts @@ -1,12 +1,12 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; import { VKError } from '../../errors'; import { Attachmentable } from '../shared/attachmentable'; import { kSerializeData } from '../../utils/constants'; +import { applyMixins, pickProperties } from '../../utils/helpers'; import { transformAttachments } from '../attachments/helpers'; -import { pickProperties, applyMixins } from '../../utils/helpers'; export interface ICommentContextPayload { id: number; @@ -32,59 +32,51 @@ export interface ICommentContextPayload { likes?: object; } -export type CommentContextOptions = - ContextFactoryOptions; +export type CommentContextOptions = ContextFactoryOptions; export type CommentContextType = 'comment'; export type CommentContextSubType = -'photo_comment' -| 'video_comment' -| 'wall_reply' -| 'board_comment' -| 'market_comment' -| 'photo_comment_new' -| 'photo_comment_edit' -| 'photo_comment_delete' -| 'photo_comment_restore' -| 'video_comment_new' -| 'video_comment_edit' -| 'video_comment_delete' -| 'video_comment_restore' -| 'wall_reply_new' -| 'wall_reply_edit' -| 'wall_reply_restore' -| 'wall_reply_delete' -| 'board_comment_new' -| 'board_comment_edit' -| 'board_comment_delete' -| 'board_comment_restore' -| 'market_comment_new' -| 'market_comment_edit' -| 'market_comment_delete' -| 'market_comment_restore'; - -class CommentContext - extends Context< + | 'photo_comment' + | 'video_comment' + | 'wall_reply' + | 'board_comment' + | 'market_comment' + | 'photo_comment_new' + | 'photo_comment_edit' + | 'photo_comment_delete' + | 'photo_comment_restore' + | 'video_comment_new' + | 'video_comment_edit' + | 'video_comment_delete' + | 'video_comment_restore' + | 'wall_reply_new' + | 'wall_reply_edit' + | 'wall_reply_restore' + | 'wall_reply_delete' + | 'board_comment_new' + | 'board_comment_edit' + | 'board_comment_delete' + | 'board_comment_restore' + | 'market_comment_new' + | 'market_comment_edit' + | 'market_comment_delete' + | 'market_comment_restore'; + +class CommentContext extends Context< ICommentContextPayload, S, CommentContextType, CommentContextSubType - > { +> { public constructor(options: CommentContextOptions) { - const initiator = (options.updateType as string).substring( - 0, - (options.updateType as string).lastIndexOf('_'), - ); + const initiator = (options.updateType as string).substring(0, (options.updateType as string).lastIndexOf('_')); super({ ...options, type: 'comment', - subTypes: [ - initiator as CommentContextSubType, - options.updateType as CommentContextSubType, - ], + subTypes: [initiator as CommentContextSubType, options.updateType as CommentContextSubType], }); this.attachments = transformAttachments(this.payload.attachments || [], this.api); @@ -204,10 +196,7 @@ class CommentContext * identifier of who wrote the comment */ public get fromId(): number | undefined { - return ( - this.payload.from_id - || this.payload.user_id - ); + return this.payload.from_id || this.payload.user_id; } /** @@ -231,13 +220,7 @@ class CommentContext const { payload } = this; // biome-ignore lint/style/noNonNullAssertion: one of properties is present - return ( - payload.photo_id - || payload.video_id - || payload.post_id - || payload.topic_id - || payload.item_id - )!; + return (payload.photo_id || payload.video_id || payload.post_id || payload.topic_id || payload.item_id)!; } /** @@ -247,14 +230,12 @@ class CommentContext const { payload } = this; // biome-ignore lint/style/noNonNullAssertion: one of properties is present - return ( - payload.owner_id - || payload.photo_owner_id - || payload.video_owner_id - || payload.post_owner_id - || payload.topic_owner_id - || payload.market_owner_id - )!; + return (payload.owner_id || + payload.photo_owner_id || + payload.video_owner_id || + payload.post_owner_id || + payload.topic_owner_id || + payload.market_owner_id)!; } /** @@ -290,10 +271,12 @@ class CommentContext */ editComment(options: { message?: string; attachments?: any }): Promise { if (this.isDelete) { - return Promise.reject(new VKError({ - message: 'Comment is deleted', - code: 'ALREADY_DELETED', - })); + return Promise.reject( + new VKError({ + message: 'Comment is deleted', + code: 'ALREADY_DELETED', + }), + ); } if (this.isBoardComment) { @@ -330,10 +313,12 @@ class CommentContext return this.api.market.editComment(params); } - return Promise.reject(new VKError({ - message: 'Unsupported event for editing comment', - code: 'UNSUPPORTED_EVENT', - })); + return Promise.reject( + new VKError({ + message: 'Unsupported event for editing comment', + code: 'UNSUPPORTED_EVENT', + }), + ); } /** @@ -341,10 +326,12 @@ class CommentContext */ deleteComment(): Promise { if (this.isDelete) { - return Promise.reject(new VKError({ - message: 'Comment is deleted', - code: 'ALREADY_DELETED', - })); + return Promise.reject( + new VKError({ + message: 'Comment is deleted', + code: 'ALREADY_DELETED', + }), + ); } if (this.isBoardComment) { @@ -377,10 +364,12 @@ class CommentContext return this.api.market.deleteComment(params); } - return Promise.reject(new VKError({ - message: 'Unsupported event for deleting comment', - code: 'UNSUPPORTED_EVENT', - })); + return Promise.reject( + new VKError({ + message: 'Unsupported event for deleting comment', + code: 'UNSUPPORTED_EVENT', + }), + ); } /** @@ -412,9 +401,7 @@ class CommentContext 'likes', ]; - const filtredEmptyProperties = properties.filter(property => ( - this[property] !== undefined - )); + const filtredEmptyProperties = properties.filter(property => this[property] !== undefined); return pickProperties(this, filtredEmptyProperties); } diff --git a/packages/vk-io/src/structures/contexts/context.ts b/packages/vk-io/src/structures/contexts/context.ts index 24af21f38..f2c6522f2 100644 --- a/packages/vk-io/src/structures/contexts/context.ts +++ b/packages/vk-io/src/structures/contexts/context.ts @@ -2,16 +2,11 @@ import { inspectable } from 'inspectable'; import type { API } from '../../api'; import type { Upload } from '../../upload'; -import { kSerializeData, type UpdateSource } from '../../utils/constants'; +import { type UpdateSource, kSerializeData } from '../../utils/constants'; export type ContextDefaultState = Record; -export interface IContextOptions< - P, - S, - Type extends string = string, - SubType extends string = string -> { +export interface IContextOptions { api: API; upload: Upload; @@ -27,14 +22,13 @@ export interface IContextOptions< groupId?: number; } -export type ContextFactoryOptions = - Omit, 'type' | 'subTypes'>; +export type ContextFactoryOptions = Omit, 'type' | 'subTypes'>; export class Context< P = object, S = ContextDefaultState, Type extends string = string, - SubType extends string = string + SubType extends string = string, > { public type: Type; @@ -62,7 +56,7 @@ export class Context< this.subTypes = options.subTypes; this.payload = options.payload; - this.state = options.state || {} as S; + this.state = options.state || ({} as S); this.$groupId = options.groupId; } @@ -78,17 +72,13 @@ export class Context< * Checks whether the context of some of these types */ public is(rawTypes: (Type | SubType)[]): boolean { - const types = !Array.isArray(rawTypes) - ? [rawTypes] - : rawTypes; + const types = !Array.isArray(rawTypes) ? [rawTypes] : rawTypes; if (types.includes(this.type)) { return true; } - return this.subTypes.some((type): boolean => ( - types.includes(type) - )); + return this.subTypes.some((type): boolean => types.includes(type)); } /** @@ -116,7 +106,6 @@ export class Context< inspectable(Context, { serialize: instance => instance.toJSON(), - stringify: (instance, payload, context): string => ( - `${context.stylize(instance.constructor.name, 'special')} ${context.inspect(payload)}` - ), + stringify: (instance, payload, context): string => + `${context.stylize(instance.constructor.name, 'special')} ${context.inspect(payload)}`, }); diff --git a/packages/vk-io/src/structures/contexts/dialog-flags.ts b/packages/vk-io/src/structures/contexts/dialog-flags.ts index f7eb49a55..0faf0f3f8 100644 --- a/packages/vk-io/src/structures/contexts/dialog-flags.ts +++ b/packages/vk-io/src/structures/contexts/dialog-flags.ts @@ -1,15 +1,13 @@ import type { Params } from '../../api'; -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type DialogFlagsContextType = 'dialog_flags'; -export type DialogFlagsContextSubType = -'dialog_flags_add' -| 'dialog_flags_delete'; +export type DialogFlagsContextSubType = 'dialog_flags_add' | 'dialog_flags_delete'; const subTypes: Record = { 10: 'dialog_flags_delete', @@ -19,7 +17,7 @@ const subTypes: Record = { /* eslint-disable no-bitwise */ enum DialogFlag { IMPORTANT = 1 << 0, - UNANSWERED = 1 << 1 + UNANSWERED = 1 << 1, } /* eslint-enable no-bitwise */ @@ -28,16 +26,14 @@ export interface IDialogFlagsContextPayload { flags: number; } -export type DialogFlagsContextOptions = - ContextFactoryOptions; +export type DialogFlagsContextOptions = ContextFactoryOptions; -export class DialogFlagsContext - extends Context< +export class DialogFlagsContext extends Context< IDialogFlagsContextPayload, S, DialogFlagsContextType, DialogFlagsContextSubType - > { +> { public constructor(options: DialogFlagsContextOptions) { const [eventId, peerId, flags] = options.payload; @@ -45,9 +41,7 @@ export class DialogFlagsContext ...options, type: 'dialog_flags', - subTypes: [ - subTypes[eventId], - ], + subTypes: [subTypes[eventId]], payload: { peer_id: peerId, @@ -87,9 +81,7 @@ export class DialogFlagsContext /** * Marks the conversation as answered or unchecked */ - public markAsAnsweredConversation( - params: Params.MessagesMarkAsAnsweredConversationParams, - ): Promise { + public markAsAnsweredConversation(params: Params.MessagesMarkAsAnsweredConversationParams): Promise { return this.api.messages.markAsAnsweredConversation({ ...params, @@ -100,9 +92,7 @@ export class DialogFlagsContext /** * Marks the conversation as important or removes the mark */ - public markAsImportantConversation( - params: Params.MessagesMarkAsImportantConversationParams, - ): Promise { + public markAsImportantConversation(params: Params.MessagesMarkAsImportantConversationParams): Promise { return this.api.messages.markAsImportantConversation({ ...params, @@ -118,11 +108,6 @@ export class DialogFlagsContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'peerId', - 'flags', - 'isImportant', - 'isUnanswered', - ]); + return pickProperties(this, ['peerId', 'flags', 'isImportant', 'isUnanswered']); } } diff --git a/packages/vk-io/src/structures/contexts/dialog-messages.ts b/packages/vk-io/src/structures/contexts/dialog-messages.ts index f6953d481..02f4f5646 100644 --- a/packages/vk-io/src/structures/contexts/dialog-messages.ts +++ b/packages/vk-io/src/structures/contexts/dialog-messages.ts @@ -1,7 +1,7 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type DialogMessagesContextType = 'dialog_messages'; @@ -15,16 +15,14 @@ export interface IDialogMessagesContextPayload { peer_id: number; } -export type DialogMessagesContextOptions = - ContextFactoryOptions; +export type DialogMessagesContextOptions = ContextFactoryOptions; -export class DialogMessagesContext - extends Context< +export class DialogMessagesContext extends Context< IDialogMessagesContextPayload, S, DialogMessagesContextType, DialogMessagesContextSubType - > { +> { public constructor(options: DialogMessagesContextOptions) { const [eventId, peerId, localId] = options.payload; @@ -32,9 +30,7 @@ export class DialogMessagesContext ...options, type: 'dialog_messages', - subTypes: [ - subTypes[eventId], - ], + subTypes: [subTypes[eventId]], payload: { peer_id: peerId, @@ -74,11 +70,6 @@ export class DialogMessagesContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'peerId', - 'localId', - 'isDelete', - 'isRestore', - ]); + return pickProperties(this, ['peerId', 'localId', 'isDelete', 'isRestore']); } } diff --git a/packages/vk-io/src/structures/contexts/dialog-notification-settings.ts b/packages/vk-io/src/structures/contexts/dialog-notification-settings.ts index 863f98a90..5c804f1d1 100644 --- a/packages/vk-io/src/structures/contexts/dialog-notification-settings.ts +++ b/packages/vk-io/src/structures/contexts/dialog-notification-settings.ts @@ -1,12 +1,12 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type DialogNotificationSettingsContextType = 'dialog_notification_settings'; export type DialogNotificationSettingsContextSubType = - 'dialog_notification_settings_subscribe' + | 'dialog_notification_settings_subscribe' | 'dialog_notification_settings_unsubscribe'; export interface IDialogNotificationSettingsContextPayload { @@ -15,16 +15,17 @@ export interface IDialogNotificationSettingsContextPayload { disabled_until: number; } -export type DialogNotificationSettingsContextOptions = - ContextFactoryOptions<[number, IDialogNotificationSettingsContextPayload], S>; - -export class DialogNotificationSettingsContext - extends Context< - IDialogNotificationSettingsContextPayload, - S, - DialogNotificationSettingsContextType, - DialogNotificationSettingsContextSubType - > { +export type DialogNotificationSettingsContextOptions = ContextFactoryOptions< + [number, IDialogNotificationSettingsContextPayload], + S +>; + +export class DialogNotificationSettingsContext extends Context< + IDialogNotificationSettingsContextPayload, + S, + DialogNotificationSettingsContextType, + DialogNotificationSettingsContextSubType +> { public constructor(options: DialogNotificationSettingsContextOptions) { const [, payload] = options.payload; @@ -83,12 +84,6 @@ export class DialogNotificationSettingsContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'peerId', - 'hasSound', - 'disabledUntil', - 'isSubscribed', - 'isUnsubscribed', - ]); + return pickProperties(this, ['peerId', 'hasSound', 'disabledUntil', 'isSubscribed', 'isUnsubscribed']); } } diff --git a/packages/vk-io/src/structures/contexts/donut-subscription-price.ts b/packages/vk-io/src/structures/contexts/donut-subscription-price.ts index 6de677a5b..bdb43fb74 100644 --- a/packages/vk-io/src/structures/contexts/donut-subscription-price.ts +++ b/packages/vk-io/src/structures/contexts/donut-subscription-price.ts @@ -1,7 +1,7 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type DonutSubscriptionPriceContextType = 'donut_subscription_price'; @@ -16,24 +16,20 @@ export interface IDonutSubscriptionPriceContextPayload { amount_diff_without_fee: number; } -export type DonutSubscriptionPriceContextOptions = - ContextFactoryOptions; +export type DonutSubscriptionPriceContextOptions = ContextFactoryOptions; -export class DonutSubscriptionPriceContext - extends Context< +export class DonutSubscriptionPriceContext extends Context< IDonutSubscriptionPriceContextPayload, S, DonutSubscriptionPriceContextType, DonutSubscriptionPriceContextSubType - > { +> { public constructor(options: DonutSubscriptionPriceContextOptions) { super({ ...options, type: 'donut_subscription_price', - subTypes: [ - options.updateType as DonutSubscriptionPriceContextSubType, - ], + subTypes: [options.updateType as DonutSubscriptionPriceContextSubType], }); } diff --git a/packages/vk-io/src/structures/contexts/donut-subscription.ts b/packages/vk-io/src/structures/contexts/donut-subscription.ts index b80710fd7..51a59fea1 100644 --- a/packages/vk-io/src/structures/contexts/donut-subscription.ts +++ b/packages/vk-io/src/structures/contexts/donut-subscription.ts @@ -1,15 +1,15 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type DonutSubscriptionContextType = 'donut_subscription'; export type DonutSubscriptionContextSubType = -'donut_subscription_create' -| 'donut_subscription_prolonged' -| 'donut_subscription_expired' -| 'donut_subscription_cancelled'; + | 'donut_subscription_create' + | 'donut_subscription_prolonged' + | 'donut_subscription_expired' + | 'donut_subscription_cancelled'; export interface IDonutSubscriptionContextPayload { user_id: number; @@ -18,24 +18,20 @@ export interface IDonutSubscriptionContextPayload { amount_without_fee?: number; } -export type DonutSubscriptionContextOptions = - ContextFactoryOptions; +export type DonutSubscriptionContextOptions = ContextFactoryOptions; -export class DonutSubscriptionContext - extends Context< +export class DonutSubscriptionContext extends Context< IDonutSubscriptionContextPayload, S, DonutSubscriptionContextType, DonutSubscriptionContextSubType - > { +> { public constructor(options: DonutSubscriptionContextOptions) { super({ ...options, type: 'donut_subscription', - subTypes: [ - options.updateType as DonutSubscriptionContextSubType, - ], + subTypes: [options.updateType as DonutSubscriptionContextSubType], }); } @@ -78,7 +74,7 @@ export class DonutSubscriptionContext * Returns the amount */ public get amount(): number { - // biome-ignore lint/style/noNonNullAssertion: always present + // biome-ignore lint/style/noNonNullAssertion: always present return this.payload.amount!; } diff --git a/packages/vk-io/src/structures/contexts/donut-withdraw.ts b/packages/vk-io/src/structures/contexts/donut-withdraw.ts index e5795e45d..29d7df676 100644 --- a/packages/vk-io/src/structures/contexts/donut-withdraw.ts +++ b/packages/vk-io/src/structures/contexts/donut-withdraw.ts @@ -1,13 +1,11 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type DonutWithdrawContextType = 'donut_withdraw'; -export type DonutWithdrawContextSubType = -'donut_money_withdraw' -| 'donut_money_withdraw_error'; +export type DonutWithdrawContextSubType = 'donut_money_withdraw' | 'donut_money_withdraw_error'; export interface IDonutWithdrawContextPayload { reason?: string; @@ -16,24 +14,20 @@ export interface IDonutWithdrawContextPayload { amount_without_fee?: number; } -export type DonutWithdrawContextOptions = - ContextFactoryOptions; +export type DonutWithdrawContextOptions = ContextFactoryOptions; -export class DonutWithdrawContext - extends Context< +export class DonutWithdrawContext extends Context< IDonutWithdrawContextPayload, S, DonutWithdrawContextType, DonutWithdrawContextSubType - > { +> { public constructor(options: DonutWithdrawContextOptions) { super({ ...options, type: 'donut_withdraw', - subTypes: [ - options.updateType as DonutWithdrawContextSubType, - ], + subTypes: [options.updateType as DonutWithdrawContextSubType], }); } @@ -71,11 +65,6 @@ export class DonutWithdrawContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'isError', - 'amount', - 'amountWithoutFee', - 'reason', - ]); + return pickProperties(this, ['isError', 'amount', 'amountWithoutFee', 'reason']); } } diff --git a/packages/vk-io/src/structures/contexts/friend-activity.ts b/packages/vk-io/src/structures/contexts/friend-activity.ts index 41bb15c61..c8730aaf3 100644 --- a/packages/vk-io/src/structures/contexts/friend-activity.ts +++ b/packages/vk-io/src/structures/contexts/friend-activity.ts @@ -1,14 +1,11 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type FriendActivityContextType = 'friend_activity'; -export type FriendActivityContextSubType = -'friend_online' -| 'friend_offline' -| 'friend_invisible'; +export type FriendActivityContextSubType = 'friend_online' | 'friend_offline' | 'friend_invisible'; const subTypes: Record = { 8: 'friend_online', @@ -23,16 +20,14 @@ export interface IFriendActivityContextPayload { app_id: number; } -export type FriendActivityContextOptions = - ContextFactoryOptions<[number, number, number, number, number], S>; +export type FriendActivityContextOptions = ContextFactoryOptions<[number, number, number, number, number], S>; -export class FriendActivityContext - extends Context< +export class FriendActivityContext extends Context< IFriendActivityContextPayload, S, FriendActivityContextType, FriendActivityContextSubType - > { +> { public constructor(options: FriendActivityContextOptions) { const [eventId, userId, extra, date, appId] = options.payload; @@ -40,9 +35,7 @@ export class FriendActivityContext ...options, type: 'friend_activity', - subTypes: [ - subTypes[eventId], - ], + subTypes: [subTypes[eventId]], payload: { user_id: -userId, @@ -71,9 +64,7 @@ export class FriendActivityContext * Checks that the user is invisible */ public get isInvisible(): boolean { - return this.subTypes.includes('friend_invisible') - ? Boolean(this.payload.extra) - : false; + return this.subTypes.includes('friend_invisible') ? Boolean(this.payload.extra) : false; } /** @@ -125,9 +116,7 @@ export class FriendActivityContext public get platform(): number | undefined { const { extra } = this.payload; - return extra !== -1 - ? extra - : undefined; + return extra !== -1 ? extra : undefined; } /** diff --git a/packages/vk-io/src/structures/contexts/group-member.ts b/packages/vk-io/src/structures/contexts/group-member.ts index e0ca66446..2857587cb 100644 --- a/packages/vk-io/src/structures/contexts/group-member.ts +++ b/packages/vk-io/src/structures/contexts/group-member.ts @@ -1,13 +1,11 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type GroupMemberContextType = 'group_member'; -export type GroupMemberContextSubType = -'group_leave' -| 'group_join'; +export type GroupMemberContextSubType = 'group_leave' | 'group_join'; export interface IGroupMemberContextPayload { user_id: number; @@ -15,24 +13,20 @@ export interface IGroupMemberContextPayload { join_type?: string; } -export type GroupMemberContextOptions = - ContextFactoryOptions; +export type GroupMemberContextOptions = ContextFactoryOptions; -export class GroupMemberContext - extends Context< +export class GroupMemberContext extends Context< IGroupMemberContextPayload, S, GroupMemberContextType, GroupMemberContextSubType - > { +> { public constructor(options: GroupMemberContextOptions) { super({ ...options, type: 'group_member', - subTypes: [ - options.updateType as GroupMemberContextSubType, - ], + subTypes: [options.updateType as GroupMemberContextSubType], }); } @@ -83,12 +77,6 @@ export class GroupMemberContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'userId', - 'joinType', - 'isJoin', - 'isLeave', - 'isSelfLeave', - ]); + return pickProperties(this, ['userId', 'joinType', 'isJoin', 'isLeave', 'isSelfLeave']); } } diff --git a/packages/vk-io/src/structures/contexts/group-update.ts b/packages/vk-io/src/structures/contexts/group-update.ts index b5cea3520..6e04688d8 100644 --- a/packages/vk-io/src/structures/contexts/group-update.ts +++ b/packages/vk-io/src/structures/contexts/group-update.ts @@ -1,17 +1,14 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; +import { type IPhotoAttachmentPayload, PhotoAttachment } from '../attachments'; import { Attachmentable } from '../shared/attachmentable'; -import { PhotoAttachment, type IPhotoAttachmentPayload } from '../attachments'; import { kSerializeData } from '../../utils/constants'; -import { pickProperties, applyMixins } from '../../utils/helpers'; +import { applyMixins, pickProperties } from '../../utils/helpers'; export type GroupUpdateContextType = 'group_update'; -export type GroupUpdateContextSubType = -'group_change_photo' -| 'group_officers_edit' -| 'group_change_settings'; +export type GroupUpdateContextSubType = 'group_change_photo' | 'group_officers_edit' | 'group_change_settings'; export interface IGroupUpdateContextPayload { user_id: number; @@ -22,31 +19,31 @@ export interface IGroupUpdateContextPayload { photo?: IPhotoAttachmentPayload; } -export type GroupUpdateContextOptions = - ContextFactoryOptions; +export type GroupUpdateContextOptions = ContextFactoryOptions; -class GroupUpdateContext - extends Context< +class GroupUpdateContext extends Context< IGroupUpdateContextPayload, S, GroupUpdateContextType, - GroupUpdateContextSubType> { + GroupUpdateContextSubType +> { public constructor(options: GroupUpdateContextOptions) { super({ ...options, type: 'group_update', - subTypes: [ - options.updateType as GroupUpdateContextSubType, - ], + subTypes: [options.updateType as GroupUpdateContextSubType], }); - this.attachments = options.updateType === 'group_change_photo' - ? [new PhotoAttachment({ - api: this.api, - payload: this.payload.photo as IPhotoAttachmentPayload, - })] - : []; + this.attachments = + options.updateType === 'group_change_photo' + ? [ + new PhotoAttachment({ + api: this.api, + payload: this.payload.photo as IPhotoAttachmentPayload, + }), + ] + : []; } /** @@ -109,14 +106,7 @@ class GroupUpdateContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'adminId', - 'userId', - 'oldLevel', - 'newLevel', - 'changes', - 'attachments', - ]); + return pickProperties(this, ['adminId', 'userId', 'oldLevel', 'newLevel', 'changes', 'attachments']); } } diff --git a/packages/vk-io/src/structures/contexts/group-user.ts b/packages/vk-io/src/structures/contexts/group-user.ts index c4c2bb20d..902407182 100644 --- a/packages/vk-io/src/structures/contexts/group-user.ts +++ b/packages/vk-io/src/structures/contexts/group-user.ts @@ -1,10 +1,10 @@ import type { Params } from '../../api'; -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; import { VKError } from '../../errors'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; /** * Causes of blocking @@ -19,9 +19,7 @@ const reasonNames = new Map([ export type GroupUserContextType = 'group_user'; -export type GroupUserContextSubType = -'user_block' -| 'user_unblock'; +export type GroupUserContextSubType = 'user_block' | 'user_unblock'; export interface IGroupUserContextPayload { admin_id: number; @@ -32,24 +30,20 @@ export interface IGroupUserContextPayload { by_end_date?: number; } -export type GroupUserContextOptions = - ContextFactoryOptions; +export type GroupUserContextOptions = ContextFactoryOptions; -export class GroupUserContext - extends Context< +export class GroupUserContext extends Context< IGroupUserContextPayload, S, GroupUserContextType, GroupUserContextSubType - > { +> { public constructor(options: GroupUserContextOptions) { super({ ...options, type: 'group_user', - subTypes: [ - options.updateType as GroupUserContextSubType, - ], + subTypes: [options.updateType as GroupUserContextSubType], }); } @@ -106,7 +100,7 @@ export class GroupUserContext const { reasonId } = this; if (!reasonId) { - return undefined + return undefined; } return reasonNames.get(reasonId); @@ -131,10 +125,12 @@ export class GroupUserContext */ ban(params: Partial): Promise { if (this.isBlocked) { - return Promise.reject(new VKError({ - message: 'User is blocked', - code: 'ALREADY_BANNED', - })); + return Promise.reject( + new VKError({ + message: 'User is blocked', + code: 'ALREADY_BANNED', + }), + ); } return this.api.groups.ban({ @@ -151,10 +147,12 @@ export class GroupUserContext */ unban(): Promise { if (this.isUnblocked) { - return Promise.reject(new VKError({ - message: 'User is not blocked', - code: 'ALREADY_UNBANNED', - })); + return Promise.reject( + new VKError({ + message: 'User is not blocked', + code: 'ALREADY_UNBANNED', + }), + ); } return this.api.groups.unban({ diff --git a/packages/vk-io/src/structures/contexts/helpers/transform-message.ts b/packages/vk-io/src/structures/contexts/helpers/transform-message.ts index 011143340..5ce8093c4 100644 --- a/packages/vk-io/src/structures/contexts/helpers/transform-message.ts +++ b/packages/vk-io/src/structures/contexts/helpers/transform-message.ts @@ -48,9 +48,7 @@ const attachmentHandlers = { url: raw[`${key}_url`], title: raw[`${key}_title`], description: raw[`${key}_desc`], - photo: photoId !== undefined - ? idToAttachmentPayload(photoId) - : undefined, + photo: photoId !== undefined ? idToAttachmentPayload(photoId) : undefined, }, }; }, @@ -75,51 +73,51 @@ const attachmentHandlers = { /** * Transform message to Object */ -export function transformMessage(rawMessage: [ - // type - number, - // conversation message id - number, - // flags - number, - // minor id - number, - // peer id - number, - // timestamp - number, - - // text - string, - - // additional - { - title?: string; - from?: string; - - emoji?: '1'; - has_template?: '1'; - is_expired?: '1'; - - source_act?: MessageContextPayloadEventType; - source_mid?: string; - source_message?: string; - source_chat_local_id?: string; - - payload?: string; - }, - // attachments - Record & { - fwd?: string; - reply?: string; - }, - // randomId - number, - // messageId - number, - // updateTimestamp - number -]): IMessageContextPayload['message'] { +export function transformMessage( + rawMessage: [ + // type + number, + // conversation message id + number, + // flags + number, + // minor id + number, + // peer id + number, + // timestamp + number, + // text + string, + // additional + { + title?: string; + from?: string; + + emoji?: '1'; + has_template?: '1'; + is_expired?: '1'; + + source_act?: MessageContextPayloadEventType; + source_mid?: string; + source_message?: string; + source_chat_local_id?: string; + + payload?: string; + }, + // attachments + Record & { + fwd?: string; + reply?: string; + }, + // randomId + number, + // messageId + number, + // updateTimestamp + number, + ], +): IMessageContextPayload['message'] { if (rawMessage[0] !== 10004) { // set minor id to 0 rawMessage.splice(3, 0, 0); @@ -146,9 +144,7 @@ export function transformMessage(rawMessage: [ update_time, text, random_id, - geo: attachments.geo !== undefined - ? {} - : undefined, + geo: attachments.geo !== undefined ? {} : undefined, payload: extra.payload, } as IMessageContextPayload['message']; @@ -171,9 +167,7 @@ export function transformMessage(rawMessage: [ type: extra.source_act, text: extra.source_message, - member_id: extra.source_mid - ? Number(extra.source_mid) - : undefined, + member_id: extra.source_mid ? Number(extra.source_mid) : undefined, }; } @@ -182,17 +176,9 @@ export function transformMessage(rawMessage: [ for (let i = 1, key = 'attach1'; attachments[key] !== undefined; i += 1, key = `attach${i}`) { const type = attachments[`${key}_type`] as string; - const handler = attachmentHandlers[type as keyof typeof attachmentHandlers] - || attachmentHandlers.default; - - message.attachments.push( - handler( - attachments, - key, - type, - i, - ), - ); + const handler = attachmentHandlers[type as keyof typeof attachmentHandlers] || attachmentHandlers.default; + + message.attachments.push(handler(attachments, key, type, i)); } if (attachments.reply !== undefined) { @@ -213,20 +199,22 @@ export function transformMessage(rawMessage: [ important: false, }; } else if (attachments.fwd !== undefined) { - message.fwd_messages = [{ - id: 0, - conversation_message_id: 0, - date: 0, - update_time: 0, - from_id: 0, - peer_id: 0, - out: 0, - text: '', - fwd_messages: [], - attachments: [], - random_id: 0, - important: false, - }]; + message.fwd_messages = [ + { + id: 0, + conversation_message_id: 0, + date: 0, + update_time: 0, + from_id: 0, + peer_id: 0, + out: 0, + text: '', + fwd_messages: [], + attachments: [], + random_id: 0, + important: false, + }, + ]; } return message; diff --git a/packages/vk-io/src/structures/contexts/like.ts b/packages/vk-io/src/structures/contexts/like.ts index 5c9920013..190f74ea4 100644 --- a/packages/vk-io/src/structures/contexts/like.ts +++ b/packages/vk-io/src/structures/contexts/like.ts @@ -1,7 +1,7 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type LikeContextType = 'like'; @@ -12,30 +12,35 @@ export interface ILikeContextPayload { object_id: number; object_owner_id: number; - object_type: 'video' | 'photo' | 'comment' | 'note' | 'topic_comment' | 'photo_comment' | 'video_comment' | 'market' | 'market_comment'; + object_type: + | 'video' + | 'photo' + | 'comment' + | 'note' + | 'topic_comment' + | 'photo_comment' + | 'video_comment' + | 'market' + | 'market_comment'; post_id: number; thread_reply_id: number; } -export type LikeContextOptions = - ContextFactoryOptions; +export type LikeContextOptions = ContextFactoryOptions; -export class LikeContext - extends Context< +export class LikeContext extends Context< ILikeContextPayload, S, LikeContextType, LikeContextSubType - > { +> { public constructor(options: LikeContextOptions) { super({ ...options, type: 'like', - subTypes: [ - options.updateType as LikeContextSubType, - ], + subTypes: [options.updateType as LikeContextSubType], }); } @@ -85,13 +90,6 @@ export class LikeContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'likerId', - 'objectId', - 'objectOwnerId', - 'objectType', - 'postId', - 'threadReplyId', - ]); + return pickProperties(this, ['likerId', 'objectId', 'objectOwnerId', 'objectType', 'postId', 'threadReplyId']); } } diff --git a/packages/vk-io/src/structures/contexts/market-order.ts b/packages/vk-io/src/structures/contexts/market-order.ts index a1f18553d..718edb3d8 100644 --- a/packages/vk-io/src/structures/contexts/market-order.ts +++ b/packages/vk-io/src/structures/contexts/market-order.ts @@ -1,9 +1,9 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; import { type IMarketAttachmentPayload, MarketAttachment } from '../attachments'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type MarketOrderContextType = 'market_order'; @@ -22,7 +22,7 @@ export interface IMarketOrderContextPayload { property_values: { variant_id: number; variant_name: string; - property_name : string; + property_name: string; }[]; cart_quantity: number; status: 0 | 1 | 2 | 3 | 4 | 5 | 6; @@ -46,21 +46,19 @@ export interface IMarketOrderContextPayload { recipient: { name: string; phone: string; - display_text : string; + display_text: string; }; date: number; } -export type MarketOrderContextOptions = - ContextFactoryOptions; +export type MarketOrderContextOptions = ContextFactoryOptions; -export class MarketOrderContext - extends Context< +export class MarketOrderContext extends Context< IMarketOrderContextPayload, S, MarketOrderContextType, MarketOrderContextSubType - > { +> { public previewOrderItems: MarketAttachment[]; public constructor(options: MarketOrderContextOptions) { @@ -68,17 +66,16 @@ export class MarketOrderContext ...options, type: 'market_order', - subTypes: [ - options.updateType as MarketOrderContextSubType, - ], + subTypes: [options.updateType as MarketOrderContextSubType], }); - this.previewOrderItems = this.payload.preview_order_items.map(market => ( - new MarketAttachment({ - api: this.api, - payload: market, - }) - )); + this.previewOrderItems = this.payload.preview_order_items.map( + market => + new MarketAttachment({ + api: this.api, + payload: market, + }), + ); } /** diff --git a/packages/vk-io/src/structures/contexts/message-event.ts b/packages/vk-io/src/structures/contexts/message-event.ts index d8625c1df..5e4b432e9 100644 --- a/packages/vk-io/src/structures/contexts/message-event.ts +++ b/packages/vk-io/src/structures/contexts/message-event.ts @@ -1,9 +1,9 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; import { type IMessageContextSendOptions, MessageContext } from './message'; -import { getRandomId, pickProperties } from '../../utils/helpers'; import { UpdateSource, kSerializeData } from '../../utils/constants'; +import { getRandomId, pickProperties } from '../../utils/helpers'; export interface IMessageEventShowSnackbar { type: 'show_snackbar'; @@ -22,10 +22,7 @@ export interface IMessageEventOpenApp { hash: string; } -export type MessageEventAction = -IMessageEventShowSnackbar -| IMessageEventOpenLink -| IMessageEventOpenApp; +export type MessageEventAction = IMessageEventShowSnackbar | IMessageEventOpenLink | IMessageEventOpenApp; export type MessageEventContextType = 'message_event'; @@ -39,24 +36,20 @@ export interface IMessageEventContextPayload { payload: any; } -export type MessageEventContextOptions = - ContextFactoryOptions; +export type MessageEventContextOptions = ContextFactoryOptions; -export class MessageEventContext - extends Context< +export class MessageEventContext extends Context< IMessageEventContextPayload, S, MessageEventContextType, MessageEventContextSubType - > { +> { public constructor(options: MessageEventContextOptions) { super({ ...options, type: 'message_event', - subTypes: [ - options.updateType as MessageEventContextSubType, - ], + subTypes: [options.updateType as MessageEventContextSubType], }); } @@ -119,15 +112,13 @@ export class MessageEventContext const options = { random_id: randomId, - ...( - typeof text !== 'object' - ? { - message: text, + ...(typeof text !== 'object' + ? { + message: text, - ...params, - } - : text - ), + ...params, + } + : text), } as IMessageContextSendOptions; if (this.$groupId !== undefined) { @@ -138,18 +129,19 @@ export class MessageEventContext const rawDestination = await this.api.messages.send(options); - const destination = typeof rawDestination !== 'number' - ? rawDestination[0] as { - peer_id : number; - message_id: number; - conversation_message_id: number; - error: number; - } - : { - peer_id: this.peer_id, - message_id: rawDestination, - conversation_message_id: 0, - }; + const destination = + typeof rawDestination !== 'number' + ? (rawDestination[0] as { + peer_id: number; + message_id: number; + conversation_message_id: number; + error: number; + }) + : { + peer_id: this.peer_id, + message_id: rawDestination, + conversation_message_id: 0, + }; const messageContext = new MessageContext({ api: this.api, @@ -190,12 +182,6 @@ export class MessageEventContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'userId', - 'conversationMessageId', - 'peerId', - 'eventId', - 'eventPayload', - ]); + return pickProperties(this, ['userId', 'conversationMessageId', 'peerId', 'eventId', 'eventPayload']); } } diff --git a/packages/vk-io/src/structures/contexts/message-flags.ts b/packages/vk-io/src/structures/contexts/message-flags.ts index 5423a1910..cb5121195 100644 --- a/packages/vk-io/src/structures/contexts/message-flags.ts +++ b/packages/vk-io/src/structures/contexts/message-flags.ts @@ -1,15 +1,13 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; import { MessageContext } from './message'; +import { UpdateSource, kSerializeData } from '../../utils/constants'; import { pickProperties } from '../../utils/helpers'; -import { kSerializeData, UpdateSource } from '../../utils/constants'; export type MessageFlagsContextType = 'message_flags'; -export type MessageFlagsContextSubType = -'message_flags_add' -| 'message_flags_delete'; +export type MessageFlagsContextSubType = 'message_flags_add' | 'message_flags_delete'; const subTypes: Record = { 2: 'message_flags_add', @@ -33,7 +31,7 @@ enum MessageFlag { INBOX_FROM_CHAT = 1 << 19, SILENT = 1 << 20, REPLIED = 1 << 21, - AUTO_READ = 1 << 23 + AUTO_READ = 1 << 23, } /* eslint-enable no-bitwise */ @@ -43,16 +41,14 @@ export interface IMessageFlagsContextPayload { flags: number; } -export type MessageFlagsContextOptions = -ContextFactoryOptions; +export type MessageFlagsContextOptions = ContextFactoryOptions; -export class MessageFlagsContext - extends Context< +export class MessageFlagsContext extends Context< IMessageFlagsContextPayload, S, MessageFlagsContextType, MessageFlagsContextSubType - > { +> { public message?: MessageContext; public constructor(options: MessageFlagsContextOptions) { @@ -62,9 +58,7 @@ export class MessageFlagsContext ...options, type: 'message_flags', - subTypes: [ - subTypes[eventId], - ], + subTypes: [subTypes[eventId]], payload: { peer_id: peerId, diff --git a/packages/vk-io/src/structures/contexts/message-subscription.ts b/packages/vk-io/src/structures/contexts/message-subscription.ts index 72c8134f9..cec656855 100644 --- a/packages/vk-io/src/structures/contexts/message-subscription.ts +++ b/packages/vk-io/src/structures/contexts/message-subscription.ts @@ -1,37 +1,31 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type MessageSubscriptionContextType = 'message_subscription'; -export type MessageSubscriptionContextSubType = -'message_allow' -| 'message_deny'; +export type MessageSubscriptionContextSubType = 'message_allow' | 'message_deny'; export interface IMessageSubscriptionContextPayload { user_id: number; key: string; } -export type MessageSubscriptionContextOptions = - ContextFactoryOptions; +export type MessageSubscriptionContextOptions = ContextFactoryOptions; -export class MessageSubscriptionContext - extends Context< +export class MessageSubscriptionContext extends Context< IMessageSubscriptionContextPayload, S, MessageSubscriptionContextType, MessageSubscriptionContextSubType - > { +> { public constructor(options: MessageSubscriptionContextOptions) { super({ ...options, type: 'message_subscription', - subTypes: [ - options.updateType as MessageSubscriptionContextSubType, - ], + subTypes: [options.updateType as MessageSubscriptionContextSubType], }); } @@ -67,11 +61,6 @@ export class MessageSubscriptionContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'userId', - 'key', - 'isSubscribed', - 'isUnsubscribed', - ]); + return pickProperties(this, ['userId', 'key', 'isSubscribed', 'isUnsubscribed']); } } diff --git a/packages/vk-io/src/structures/contexts/message.ts b/packages/vk-io/src/structures/contexts/message.ts index 6222af942..1d6c87b86 100644 --- a/packages/vk-io/src/structures/contexts/message.ts +++ b/packages/vk-io/src/structures/contexts/message.ts @@ -1,50 +1,40 @@ /* eslint-disable max-classes-per-file */ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; import type { Params } from '../../api'; +import { Attachmentable, type IAllAttachmentable, MessageForwardsCollection } from '../shared'; import { transformMessage } from './helpers/transform-message'; -import { MessageForwardsCollection, Attachmentable, type IAllAttachmentable } from '../shared'; import { type Attachment, type ExternalAttachment, transformAttachments } from '../attachments'; +import type { AllowArray } from '../../types'; +import type { IUploadSourceMedia } from '../../upload'; import { - unescapeHTML, - pickProperties, - getPeerType, - applyMixins, - getRandomId, -} from '../../utils/helpers'; -import { - UpdateSource, + type AttachmentType, + type AttachmentTypeString, MessageSource, PEER_CHAT_ID_OFFSET, - type AttachmentType, + UpdateSource, kSerializeData, - type AttachmentTypeString, } from '../../utils/constants'; -import type { AllowArray } from '../../types'; +import { applyMixins, getPeerType, getRandomId, pickProperties, unescapeHTML } from '../../utils/helpers'; import type { KeyboardBuilder } from '../keyboard'; -import type { IUploadSourceMedia } from '../../upload'; export type MessageContextType = 'message'; export type MessageContextPayloadEventType = -'chat_photo_update' -| 'chat_photo_remove' -| 'chat_create' -| 'chat_title_update' -| 'chat_invite_user' -| 'chat_kick_user' -| 'chat_pin_message' -| 'chat_unpin_message' -| 'chat_invite_user_by_link'; - -export type MessageContextSubType = -'message_new' -| 'message_edit' -| 'message_reply' -| MessageContextPayloadEventType; + | 'chat_photo_update' + | 'chat_photo_remove' + | 'chat_create' + | 'chat_title_update' + | 'chat_invite_user' + | 'chat_kick_user' + | 'chat_pin_message' + | 'chat_unpin_message' + | 'chat_invite_user_by_link'; + +export type MessageContextSubType = 'message_new' | 'message_edit' | 'message_reply' | MessageContextPayloadEventType; const subTypesEnum: Record = { 10004: 'message_new', @@ -125,14 +115,7 @@ export interface IMessageContextPayload { is_expired?: boolean; }; client_info: { - button_actions: ( - 'text' - | 'vkpay' - | 'open_app' - | 'location' - | 'open_link' - | 'callback' - )[]; + button_actions: ('text' | 'vkpay' | 'open_app' | 'location' | 'open_link' | 'callback')[]; keyboard: boolean; inline_keyboard: boolean; carousel: boolean; @@ -140,16 +123,14 @@ export interface IMessageContextPayload { }; } -export type MessageContextOptions = - ContextFactoryOptions; +export type MessageContextOptions = ContextFactoryOptions; -class MessageContext - extends Context< +class MessageContext extends Context< IMessageContextPayload, S, MessageContextType, MessageContextSubType - > { +> { public $match!: RegExpMatchArray; public text?: string; @@ -175,9 +156,9 @@ class MessageContext this.applyPayload( Array.isArray(options.payload) - ? transformMessage((options.payload as unknown) as Parameters[0]) - // There's user long poll reply message - : options.payload, + ? transformMessage(options.payload as unknown as Parameters[0]) + : // There's user long poll reply message + options.payload, ); } else { this.$filled = true; @@ -186,9 +167,7 @@ class MessageContext } this.subTypes = [ - this.eventType - || subTypesEnum[options.updateType] - || options.updateType as MessageContextSubType, + this.eventType || subTypesEnum[options.updateType] || (options.updateType as MessageContextSubType), ]; } @@ -200,20 +179,21 @@ class MessageContext return; } - const { items } = this.id !== 0 - ? await this.api.messages.getById({ - message_ids: this.id, - }) - : await this.api.messages.getByConversationMessageId({ - peer_id: this.peerId, - conversation_message_ids: this.conversationMessageId, - }); + const { items } = + this.id !== 0 + ? await this.api.messages.getById({ + message_ids: this.id, + }) + : await this.api.messages.getByConversationMessageId({ + peer_id: this.peerId, + conversation_message_ids: this.conversationMessageId, + }); const [message] = items; this.applyPayload({ out: Number(this.isOutbox), - ...message as Omit, + ...(message as Omit), }); this.$filled = true; @@ -532,16 +512,11 @@ class MessageContext * Edits a message */ editMessage(params: IMessageContextSendOptions): Promise { - const target = this.id !== 0 - ? { message_id: this.id } - : { conversation_message_id: this.conversationMessageId }; + const target = + this.id !== 0 ? { message_id: this.id } : { conversation_message_id: this.conversationMessageId }; return this.api.messages.edit({ - attachment: String( - this.attachments.filter(attachment => ( - attachment.canBeAttached - )), - ), + attachment: String(this.attachments.filter(attachment => attachment.canBeAttached)), message: this.text, keep_forward_messages: 1, keep_snippets: 1, @@ -566,15 +541,13 @@ class MessageContext const options = { random_id: randomId, - ...( - typeof text !== 'object' - ? { - message: text, + ...(typeof text !== 'object' + ? { + message: text, - ...params, - } - : text - ), + ...params, + } + : text), } as IMessageContextSendOptions; if (this.$groupId !== undefined) { @@ -587,18 +560,19 @@ class MessageContext const { message } = this; - const destination = typeof rawDestination !== 'number' - ? rawDestination[0] as { - peer_id : number; - message_id: number; - conversation_message_id: number; - error: number; - } - : { - peer_id: message.peer_id, - message_id: rawDestination, - conversation_message_id: 0, - }; + const destination = + typeof rawDestination !== 'number' + ? (rawDestination[0] as { + peer_id: number; + message_id: number; + conversation_message_id: number; + error: number; + }) + : { + peer_id: message.peer_id, + message_id: rawDestination, + conversation_message_id: 0, + }; const messageContext = new MessageContext({ api: this.api, @@ -638,10 +612,7 @@ class MessageContext /** * Responds to the current message */ - reply( - text: string | IMessageContextSendOptions, - params?: IMessageContextSendOptions, - ): Promise> { + reply(text: string | IMessageContextSendOptions, params?: IMessageContextSendOptions): Promise> { const forwardOptions = this.conversationMessageId ? { conversation_message_ids: this.conversationMessageId } : { message_ids: this.id }; @@ -654,15 +625,13 @@ class MessageContext is_reply: true, }), - ...( - typeof text !== 'object' - ? { - message: text, + ...(typeof text !== 'object' + ? { + message: text, - ...params, - } - : text - ), + ...params, + } + : text), }); } @@ -673,17 +642,17 @@ class MessageContext rawSources: AllowArray, params: IMessageContextSendOptions = {}, ): Promise> { - const sources = !Array.isArray(rawSources) - ? [rawSources] - : rawSources; + const sources = !Array.isArray(rawSources) ? [rawSources] : rawSources; - const attachment = await Promise.all(sources.map(source => ( - this.upload.messagePhoto({ - source, + const attachment = await Promise.all( + sources.map(source => + this.upload.messagePhoto({ + source, - peer_id: this.peerId, - }) - ))); + peer_id: this.peerId, + }), + ), + ); return this.send({ ...params, @@ -699,17 +668,17 @@ class MessageContext rawSources: AllowArray, params: IMessageContextSendOptions = {}, ): Promise> { - const sources = !Array.isArray(rawSources) - ? [rawSources] - : rawSources; + const sources = !Array.isArray(rawSources) ? [rawSources] : rawSources; - const attachment = await Promise.all(sources.map(source => ( - this.upload.messageDocument({ - source, + const attachment = await Promise.all( + sources.map(source => + this.upload.messageDocument({ + source, - peer_id: this.peerId, - }) - ))); + peer_id: this.peerId, + }), + ), + ); return this.send({ ...params, @@ -766,7 +735,7 @@ class MessageContext ...target, }); - return Boolean(messageIds[isConversation ? this.conversationMessageId as number : this.id]); + return Boolean(messageIds[isConversation ? (this.conversationMessageId as number) : this.id]); } /** @@ -790,31 +759,24 @@ class MessageContext /** * Applies the payload */ - private applyPayload( - payload: IMessageContextPayload - | IMessageContextPayload['message'], - ): void { + private applyPayload(payload: IMessageContextPayload | IMessageContextPayload['message']): void { // Polyfill for all events except new_message this.payload = !('client_info' in payload) ? { - message: payload , - client_info: { - button_actions: [ - 'text', - ], - inline_keyboard: false, - keyboard: true, - carousel: false, - lang_id: 0, - }, - } + message: payload, + client_info: { + button_actions: ['text'], + inline_keyboard: false, + keyboard: true, + carousel: false, + lang_id: 0, + }, + } : payload; const { message } = this; - this.text = message.text - ? unescapeHTML(message.text) - : undefined; + this.text = message.text ? unescapeHTML(message.text) : undefined; this[kAttachments] = transformAttachments(message.attachments || [], this.api); @@ -824,9 +786,7 @@ class MessageContext this[kReplyMessage] = new MessageContext({ api: this.api, upload: this.upload, - source: this.$filled - ? UpdateSource.WEBHOOK - : UpdateSource.POLLING, + source: this.$filled ? UpdateSource.WEBHOOK : UpdateSource.POLLING, groupId: this.$groupId, updateType: 'message_new', state: this.state, @@ -835,28 +795,29 @@ class MessageContext message: { ...message.reply_message, - peer_id: replyPeerId !== 0 - ? replyPeerId - : this.peerId, + peer_id: replyPeerId !== 0 ? replyPeerId : this.peerId, }, }, }); } - this[kForwards] = new MessageForwardsCollection(...(message.fwd_messages || []).map(forward => ( - new MessageContext({ - api: this.api, - upload: this.upload, - source: UpdateSource.WEBHOOK, - groupId: this.$groupId, - updateType: 'message_new', - state: this.state, - payload: { - client_info: this.clientInfo, - message: forward, - }, - }) - ))); + this[kForwards] = new MessageForwardsCollection( + ...(message.fwd_messages || []).map( + forward => + new MessageContext({ + api: this.api, + upload: this.upload, + source: UpdateSource.WEBHOOK, + groupId: this.$groupId, + updateType: 'message_new', + state: this.state, + payload: { + client_info: this.clientInfo, + message: forward, + }, + }), + ), + ); if (message.payload) { this[kMessagePayload] = JSON.parse(message.payload); @@ -870,12 +831,7 @@ class MessageContext const beforeAttachments: string[] = []; if (this.isEvent) { - beforeAttachments.push( - 'eventType', - 'eventMemberId', - 'eventText', - 'eventEmail', - ); + beforeAttachments.push('eventType', 'eventMemberId', 'eventText', 'eventEmail'); } if (this.hasReplyMessage) { @@ -931,20 +887,18 @@ applyMixins(MessageContext, [ public hasAllAttachments(type: AttachmentType | AttachmentTypeString | undefined): boolean { return ( - this.hasAttachments(type) - || (this.replyMessage?.hasAttachments(type)) - || this.forwards.hasAttachments(type) + this.hasAttachments(type) || + this.replyMessage?.hasAttachments(type) || + this.forwards.hasAttachments(type) ); } - public getAllAttachments( - type: AttachmentType | AttachmentTypeString, - ): (Attachment | ExternalAttachment)[] { + public getAllAttachments(type: AttachmentType | AttachmentTypeString): (Attachment | ExternalAttachment)[] { return [ // @ts-expect-error no override ...this.getAttachments(type), // @ts-expect-error no override - ...((this.replyMessage?.getAttachments(type)) ?? []), + ...(this.replyMessage?.getAttachments(type) ?? []), // @ts-expect-error no override ...this.forwards.getAttachments(type), ]; diff --git a/packages/vk-io/src/structures/contexts/messages-read.ts b/packages/vk-io/src/structures/contexts/messages-read.ts index 670053f6c..df319f521 100644 --- a/packages/vk-io/src/structures/contexts/messages-read.ts +++ b/packages/vk-io/src/structures/contexts/messages-read.ts @@ -1,13 +1,11 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type MessagesReadContextType = 'messages_read'; -export type MessagesReadContextSubType = -'messages_read_inbox' -| 'messages_read_outbox'; +export type MessagesReadContextSubType = 'messages_read_inbox' | 'messages_read_outbox'; const subTypes: Record = { 10006: 'messages_read_inbox', @@ -19,16 +17,14 @@ export interface IMessagesReadContextPayload { local_id: number; } -export type MessagesReadContextContextOptions = - ContextFactoryOptions; +export type MessagesReadContextContextOptions = ContextFactoryOptions; -export class MessagesReadContext - extends Context< +export class MessagesReadContext extends Context< IMessagesReadContextPayload, S, MessagesReadContextType, MessagesReadContextSubType - > { +> { public constructor(options: MessagesReadContextContextOptions) { const [eventId, peerId, localId] = options.payload; @@ -36,9 +32,7 @@ export class MessagesReadContext ...options, type: 'messages_read', - subTypes: [ - subTypes[eventId], - ], + subTypes: [subTypes[eventId]], payload: { peer_id: peerId, @@ -79,11 +73,6 @@ export class MessagesReadContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'id', - 'peerId', - 'isInbox', - 'isOutbox', - ]); + return pickProperties(this, ['id', 'peerId', 'isInbox', 'isOutbox']); } } diff --git a/packages/vk-io/src/structures/contexts/new-attachments.ts b/packages/vk-io/src/structures/contexts/new-attachments.ts index 275838397..137e9d5df 100644 --- a/packages/vk-io/src/structures/contexts/new-attachments.ts +++ b/packages/vk-io/src/structures/contexts/new-attachments.ts @@ -1,23 +1,16 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; import { VKError } from '../../errors'; -import { - AudioAttachment, - PhotoAttachment, - VideoAttachment, -} from '../attachments'; +import { AudioAttachment, PhotoAttachment, VideoAttachment } from '../attachments'; import { Attachmentable } from '../shared/attachmentable'; -import { pickProperties, applyMixins } from '../../utils/helpers'; -import { kSerializeData, AttachmentType } from '../../utils/constants'; +import { AttachmentType, kSerializeData } from '../../utils/constants'; +import { applyMixins, pickProperties } from '../../utils/helpers'; export type NewAttachmentsContextType = 'new_attachment'; -export type NewAttachmentsContextSubType = -'photo_new' -| 'video_new' -| 'audio_new'; +export type NewAttachmentsContextSubType = 'photo_new' | 'video_new' | 'audio_new'; const subAttachmentTypes = { photo_new: PhotoAttachment, @@ -29,16 +22,14 @@ export interface INewAttachmentsContextPayload { id: number; } -export type NewAttachmentsContextOptions = - ContextFactoryOptions; +export type NewAttachmentsContextOptions = ContextFactoryOptions; -class NewAttachmentsContext - extends Context< +class NewAttachmentsContext extends Context< INewAttachmentsContextPayload, S, NewAttachmentsContextType, NewAttachmentsContextSubType - > { +> { public constructor(options: NewAttachmentsContextOptions) { const PayloadAttachment = subAttachmentTypes[options.updateType as keyof typeof subAttachmentTypes]; @@ -46,15 +37,15 @@ class NewAttachmentsContext ...options, type: 'new_attachment', - subTypes: [ - options.updateType as NewAttachmentsContextSubType, - ], + subTypes: [options.updateType as NewAttachmentsContextSubType], }); - this.attachments = [new PayloadAttachment({ - api: this.api, - payload: this.payload as InstanceType['payload'], - })]; + this.attachments = [ + new PayloadAttachment({ + api: this.api, + payload: this.payload as InstanceType['payload'], + }), + ]; } /** @@ -110,22 +101,19 @@ class NewAttachmentsContext }); } - return Promise.reject(new VKError({ - message: 'Unsupported event for deleting attachment', - code: 'UNSUPPORTED_EVENT', - })); + return Promise.reject( + new VKError({ + message: 'Unsupported event for deleting attachment', + code: 'UNSUPPORTED_EVENT', + }), + ); } /** * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'attachments', - 'isPhoto', - 'isVideo', - 'isAudio', - ]); + return pickProperties(this, ['attachments', 'isPhoto', 'isVideo', 'isAudio']); } } diff --git a/packages/vk-io/src/structures/contexts/typing.ts b/packages/vk-io/src/structures/contexts/typing.ts index 8cd38de4c..08fd16a86 100644 --- a/packages/vk-io/src/structures/contexts/typing.ts +++ b/packages/vk-io/src/structures/contexts/typing.ts @@ -1,19 +1,14 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties, getPeerType } from '../../utils/helpers'; -import { - PEER_CHAT_ID_OFFSET, - - UpdateSource, - kSerializeData, -} from '../../utils/constants'; +import { PEER_CHAT_ID_OFFSET, UpdateSource, kSerializeData } from '../../utils/constants'; +import { getPeerType, pickProperties } from '../../utils/helpers'; export enum TypingState { TYPING = 'typing', AUDIO_MESSAGE = 'audiomessage', PHOTO_MESSAGE = 'photo', VIDEO_MESSAGE = 'video', - FILE_MESSAGE = 'file' + FILE_MESSAGE = 'file', } export interface ITypingContextPayload { @@ -36,28 +31,21 @@ const transformPolling = ( ): ITypingContextPayload => ({ from_id: fromIds[0], to_id: toId, - state: typeof updateType === 'string' - ? updateType as TypingState - : stateTypesEnum[updateType], + state: typeof updateType === 'string' ? (updateType as TypingState) : stateTypesEnum[updateType], }); export type TypingContextType = 'typing'; -export type TypingContextSubType = -'typing_user' -| 'typing_group' -| 'message_typing_state'; +export type TypingContextSubType = 'typing_user' | 'typing_group' | 'message_typing_state'; -export type TypingContextOptions = - ContextFactoryOptions; +export type TypingContextOptions = ContextFactoryOptions; -export class TypingContext - extends Context< +export class TypingContext extends Context< ITypingContextPayload, S, TypingContextType, TypingContextSubType - > { +> { public constructor(options: TypingContextOptions) { super({ ...options, @@ -68,12 +56,10 @@ export class TypingContext `typing_${getPeerType(options.payload.from_id)}` as TypingContextSubType, ], - payload: options.source === UpdateSource.POLLING - ? transformPolling( - (options.payload as unknown) as [number, number, number[]], - options.updateType, - ) - : options.payload, + payload: + options.source === UpdateSource.POLLING + ? transformPolling(options.payload as unknown as [number, number, number[]], options.updateType) + : options.payload, }); } @@ -153,9 +139,7 @@ export class TypingContext public get chatId(): number | undefined { const chatId = this.toId - PEER_CHAT_ID_OFFSET; - return chatId > 0 - ? chatId - : undefined; + return chatId > 0 ? chatId : undefined; } /** diff --git a/packages/vk-io/src/structures/contexts/unsupported-event.ts b/packages/vk-io/src/structures/contexts/unsupported-event.ts index 7a764510d..fa8af2aca 100644 --- a/packages/vk-io/src/structures/contexts/unsupported-event.ts +++ b/packages/vk-io/src/structures/contexts/unsupported-event.ts @@ -8,35 +8,28 @@ type UnsupportedEventContextSubType = string; type UnsupportedEventContextPayload

= P; -export type UnsupportedEventOptions = - ContextFactoryOptions, S>; - -export class UnsupportedEventContext< - S = ContextDefaultState, - P extends Record = object -> - extends Context< +export type UnsupportedEventOptions = ContextFactoryOptions, S>; + +export class UnsupportedEventContext = object> extends Context< P, S, UnsupportedEventContextType, UnsupportedEventContextSubType - > { +> { constructor(options: UnsupportedEventOptions) { super({ ...options, type: 'unsupported_event', - subTypes: [ - options.updateType as string, - ], + subTypes: [options.updateType as string], payload: options.payload, }); } /** - * Event payload - */ + * Event payload + */ public get eventPayload(): P { return this.payload; } @@ -45,8 +38,6 @@ export class UnsupportedEventContext< * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'eventPayload', - ]); + return pickProperties(this, ['eventPayload']); } } diff --git a/packages/vk-io/src/structures/contexts/vk-app-payload.ts b/packages/vk-io/src/structures/contexts/vk-app-payload.ts index 04e0dda96..1184fe389 100644 --- a/packages/vk-io/src/structures/contexts/vk-app-payload.ts +++ b/packages/vk-io/src/structures/contexts/vk-app-payload.ts @@ -1,7 +1,7 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type VKAppPayloadContextType = 'vk_app_event'; @@ -14,24 +14,20 @@ export interface IVKAppPayloadPayload { group_id: number; } -export type VKAppPayloadContextOptions = - ContextFactoryOptions; +export type VKAppPayloadContextOptions = ContextFactoryOptions; -export class VKAppPayloadContext = object> - extends Context< +export class VKAppPayloadContext = object> extends Context< IVKAppPayloadPayload, S, VKAppPayloadContextType, VKAppPayloadContextSubType - > { +> { public constructor(options: VKAppPayloadContextOptions) { super({ ...options, type: 'vk_app_event', - subTypes: [ - options.updateType as VKAppPayloadContextSubType, - ], + subTypes: [options.updateType as VKAppPayloadContextSubType], }); } @@ -67,11 +63,6 @@ export class VKAppPayloadContext = - ContextFactoryOptions; +export type VKPayTransactionContextOptions = ContextFactoryOptions; -export class VKPayTransactionContext - extends Context< +export class VKPayTransactionContext extends Context< IVKPayTransactionPayload, S, VKPayTransactionContextType, VKPayTransactionContextSubType - > { +> { public constructor(options: VKPayTransactionContextOptions) { super({ ...options, type: 'vk_pay_transaction', - subTypes: [ - options.updateType as VKPayTransactionContextSubType, - ], + subTypes: [options.updateType as VKPayTransactionContextSubType], }); } @@ -67,11 +63,6 @@ export class VKPayTransactionContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'fromId', - 'amount', - 'description', - 'createdAt', - ]); + return pickProperties(this, ['fromId', 'amount', 'description', 'createdAt']); } } diff --git a/packages/vk-io/src/structures/contexts/vote.ts b/packages/vk-io/src/structures/contexts/vote.ts index f8501911a..2bf650858 100644 --- a/packages/vk-io/src/structures/contexts/vote.ts +++ b/packages/vk-io/src/structures/contexts/vote.ts @@ -1,7 +1,7 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type VoteContextType = 'vote'; @@ -14,24 +14,20 @@ export interface IVoteContextPayload { option_id: number; } -export type VoteContextOptions = - ContextFactoryOptions; +export type VoteContextOptions = ContextFactoryOptions; -export class VoteContext - extends Context< +export class VoteContext extends Context< IVoteContextPayload, S, VoteContextType, VoteContextSubType - > { +> { public constructor(options: VoteContextOptions) { super({ ...options, type: 'vote', - subTypes: [ - options.updateType as VoteContextSubType, - ], + subTypes: [options.updateType as VoteContextSubType], }); } @@ -67,11 +63,6 @@ export class VoteContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'id', - 'userId', - 'ownerId', - 'optionId', - ]); + return pickProperties(this, ['id', 'userId', 'ownerId', 'optionId']); } } diff --git a/packages/vk-io/src/structures/contexts/wall-post.ts b/packages/vk-io/src/structures/contexts/wall-post.ts index b6de74278..cc4f8a62a 100644 --- a/packages/vk-io/src/structures/contexts/wall-post.ts +++ b/packages/vk-io/src/structures/contexts/wall-post.ts @@ -1,30 +1,24 @@ -import { Context, type ContextFactoryOptions, type ContextDefaultState } from './context'; +import { Context, type ContextDefaultState, type ContextFactoryOptions } from './context'; -import { WallAttachment, type IWallAttachmentPayload } from '../attachments'; +import { type IWallAttachmentPayload, WallAttachment } from '../attachments'; -import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; +import { pickProperties } from '../../utils/helpers'; export type WallPostContextType = 'wall_post'; -export type WallPostContextSubType = -'wall_post_new' -| 'wall_repost'; +export type WallPostContextSubType = 'wall_post_new' | 'wall_repost'; -export interface IWallPostContextPayload extends IWallAttachmentPayload { - -} +export interface IWallPostContextPayload extends IWallAttachmentPayload {} -export type WallPostContextOptions = - ContextFactoryOptions; +export type WallPostContextOptions = ContextFactoryOptions; -export class WallPostContext - extends Context< +export class WallPostContext extends Context< IWallPostContextPayload, S, WallPostContextType, WallPostContextSubType - > { +> { public wall: WallAttachment; public constructor(options: WallPostContextOptions) { @@ -32,9 +26,7 @@ export class WallPostContext ...options, type: 'wall_post', - subTypes: [ - options.updateType as WallPostContextSubType, - ], + subTypes: [options.updateType as WallPostContextSubType], }); this.wall = new WallAttachment({ @@ -66,9 +58,6 @@ export class WallPostContext * Returns the custom data */ public [kSerializeData](): object { - return pickProperties(this, [ - 'wall', - 'isRepost', - ]); + return pickProperties(this, ['wall', 'isRepost']); } } diff --git a/packages/vk-io/src/structures/keyboard/builder.ts b/packages/vk-io/src/structures/keyboard/builder.ts index 46b1474f6..f0ce7f48e 100644 --- a/packages/vk-io/src/structures/keyboard/builder.ts +++ b/packages/vk-io/src/structures/keyboard/builder.ts @@ -1,14 +1,13 @@ import { ButtonColor, type ButtonPayload, - type KeyboardButton, - + type IKeyboardApplicationButtonOptions, + type IKeyboardCallbackButtonOptions, + type IKeyboardLocationRequestButtonOptions, type IKeyboardTextButtonOptions, type IKeyboardURLButtonOptions, - type IKeyboardLocationRequestButtonOptions, type IKeyboardVKPayButtonOptions, - type IKeyboardApplicationButtonOptions, - type IKeyboardCallbackButtonOptions, + type KeyboardButton, } from './types'; const serializePayload = (rawPayload: ButtonPayload): string => { @@ -95,11 +94,7 @@ export class KeyboardBuilder { * }); * ``` */ - public urlButton({ - label, - url, - payload: rawPayload = {}, - }: IKeyboardURLButtonOptions): this { + public urlButton({ label, url, payload: rawPayload = {} }: IKeyboardURLButtonOptions): this { if (label.length > 40) { throw new RangeError('Maximum length of label 40 characters'); } @@ -128,9 +123,7 @@ export class KeyboardBuilder { * }) * ``` */ - public locationRequestButton({ - payload: rawPayload = {}, - }: IKeyboardLocationRequestButtonOptions): this { + public locationRequestButton({ payload: rawPayload = {} }: IKeyboardLocationRequestButtonOptions): this { const payload = serializePayload(rawPayload); return this.addWideButton({ @@ -155,15 +148,10 @@ export class KeyboardBuilder { * }) * ``` */ - public payButton({ - payload: rawPayload, - hash: rawHash, - }: IKeyboardVKPayButtonOptions): this { + public payButton({ payload: rawPayload, hash: rawHash }: IKeyboardVKPayButtonOptions): this { const payload = serializePayload(rawPayload); - const hash = typeof rawHash === 'object' - ? String(new URLSearchParams(Object.entries(rawHash))) - : rawHash; + const hash = typeof rawHash === 'object' ? String(new URLSearchParams(Object.entries(rawHash))) : rawHash; return this.addWideButton({ action: { @@ -186,12 +174,7 @@ export class KeyboardBuilder { * }) * ``` */ - public applicationButton({ - label, - appId, - ownerId, - hash, - }: IKeyboardApplicationButtonOptions): this { + public applicationButton({ label, appId, ownerId, hash }: IKeyboardApplicationButtonOptions): this { if (label.length > 40) { throw new RangeError('Maximum length of label 40 characters'); } @@ -313,28 +296,24 @@ export class KeyboardBuilder { * Returns a string to keyboard a VK */ public toString(): string { - const maxRowsLength = this.isInline - ? 6 - : 10; + const maxRowsLength = this.isInline ? 6 : 10; if (this.rows.length > maxRowsLength) { throw new RangeError(`Max count of keyboard rows ${maxRowsLength}`); } - const buttons = this.currentRow.length !== 0 - ? [...this.rows, this.currentRow] - : this.rows; + const buttons = this.currentRow.length !== 0 ? [...this.rows, this.currentRow] : this.rows; return JSON.stringify( this.isInline ? { - buttons, - inline: true, - } + buttons, + inline: true, + } : { - buttons, - one_time: this.isOneTime, - }, + buttons, + one_time: this.isOneTime, + }, ); } diff --git a/packages/vk-io/src/structures/keyboard/keyboard.ts b/packages/vk-io/src/structures/keyboard/keyboard.ts index e44451887..ab47175af 100644 --- a/packages/vk-io/src/structures/keyboard/keyboard.ts +++ b/packages/vk-io/src/structures/keyboard/keyboard.ts @@ -1,14 +1,13 @@ import { KeyboardBuilder } from './builder'; import { + ButtonColor, + type IKeyboardApplicationButtonOptions, + type IKeyboardCallbackButtonOptions, + type IKeyboardLocationRequestButtonOptions, type IKeyboardProxyButton, type IKeyboardTextButtonOptions, type IKeyboardURLButtonOptions, - type IKeyboardLocationRequestButtonOptions, type IKeyboardVKPayButtonOptions, - type IKeyboardApplicationButtonOptions, - type IKeyboardCallbackButtonOptions, - - ButtonColor, } from './types'; export class Keyboard { @@ -69,9 +68,7 @@ export class Keyboard { const builder = new KeyboardBuilder(); for (const row of rows) { - const buttons = Array.isArray(row) - ? row - : [row]; + const buttons = Array.isArray(row) ? row : [row]; for (const { kind, options } of buttons) { if (kind === 'text') { @@ -122,45 +119,35 @@ export class Keyboard { /** * Text button, can be colored */ - public static textButton( - options: IKeyboardTextButtonOptions, - ): IKeyboardProxyButton { + public static textButton(options: IKeyboardTextButtonOptions): IKeyboardProxyButton { return { options, kind: 'text' }; } /** * URL button */ - public static urlButton( - options: IKeyboardURLButtonOptions, - ): IKeyboardProxyButton { + public static urlButton(options: IKeyboardURLButtonOptions): IKeyboardProxyButton { return { options, kind: 'url' }; } /** * User location request button, occupies the entire keyboard width */ - public static locationRequestButton( - options: IKeyboardLocationRequestButtonOptions, - ): IKeyboardProxyButton { + public static locationRequestButton(options: IKeyboardLocationRequestButtonOptions): IKeyboardProxyButton { return { options, kind: 'location_request' }; } /** * VK Pay button, occupies the entire keyboard width */ - public static payButton( - options: IKeyboardVKPayButtonOptions, - ): IKeyboardProxyButton { + public static payButton(options: IKeyboardVKPayButtonOptions): IKeyboardProxyButton { return { options, kind: 'vk_pay' }; } /** * VK Apps button, occupies the entire keyboard width */ - public static applicationButton( - options: IKeyboardApplicationButtonOptions, - ): IKeyboardProxyButton { + public static applicationButton(options: IKeyboardApplicationButtonOptions): IKeyboardProxyButton { return { options, kind: 'vk_application' }; } @@ -168,9 +155,7 @@ export class Keyboard { * Allows without sending a message from the user * to receive a notification of a button click and perform the necessary action */ - public static callbackButton( - options: IKeyboardCallbackButtonOptions, - ): IKeyboardProxyButton { + public static callbackButton(options: IKeyboardCallbackButtonOptions): IKeyboardProxyButton { return { options, kind: 'callback' }; } } diff --git a/packages/vk-io/src/structures/keyboard/types.ts b/packages/vk-io/src/structures/keyboard/types.ts index 856068ef4..20d687bda 100644 --- a/packages/vk-io/src/structures/keyboard/types.ts +++ b/packages/vk-io/src/structures/keyboard/types.ts @@ -42,14 +42,10 @@ export enum ButtonColor { * * Hex color #4BB34B */ - POSITIVE = 'positive' + POSITIVE = 'positive', } -export type ButtonColorUnion = - 'secondary' - | 'primary' - | 'negative' - | 'positive'; +export type ButtonColorUnion = 'secondary' | 'primary' | 'negative' | 'positive'; export interface ITextButton extends IButton { /** @@ -174,7 +170,7 @@ export interface ICallbackButton extends IButton { } export type KeyboardButton = - ITextButton + | ITextButton | IURLButton | ILocationButton | IVKPayButton @@ -301,16 +297,12 @@ export interface IVKPayTransferToUser { user_id: number; } -export type KeyboardVKPayHash = - (IVKPayPayToGroup - | IVKPayPayToUser - | IVKPayTransferToGroup - | IVKPayTransferToUser) & { - /** - * Application id - */ - aid: string | number; - }; +export type KeyboardVKPayHash = (IVKPayPayToGroup | IVKPayPayToUser | IVKPayTransferToGroup | IVKPayTransferToUser) & { + /** + * Application id + */ + aid: string | number; +}; export interface IKeyboardVKPayButtonOptions { payload: ButtonPayload; @@ -380,14 +372,13 @@ export interface IKeyboardCallbackButtonOptions { } export interface IKeyboardProxyButton { - options: ( - IKeyboardTextButtonOptions + options: + | IKeyboardTextButtonOptions | IKeyboardURLButtonOptions | IKeyboardLocationRequestButtonOptions | IKeyboardVKPayButtonOptions | IKeyboardApplicationButtonOptions - | IKeyboardCallbackButtonOptions - ); + | IKeyboardCallbackButtonOptions; kind: 'text' | 'url' | 'location_request' | 'vk_pay' | 'vk_application' | 'callback'; } diff --git a/packages/vk-io/src/structures/shared/attachmentable.ts b/packages/vk-io/src/structures/shared/attachmentable.ts index 75496e640..32f0c6f0a 100644 --- a/packages/vk-io/src/structures/shared/attachmentable.ts +++ b/packages/vk-io/src/structures/shared/attachmentable.ts @@ -1,11 +1,10 @@ /* eslint-disable */ import type { Attachment, - ExternalAttachment, - AudioAttachment, AudioMessageAttachment, DocumentAttachment, + ExternalAttachment, GiftAttachment, GraffitiAttachment, LinkAttachment, @@ -16,8 +15,8 @@ import type { StickerAttachment, StoryAttachment, VideoAttachment, + WallAttachment, WallReplyAttachment, - WallAttachment } from '../attachments'; import type { AttachmentType, AttachmentTypeString } from '../../utils/constants'; @@ -33,9 +32,7 @@ export class Attachmentable { return this.attachments.length > 0; } - return this.attachments.some(attachment => ( - attachment.type === type - )); + return this.attachments.some(attachment => attachment.type === type); } /** @@ -76,9 +73,7 @@ export class Attachmentable { return this.attachments; } - return this.attachments.filter(attachment => ( - attachment.type === type - )); + return this.attachments.filter(attachment => attachment.type === type); } } diff --git a/packages/vk-io/src/structures/shared/message-forward-collection.ts b/packages/vk-io/src/structures/shared/message-forward-collection.ts index fdf3931bf..29a997016 100644 --- a/packages/vk-io/src/structures/shared/message-forward-collection.ts +++ b/packages/vk-io/src/structures/shared/message-forward-collection.ts @@ -1,19 +1,16 @@ +import type { AttachmentTypeString } from '../../utils/constants'; +import { applyMixins } from '../../utils/helpers'; +import type { Attachment, ExternalAttachment } from '../attachments'; +import type { ContextDefaultState } from '../contexts/context'; /* eslint-disable max-classes-per-file */ import type { MessageContext } from '../contexts/message'; -import type { ContextDefaultState } from '../contexts/context'; -import type { Attachment, ExternalAttachment } from '../attachments'; -import type { AttachmentTypeString } from '../../utils/constants'; import type { Attachmentable } from './attachmentable'; -import { applyMixins } from '../../utils/helpers'; const getForwards = (rootForwards: MessageContext[]): MessageContext[] => { const forwards: MessageContext[] = []; for (const forward of rootForwards) { - forwards.push( - forward, - ...getForwards(forward.forwards), - ); + forwards.push(forward, ...getForwards(forward.forwards)); } return forwards; @@ -42,18 +39,14 @@ applyMixins(MessageForwardsCollection, [ public flatten!: MessageContext[]; public hasAttachments(type?: AttachmentTypeString): boolean { - return this.flatten.some(forward => ( - forward.hasAttachments(type) - )); + return this.flatten.some(forward => forward.hasAttachments(type)); } - public getAttachments( - type?: AttachmentTypeString, - ): (Attachment | ExternalAttachment)[] { - const attachments = this.flatten.map(forward => ( + public getAttachments(type?: AttachmentTypeString): (Attachment | ExternalAttachment)[] { + const attachments = this.flatten.map(forward => // @ts-expect-error too annoying for overload types - forward.getAttachments(type) - )); + forward.getAttachments(type), + ); return ([] as (Attachment | ExternalAttachment)[]).concat(...attachments); } diff --git a/packages/vk-io/src/types.ts b/packages/vk-io/src/types.ts index 0ba33f932..49edf4c09 100644 --- a/packages/vk-io/src/types.ts +++ b/packages/vk-io/src/types.ts @@ -7,9 +7,8 @@ export type AllowArray = T | T[]; export type Constructor = new (...args: any[]) => T; -export type VKOptions = IAPIOptions -& IUpdatesOptions -& IUploadOptions -& { - callbackService?: CallbackService; -}; +export type VKOptions = IAPIOptions & + IUpdatesOptions & + IUploadOptions & { + callbackService?: CallbackService; + }; diff --git a/packages/vk-io/src/updates/helpers.ts b/packages/vk-io/src/updates/helpers.ts index 25f228565..b5e1af794 100644 --- a/packages/vk-io/src/updates/helpers.ts +++ b/packages/vk-io/src/updates/helpers.ts @@ -10,7 +10,5 @@ export const parseRequestJSON = async (req: IncomingMessage): Promise controller.abort(), 30e3); let result: - | { ts: number, pts?: number, updates: unknown[] } - | { failed: 1, ts: number } - | { failed: 2, error: string } - | { failed: 4, min_version: 0, max_version: 19 }; + | { ts: number; pts?: number; updates: unknown[] } + | { failed: 1; ts: number } + | { failed: 2; error: string } + | { failed: 4; min_version: 0; max_version: 19 }; try { const response = await fetch(this.url, { @@ -188,7 +188,7 @@ export class PollingTransport { message: 'Polling request failed', }); } - result = await response.json() as any; + result = (await response.json()) as any; } finally { clearTimeout(interval); } diff --git a/packages/vk-io/src/updates/transports/webhook.ts b/packages/vk-io/src/updates/transports/webhook.ts index 608a3ea49..e1909f774 100644 --- a/packages/vk-io/src/updates/transports/webhook.ts +++ b/packages/vk-io/src/updates/transports/webhook.ts @@ -1,14 +1,13 @@ import createDebug from 'debug'; -import type { TlsOptions } from 'tls'; -import { type Server as HTTPSServer, createServer as createHttpsServer } from 'https'; import { type Server as HttpServer, type IncomingMessage, type ServerResponse, - createServer as createHttpServer, } from 'http'; +import { type Server as HTTPSServer, createServer as createHttpsServer } from 'https'; +import type { TlsOptions } from 'tls'; import { promisify } from 'util'; import type { API } from '../../api'; @@ -27,25 +26,25 @@ export interface IWebhookTransportStartOptions { path?: string; port?: number; host?: string; - next?: (req: IncomingMessage, res: ServerResponse) => unknown + next?: (req: IncomingMessage, res: ServerResponse) => unknown; } export type WebhookTransportCallback = ( req: IncomingMessage, res: ServerResponse, - next?: (err?: Error) => unknown + next?: (err?: Error) => unknown, ) => unknown; export type WebhookTransportKoaCallback = ( context: { request: { body: Record; - } + }; body: object; status: number; set(key: string, value: string): unknown; }, - next: () => unknown + next: () => unknown, ) => unknown; export class WebhookTransport { @@ -82,7 +81,7 @@ export class WebhookTransport { } if (!this.webhookHandler) { - throw new Error('You didn\'t subscribe to updates'); + throw new Error("You didn't subscribe to updates"); } this.started = true; @@ -90,23 +89,14 @@ export class WebhookTransport { try { const webhookCallback = this.getWebhookCallback(path); - const callback = (req: IncomingMessage, res: ServerResponse) => ( - webhookCallback(req, res, (): unknown => ( - next(req, res) - )) - ); + const callback = (req: IncomingMessage, res: ServerResponse) => + webhookCallback(req, res, (): unknown => next(req, res)); - this.webhookServer = tls - ? createHttpsServer(tls, callback) - : createHttpServer(callback); + this.webhookServer = tls ? createHttpsServer(tls, callback) : createHttpServer(callback); const { webhookServer } = this; - const port = customPort || ( - tls - ? 443 - : 80 - ); + const port = customPort || (tls ? 443 : 80); await promisify(webhookServer.listen) // @ts-ignore https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#unmatched-parameters-are-no-longer-related @@ -144,9 +134,10 @@ export class WebhookTransport { 'content-type': 'text/plain', }; - const checkIsNotValidPath = path !== undefined - ? (requestPath: string | undefined): boolean => requestPath !== path - : (): boolean => false; + const checkIsNotValidPath = + path !== undefined + ? (requestPath: string | undefined): boolean => requestPath !== path + : (): boolean => false; return async (req, res, next) => { if (req.method !== 'POST' || checkIsNotValidPath(req.url)) { @@ -154,13 +145,11 @@ export class WebhookTransport { return; } - const reqBody = (req as typeof req & { body: string | Record; }).body; + const reqBody = (req as typeof req & { body: string | Record }).body; let update: any; try { - update = typeof reqBody !== 'object' - ? await parseRequestJSON(req) - : reqBody; + update = typeof reqBody !== 'object' ? await parseRequestJSON(req) : reqBody; } catch (e) { debug(e); diff --git a/packages/vk-io/src/updates/updates.ts b/packages/vk-io/src/updates/updates.ts index 2965cf397..993124d1d 100644 --- a/packages/vk-io/src/updates/updates.ts +++ b/packages/vk-io/src/updates/updates.ts @@ -5,136 +5,111 @@ import { type Middleware, compose, noopNext } from 'middleware-io'; import { type Agent, globalAgent } from 'https'; import { + CommentContext, + type CommentContextSubType, + type CommentContextType, Composer, - type ContextDefaultState, - type Context, - UnsupportedEventContext, - VoteContext, - LikeContext, - TypingContext, - MessageContext, - WallPostContext, - GroupUserContext, - FriendActivityContext, - GroupUpdateContext, + type ContextDefaultState, DialogFlagsContext, - GroupMemberContext, - MarketOrderContext, - MessageSubscriptionContext, - MessagesReadContext, - MessageFlagsContext, - MessageEventContext, - VKAppPayloadContext, - CommentContext, - NewAttachmentsContext, + type DialogFlagsContextSubType, + type DialogFlagsContextType, DialogMessagesContext, + type DialogMessagesContextSubType, + type DialogMessagesContextType, DialogNotificationSettingsContext, - VKPayTransactionContext, + type DialogNotificationSettingsContextSubType, + type DialogNotificationSettingsContextType, DonutSubscriptionContext, + type DonutSubscriptionContextSubType, + type DonutSubscriptionContextType, DonutSubscriptionPriceContext, + type DonutSubscriptionPriceContextSubType, + type DonutSubscriptionPriceContextType, DonutWithdrawContext, - - type UnsupportedEventContextType, - type CommentContextType, - type DialogFlagsContextType, - type DialogNotificationSettingsContextType, + type DonutWithdrawContextSubType, + type DonutWithdrawContextType, + FriendActivityContext, + type FriendActivityContextSubType, + type FriendActivityContextType, + GroupMemberContext, + type GroupMemberContextSubType, type GroupMemberContextType, + GroupUpdateContext, + type GroupUpdateContextSubType, type GroupUpdateContextType, + GroupUserContext, + type GroupUserContextSubType, type GroupUserContextType, - type MessageSubscriptionContextType, - type MessageEventContextType, - type MessageFlagsContextType, - type MessageContextType, - type NewAttachmentsContextType, - type MessagesReadContextType, - type DialogMessagesContextType, - type TypingContextType, - type FriendActivityContextType, - type VKAppPayloadContextType, - type VKPayTransactionContextType, - type VoteContextType, + LikeContext, + type LikeContextSubType, type LikeContextType, - type WallPostContextType, + MarketOrderContext, + type MarketOrderContextSubType, type MarketOrderContextType, - type DonutSubscriptionContextType, - type DonutSubscriptionPriceContextType, - type DonutWithdrawContextType, - - type CommentContextSubType, - type DialogFlagsContextSubType, - type DialogNotificationSettingsContextSubType, - type GroupMemberContextSubType, - type GroupUpdateContextSubType, - type GroupUserContextSubType, - type MessageSubscriptionContextSubType, + MessageContext, + type MessageContextSubType, + type MessageContextType, + MessageEventContext, type MessageEventContextSubType, + type MessageEventContextType, + MessageFlagsContext, type MessageFlagsContextSubType, - type MessageContextSubType, - type NewAttachmentsContextSubType, + type MessageFlagsContextType, + MessageSubscriptionContext, + type MessageSubscriptionContextSubType, + type MessageSubscriptionContextType, + MessagesReadContext, type MessagesReadContextSubType, - type DialogMessagesContextSubType, + type MessagesReadContextType, + NewAttachmentsContext, + type NewAttachmentsContextSubType, + type NewAttachmentsContextType, + TypingContext, type TypingContextSubType, - type FriendActivityContextSubType, + type TypingContextType, + UnsupportedEventContext, + type UnsupportedEventContextType, + VKAppPayloadContext, type VKAppPayloadContextSubType, + type VKAppPayloadContextType, + VKPayTransactionContext, type VKPayTransactionContextSubType, + type VKPayTransactionContextType, + VoteContext, type VoteContextSubType, - type LikeContextSubType, + type VoteContextType, + WallPostContext, type WallPostContextSubType, - type MarketOrderContextSubType, - type DonutSubscriptionContextSubType, - type DonutSubscriptionPriceContextSubType, - type DonutWithdrawContextSubType, + type WallPostContextType, } from '../structures'; import type { API } from '../api'; import type { Upload } from '../upload'; import { + type IWebhookTransportStartOptions, PollingTransport, - WebhookTransport, type WebhookTransportCallback, type WebhookTransportKoaCallback, - type IWebhookTransportStartOptions, } from './transports'; import { type APIError, APIErrorCode } from '../errors'; -import { UpdateSource } from '../utils/constants'; import type { AllowArray, Constructor } from '../types'; +import { UpdateSource } from '../utils/constants'; const debug = createDebug('vk-io:updates'); const webhookContextsEvents: [string[], Constructor][] = [ - [ - ['message_new', 'message_edit', 'message_reply'], - MessageContext, - ], - [ - ['message_allow', 'message_deny'], - MessageSubscriptionContext, - ], - [ - ['message_event'], - MessageEventContext, - ], - [ - ['photo_new', 'audio_new', 'video_new'], - NewAttachmentsContext, - ], - [ - ['wall_post_new', 'wall_repost'], - WallPostContext, - ], - [ - ['group_join', 'group_leave'], - GroupMemberContext, - ], - [ - ['user_block', 'user_unblock'], - GroupUserContext, - ], + [['message_new', 'message_edit', 'message_reply'], MessageContext], + [['message_allow', 'message_deny'], MessageSubscriptionContext], + [['message_event'], MessageEventContext], + [['photo_new', 'audio_new', 'video_new'], NewAttachmentsContext], + [['wall_post_new', 'wall_repost'], WallPostContext], + [['group_join', 'group_leave'], GroupMemberContext], + [['user_block', 'user_unblock'], GroupUserContext], [ [ 'photo_comment_new', @@ -160,34 +135,13 @@ const webhookContextsEvents: [string[], Constructor][] = [ ], CommentContext, ], - [ - ['poll_vote_new'], - VoteContext, - ], - [ - ['group_change_photo', 'group_officers_edit', 'group_change_settings'], - GroupUpdateContext, - ], - [ - ['message_typing_state'], - TypingContext, - ], - [ - ['app_payload'], - VKAppPayloadContext, - ], - [ - ['vkpay_transaction'], - VKPayTransactionContext, - ], - [ - ['like_add', 'like_remove'], - LikeContext, - ], - [ - ['market_order_new', 'market_order_edit'], - MarketOrderContext, - ], + [['poll_vote_new'], VoteContext], + [['group_change_photo', 'group_officers_edit', 'group_change_settings'], GroupUpdateContext], + [['message_typing_state'], TypingContext], + [['app_payload'], VKAppPayloadContext], + [['vkpay_transaction'], VKPayTransactionContext], + [['like_add', 'like_remove'], LikeContext], + [['market_order_new', 'market_order_edit'], MarketOrderContext], [ [ 'donut_subscription_create', @@ -197,57 +151,22 @@ const webhookContextsEvents: [string[], Constructor][] = [ ], DonutSubscriptionContext, ], - [ - ['donut_subscription_price_changed'], - DonutSubscriptionPriceContext, - ], - [ - [ - 'donut_money_withdraw', - 'donut_money_withdraw_error', - ], - DonutWithdrawContext, - ], + [['donut_subscription_price_changed'], DonutSubscriptionPriceContext], + [['donut_money_withdraw', 'donut_money_withdraw_error'], DonutWithdrawContext], ]; const pollingContextsEvents: [number[], Constructor][] = [ - [ - [10002, 10003], - MessageFlagsContext, - ], - [ - [10004, 10005, 10018], - MessageContext, - ], - [ - [10006, 10007], - MessagesReadContext, - ], - [ - [8, 9, 81], - FriendActivityContext, - ], - [ - [10, 12], - DialogFlagsContext, - ], - [ - [10013], - DialogMessagesContext, - ], - [ - [63, 64, 65, 66, 67], - TypingContext, - ], - [ - [114], - DialogNotificationSettingsContext, - ], + [[10002, 10003], MessageFlagsContext], + [[10004, 10005, 10018], MessageContext], + [[10006, 10007], MessagesReadContext], + [[8, 9, 81], FriendActivityContext], + [[10, 12], DialogFlagsContext], + [[10013], DialogMessagesContext], + [[63, 64, 65, 66, 67], TypingContext], + [[114], DialogNotificationSettingsContext], ]; -const makeContexts = ( - groups: [(number | string)[], Constructor][], -): Record> => { +const makeContexts = (groups: [(number | string)[], Constructor][]): Record> => { const contexts: Record> = {}; for (const [events, UpdateContext] of groups) { @@ -263,55 +182,55 @@ const webhookContexts = makeContexts(webhookContextsEvents); const pollingContexts = makeContexts(pollingContextsEvents); export type ContextTypes = -UnsupportedEventContextType -| CommentContextType -| DialogFlagsContextType -| DialogNotificationSettingsContextType -| GroupMemberContextType -| GroupUpdateContextType -| GroupUserContextType -| MessageSubscriptionContextType -| MessageEventContextType -| MessageFlagsContextType -| MessageContextType -| NewAttachmentsContextType -| MessagesReadContextType -| DialogMessagesContextType -| TypingContextType -| FriendActivityContextType -| VKAppPayloadContextType -| VKPayTransactionContextType -| VoteContextType -| LikeContextType -| WallPostContextType -| DonutSubscriptionContextType -| DonutSubscriptionPriceContextType -| DonutWithdrawContextType; + | UnsupportedEventContextType + | CommentContextType + | DialogFlagsContextType + | DialogNotificationSettingsContextType + | GroupMemberContextType + | GroupUpdateContextType + | GroupUserContextType + | MessageSubscriptionContextType + | MessageEventContextType + | MessageFlagsContextType + | MessageContextType + | NewAttachmentsContextType + | MessagesReadContextType + | DialogMessagesContextType + | TypingContextType + | FriendActivityContextType + | VKAppPayloadContextType + | VKPayTransactionContextType + | VoteContextType + | LikeContextType + | WallPostContextType + | DonutSubscriptionContextType + | DonutSubscriptionPriceContextType + | DonutWithdrawContextType; export type ContextSubTypes = -CommentContextSubType -| DialogFlagsContextSubType -| DialogNotificationSettingsContextSubType -| GroupMemberContextSubType -| GroupUpdateContextSubType -| GroupUserContextSubType -| MessageSubscriptionContextSubType -| MessageEventContextSubType -| MessageFlagsContextSubType -| MessageContextSubType -| NewAttachmentsContextSubType -| MessagesReadContextSubType -| DialogMessagesContextSubType -| TypingContextSubType -| FriendActivityContextSubType -| VKAppPayloadContextSubType -| VKPayTransactionContextSubType -| VoteContextSubType -| LikeContextSubType -| WallPostContextSubType -| DonutSubscriptionContextSubType -| DonutSubscriptionPriceContextSubType -| DonutWithdrawContextSubType; + | CommentContextSubType + | DialogFlagsContextSubType + | DialogNotificationSettingsContextSubType + | GroupMemberContextSubType + | GroupUpdateContextSubType + | GroupUserContextSubType + | MessageSubscriptionContextSubType + | MessageEventContextSubType + | MessageFlagsContextSubType + | MessageContextSubType + | NewAttachmentsContextSubType + | MessagesReadContextSubType + | DialogMessagesContextSubType + | TypingContextSubType + | FriendActivityContextSubType + | VKAppPayloadContextSubType + | VKPayTransactionContextSubType + | VoteContextSubType + | LikeContextSubType + | WallPostContextSubType + | DonutSubscriptionContextSubType + | DonutSubscriptionPriceContextSubType + | DonutWithdrawContextSubType; export type ContextPossibleTypes = ContextTypes | ContextSubTypes; @@ -357,10 +276,9 @@ export class Updates { private webhookTransport: WebhookTransport; - private composer = Composer.builder() - .caught((context, error) => { - console.error(error); - }); + private composer = Composer.builder().caught((context, error) => { + console.error(error); + }); private composed!: Middleware; @@ -445,135 +363,133 @@ export class Updates { */ public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( - events: AllowArray, - handler: AllowArray> + events: AllowArray, + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on = object>( events: AllowArray, - handler: AllowArray & T>> + handler: AllowArray & T>>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; // @ts-expect-error incompitable overload signature public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on( events: AllowArray, - handler: AllowArray> + handler: AllowArray>, ): this; public on = object>( events: AllowArray, - handler: AllowArray & T>> + handler: AllowArray & T>>, ): this; public on( rawEvents: AllowArray, rawHandlers: AllowArray>, ): this { - const events = !Array.isArray(rawEvents) - ? [rawEvents] - : rawEvents; + const events = !Array.isArray(rawEvents) ? [rawEvents] : rawEvents; const hasEvents = events.every(Boolean); @@ -581,20 +497,18 @@ export class Updates { throw new Error('Events should be not empty'); } - const handler = Array.isArray(rawHandlers) - ? compose(rawHandlers) - : rawHandlers; + const handler = Array.isArray(rawHandlers) ? compose(rawHandlers) : rawHandlers; if (typeof handler !== 'function') { throw new TypeError('Handler must be a function'); } - return this.use((context, next): unknown => ( + return this.use((context, next): unknown => context.is(events) - // @ts-expect-error we need support generic - ? handler(context, next) - : next() - )); + ? // @ts-expect-error we need support generic + handler(context, next) + : next(), + ); } /** @@ -613,14 +527,16 @@ export class Updates { return Promise.resolve(); } - return this.dispatchMiddleware(new UpdateContext({ - api: this.api, - upload: this.upload, + return this.dispatchMiddleware( + new UpdateContext({ + api: this.api, + upload: this.upload, - payload: update, - updateType: type, - source: UpdateSource.POLLING, - })); + payload: update, + updateType: type, + source: UpdateSource.POLLING, + }), + ); } /** @@ -633,15 +549,17 @@ export class Updates { const UpdateContext = webhookContexts[type] || UnsupportedEventContext; - return this.dispatchMiddleware(new UpdateContext({ - api: this.api, - upload: this.upload, + return this.dispatchMiddleware( + new UpdateContext({ + api: this.api, + upload: this.upload, - payload, - groupId, - updateType: type, - source: UpdateSource.WEBHOOK, - })); + payload, + groupId, + updateType: type, + source: UpdateSource.WEBHOOK, + }), + ); } /** @@ -653,9 +571,7 @@ export class Updates { const isGroup = pollingGroupId !== undefined; this.pollingTransport.subscribe( - isGroup - ? this.handleWebhookUpdate.bind(this) - : this.handlePollingUpdate.bind(this), + isGroup ? this.handleWebhookUpdate.bind(this) : this.handlePollingUpdate.bind(this), ); return this.pollingTransport.start(); @@ -680,7 +596,9 @@ export class Updates { if (!this.options.pollingGroupId) { try { - const { groups: [group] } = await this.api.groups.getById({}); + const { + groups: [group], + } = await this.api.groups.getById({}); this.pollingTransport = new PollingTransport({ api: this.api, @@ -707,10 +625,7 @@ export class Updates { * Stopping gets updates */ public async stop(): Promise { - await Promise.all([ - this.pollingTransport.stop(), - this.webhookTransport.stop(), - ]); + await Promise.all([this.pollingTransport.stop(), this.webhookTransport.stop()]); } /** diff --git a/packages/vk-io/src/upload/helpers.ts b/packages/vk-io/src/upload/helpers.ts index b14feb1bb..7b3a7f8ec 100644 --- a/packages/vk-io/src/upload/helpers.ts +++ b/packages/vk-io/src/upload/helpers.ts @@ -1,20 +1,16 @@ -import { Stream, PassThrough } from 'stream'; -import type { UploadNormalizedSourceOptions, UploadAllowedSource } from './types'; +import { PassThrough, Stream } from 'stream'; +import type { UploadAllowedSource, UploadNormalizedSourceOptions } from './types'; /** * Check object is stream */ -export const isStream = (source: NodeJS.ReadableStream | Buffer | string): boolean => ( - typeof source === 'object' && source instanceof Stream -); +export const isStream = (source: NodeJS.ReadableStream | Buffer | string): boolean => + typeof source === 'object' && source instanceof Stream; /** * Copies object params to new object */ -export const pickExistingProperties = < - T, - K extends keyof T ->(params: T, properties: K[]): Pick => { +export const pickExistingProperties = (params: T, properties: K[]): Pick => { const copies: Pick = {} as Pick; for (const property of properties) { @@ -36,9 +32,7 @@ export const normalizeSource = (rawSource: UploadAllowedSource): UploadNormalize return { ...rawSource, - values: Array.isArray(rawSource.values) - ? rawSource.values - : [rawSource.values], + values: Array.isArray(rawSource.values) ? rawSource.values : [rawSource.values], }; }; diff --git a/packages/vk-io/src/upload/types.ts b/packages/vk-io/src/upload/types.ts index c0e925c79..69833bd08 100644 --- a/packages/vk-io/src/upload/types.ts +++ b/packages/vk-io/src/upload/types.ts @@ -1,7 +1,7 @@ import type { Agent } from 'https'; -import type { AllowArray } from '../types'; import type { API } from '../api'; +import type { AllowArray } from '../types'; /** * Stream, buffer, url or file path diff --git a/packages/vk-io/src/upload/upload.ts b/packages/vk-io/src/upload/upload.ts index 1e06df6a6..14c57b62b 100644 --- a/packages/vk-io/src/upload/upload.ts +++ b/packages/vk-io/src/upload/upload.ts @@ -1,56 +1,41 @@ -// eslint-disable-next-line import/extensions -import { FormData, File } from 'formdata-node'; -import { FormDataEncoder } from 'form-data-encoder'; import { AbortController } from 'abort-controller'; +import { FormDataEncoder } from 'form-data-encoder'; +// eslint-disable-next-line import/extensions +import { File, FormData } from 'formdata-node'; import { inspectable } from 'inspectable'; -import { createReadStream, promises as fs } from 'fs'; +import { promises as fs, createReadStream } from 'fs'; import { globalAgent } from 'https'; import { Readable } from 'stream'; import type { API } from '../api'; -import { fetch } from '../utils/fetch'; import { UploadError, UploadErrorCode } from '../errors'; -import { DefaultExtension, DefaultContentType } from '../utils/constants'; -import type { - IUploadOptions, - IUploadParams, - IUploadSourceMedia, - IUploadConduct, -} from './types'; -import { - isStream, - - streamToBuffer, - normalizeSource, - pickExistingProperties, -} from './helpers'; +import { DefaultContentType, DefaultExtension } from '../utils/constants'; +import { fetch } from '../utils/fetch'; +import { isStream, normalizeSource, pickExistingProperties, streamToBuffer } from './helpers'; +import type { IUploadConduct, IUploadOptions, IUploadParams, IUploadSourceMedia } from './types'; import { - StoryAttachment, - PhotoAttachment, AudioAttachment, - VideoAttachment, + AudioMessageAttachment, DocumentAttachment, GraffitiAttachment, - AudioMessageAttachment, + PhotoAttachment, + StoryAttachment, + VideoAttachment, } from '../structures'; const { stat: fileStat } = fs; -const { - MISSING_PARAMETERS, - NO_FILES_TO_UPLOAD, - EXCEEDED_MAX_FILES, - UNSUPPORTED_SOURCE_TYPE, -} = UploadErrorCode; +const { MISSING_PARAMETERS, NO_FILES_TO_UPLOAD, EXCEEDED_MAX_FILES, UNSUPPORTED_SOURCE_TYPE } = UploadErrorCode; const isURL = /^https?:\/\//i; -const DocumentTypes: Record = { +const DocumentTypes: Record< + string, + typeof DocumentAttachment | typeof GraffitiAttachment | typeof AudioMessageAttachment +> = { doc: DocumentAttachment, graffiti: GraffitiAttachment, audio_message: AudioMessageAttachment, @@ -96,7 +81,7 @@ export class Upload { longitude?: number; }, ): Promise { - const photos = await this.conduct({ + const photos = (await this.conduct({ field: 'file', params, @@ -108,14 +93,15 @@ export class Upload { maxFiles: 5, attachmentType: 'photo', - }) as PhotoAttachment['payload'][]; - - return photos.map(photo => ( - new PhotoAttachment({ - api: this.api, - payload: photo, - }) - )); + })) as PhotoAttachment['payload'][]; + + return photos.map( + photo => + new PhotoAttachment({ + api: this.api, + payload: photo, + }), + ); } /** @@ -159,13 +145,13 @@ export class Upload { owner_id?: number; }, ): Promise<{ - photo_hash: string; - photo_src: string; - photo_src_big: string; - photo_src_small: string; - saved: number; - post_id: number; - }> { + photo_hash: string; + photo_src: string; + photo_src_big: string; + photo_src_small: string; + saved: number; + post_id: number; + }> { return this.conduct({ field: 'photo', params, @@ -228,9 +214,9 @@ export class Upload { crop_width?: number; }, ): Promise<{ - message_id: number; - chat: object; - }> { + message_id: number; + chat: object; + }> { return this.conduct({ field: 'file', params, @@ -238,9 +224,7 @@ export class Upload { getServer: this.api.photos.getChatUploadServer, serverParams: ['chat_id', 'crop_x', 'crop_y', 'crop_width'], - saveFiles: file => ( - this.api.messages.setChatPhoto({ file }) - ), + saveFiles: file => this.api.messages.setChatPhoto({ file }), maxFiles: 1, attachmentType: 'photo', @@ -411,20 +395,22 @@ export class Upload { compression?: number; }, ): Promise { - const save = await this.api.video.save(pickExistingProperties(params, [ - 'group_id', - 'album_id', - 'link', - 'name', - 'description', - 'is_private', - 'wallpost', - 'privacy_view', - 'privacy_comment', - 'no_comments', - 'repeat', - 'compression', - ])); + const save = await this.api.video.save( + pickExistingProperties(params, [ + 'group_id', + 'album_id', + 'link', + 'name', + 'description', + 'is_private', + 'wallpost', + 'privacy_view', + 'privacy_comment', + 'no_comments', + 'repeat', + 'compression', + ]), + ); save.id = save.video_id; @@ -507,7 +493,10 @@ export class Upload { /** * Uploads wall document */ - async conductWallDocument(params: IUploadParams & { type?: string }, { attachmentType = 'doc' } = {}): Promise { + async conductWallDocument( + params: IUploadParams & { type?: string }, + { attachmentType = 'doc' } = {}, + ): Promise { const response = await this.conduct({ field: 'file', params, @@ -550,7 +539,10 @@ export class Upload { /** * Uploads wall document */ - async conductMessageDocument(params: IUploadParams & { type?: string }, { attachmentType = 'doc' } = {}): Promise { + async conductMessageDocument( + params: IUploadParams & { type?: string }, + { attachmentType = 'doc' } = {}, + ): Promise { const response = await this.conduct({ field: 'file', params, @@ -680,12 +672,12 @@ export class Upload { crop_y2?: number; }, ): Promise<{ - images: { - url: string; - width: number; - height: number; - }[]; - }> { + images: { + url: string; + width: number; + height: number; + }[]; + }> { return this.conduct({ field: 'photo', params, @@ -744,7 +736,9 @@ export class Upload { clickable_stickers?: string; }, ): Promise { - const { items: [story] } = await this.conduct({ + const { + items: [story], + } = await this.conduct({ field: 'file', params, @@ -760,11 +754,10 @@ export class Upload { 'clickable_stickers', ], - saveFiles: file => ( + saveFiles: file => this.api.stories.save({ upload_results: file.upload_result, - }) - ), + }), maxFiles: 1, attachmentType: 'photo', @@ -790,7 +783,9 @@ export class Upload { clickable_stickers?: string; }, ): Promise { - const { items: [story] } = await this.conduct({ + const { + items: [story], + } = await this.conduct({ field: 'video_file', params, @@ -805,11 +800,10 @@ export class Upload { 'clickable_stickers', ], - saveFiles: file => ( + saveFiles: file => this.api.stories.save({ upload_results: file.upload_result, - }) - ), + }), maxFiles: 1, attachmentType: 'video', @@ -873,9 +867,10 @@ export class Upload { const { uploadUrl: sourceUploadUrl } = source; if (sourceUploadUrl !== undefined) { - getServer = (): Promise<{ upload_url: string }> => Promise.resolve({ - upload_url: sourceUploadUrl, - }); + getServer = (): Promise<{ upload_url: string }> => + Promise.resolve({ + upload_url: sourceUploadUrl, + }); } const { length: valuesLength } = source.values; @@ -942,7 +937,7 @@ export class Upload { values: IUploadSourceMedia[]; maxFiles: number; attachmentType?: string; - }): Promise<{ formData: FormData; knownLength: boolean; }> { + }): Promise<{ formData: FormData; knownLength: boolean }> { const formData = new FormData(); const isMultipart = maxFiles > 1; @@ -980,28 +975,24 @@ export class Upload { const isBuffer = Buffer.isBuffer(value); if (isStream(value) || isBuffer) { - const name = isMultipart - ? field + (i + 1) - : field; + const name = isMultipart ? field + (i + 1) : field; const { contentType } = media; - const fileContentType = contentType - || DefaultContentType[attachmentType as keyof typeof DefaultContentType]; + const fileContentType = + contentType || DefaultContentType[attachmentType as keyof typeof DefaultContentType]; const file = isBuffer ? new File([value as Buffer], filename, { - type: fileContentType, - }) - // Workground for NodeJS streams: https://github.com/octet-stream/form-data/issues/32 - : { - size: Number(contentLength), - type: fileContentType, - stream: () => ( - value - ), - [Symbol.toStringTag]: 'Blob', - }; + type: fileContentType, + }) + : // Workground for NodeJS streams: https://github.com/octet-stream/form-data/issues/32 + { + size: Number(contentLength), + type: fileContentType, + stream: () => value, + [Symbol.toStringTag]: 'Blob', + }; if (!contentLength) { knownLength = false; @@ -1029,11 +1020,18 @@ export class Upload { /** * Upload form data */ - async upload(url: URL | string, { formData, timeout, forceBuffer }: { - formData: FormData; - timeout: number | undefined; - forceBuffer: boolean; - }): Promise { + async upload( + url: URL | string, + { + formData, + timeout, + forceBuffer, + }: { + formData: FormData; + timeout: number | undefined; + forceBuffer: boolean; + }, + ): Promise { const { agent, uploadTimeout } = this.options; const encoder = new FormDataEncoder(formData); @@ -1049,9 +1047,7 @@ export class Upload { ...encoder.headers, }; - const body = forceBuffer - ? await streamToBuffer(rawBody) - : rawBody; + const body = forceBuffer ? await streamToBuffer(rawBody) : rawBody; if (forceBuffer) { headers['Content-Length'] = String((body as Buffer).length); @@ -1070,11 +1066,9 @@ export class Upload { if (!response.ok) { throw new Error(response.statusText); } - const result = await response.json() as any; + const result = (await response.json()) as any; - return result.response !== undefined - ? result.response - : result; + return result.response !== undefined ? result.response : result; } finally { clearTimeout(interval); } diff --git a/packages/vk-io/src/utils/callback-service.ts b/packages/vk-io/src/utils/callback-service.ts index b43937dca..40890fae5 100644 --- a/packages/vk-io/src/utils/callback-service.ts +++ b/packages/vk-io/src/utils/callback-service.ts @@ -1,12 +1,9 @@ import type { APIRequest } from '../api/request'; -import { VKError, SharedErrorCode } from '../errors'; +import { SharedErrorCode, VKError } from '../errors'; import type { CaptchaType } from './constants'; -const { - MISSING_CAPTCHA_HANDLER, - MISSING_TWO_FACTOR_HANDLER, -} = SharedErrorCode; +const { MISSING_CAPTCHA_HANDLER, MISSING_TWO_FACTOR_HANDLER } = SharedErrorCode; export interface ICallbackServiceCaptchaPayload { type: CaptchaType; @@ -24,12 +21,12 @@ export type CallbackServiceRetry = (code: Error | string) => Promise; export type CaptchaHandler = ( payload: ICallbackServiceCaptchaPayload, - retry: CallbackServiceRetry + retry: CallbackServiceRetry, ) => Promise | void; export type TwoFactorHandler = ( payload: ICallbackServiceTwoFactorPayload, - retry: CallbackServiceRetry + retry: CallbackServiceRetry, ) => Promise | void; export interface ICallbackServiceValidate { @@ -84,31 +81,35 @@ export class CallbackService { const { captchaHandler } = this; if (captchaHandler === undefined) { - return Promise.reject(new VKError({ - message: 'Missing captcha handler', - code: MISSING_CAPTCHA_HANDLER, - })); + return Promise.reject( + new VKError({ + message: 'Missing captcha handler', + code: MISSING_CAPTCHA_HANDLER, + }), + ); } return new Promise((resolveProcessing, rejectProcessing): void => { - void captchaHandler(payload, (key): Promise => ( - new Promise((resolve, reject): void => { - if (key instanceof Error) { - reject(key); - rejectProcessing(key); - - return; - } - - resolveProcessing({ - key, - validate: { - resolve, - reject, - }, - }); - }) - )); + void captchaHandler( + payload, + (key): Promise => + new Promise((resolve, reject): void => { + if (key instanceof Error) { + reject(key); + rejectProcessing(key); + + return; + } + + resolveProcessing({ + key, + validate: { + resolve, + reject, + }, + }); + }), + ); }); } @@ -122,31 +123,35 @@ export class CallbackService { const { twoFactorHandler } = this; if (twoFactorHandler === undefined) { - return Promise.reject(new VKError({ - message: 'Missing two-factor handler', - code: MISSING_TWO_FACTOR_HANDLER, - })); + return Promise.reject( + new VKError({ + message: 'Missing two-factor handler', + code: MISSING_TWO_FACTOR_HANDLER, + }), + ); } return new Promise((resolveProcessing, rejectProcessing): void => { - void twoFactorHandler(payload, (code): Promise => ( - new Promise((resolve, reject): void => { - if (code instanceof Error) { - reject(code); - rejectProcessing(code); - - return; - } - - resolveProcessing({ - code, - validate: { - resolve, - reject, - }, - }); - }) - )); + void twoFactorHandler( + payload, + (code): Promise => + new Promise((resolve, reject): void => { + if (code instanceof Error) { + reject(code); + rejectProcessing(code); + + return; + } + + resolveProcessing({ + code, + validate: { + resolve, + reject, + }, + }); + }), + ); }); } } diff --git a/packages/vk-io/src/utils/constants.ts b/packages/vk-io/src/utils/constants.ts index 8b6234121..951170773 100644 --- a/packages/vk-io/src/utils/constants.ts +++ b/packages/vk-io/src/utils/constants.ts @@ -29,26 +29,26 @@ export enum AttachmentType { POLL = 'poll', PODCAST = 'podcast', STORY = 'story', - TEXTLIVE = 'textlive' + TEXTLIVE = 'textlive', } export type AttachmentTypeString = -'album' -| 'audio' -| 'audio_message' -| 'graffiti' -| 'doc' -| 'market_album' -| 'market' -| 'photo' -| 'story' -| 'video' -| 'wall' -| 'poll' -| 'gift' -| 'link' -| 'sticker' -| 'wall_reply'; + | 'album' + | 'audio' + | 'audio_message' + | 'graffiti' + | 'doc' + | 'market_album' + | 'market' + | 'photo' + | 'story' + | 'video' + | 'wall' + | 'poll' + | 'gift' + | 'link' + | 'sticker' + | 'wall_reply'; /** * Default extensions for attachments @@ -58,7 +58,7 @@ export enum DefaultExtension { video = 'mp4', audio = 'mp3', graffiti = 'png', - audioMessage = 'ogg' + audioMessage = 'ogg', } /** @@ -69,7 +69,7 @@ export enum DefaultContentType { video = 'video/mp4', audio = 'audio/mp3', graffiti = 'image/png', - audioMessage = 'audio/ogg' + audioMessage = 'audio/ogg', } /** @@ -79,7 +79,7 @@ export enum CaptchaType { API = 'API', DIRECT_AUTH = 'DIRECT_AUTH', IMPLICIT_FLOW_AUTH = 'IMPLICIT_FLOW_AUTH', - ACCOUNT_VERIFICATION = 'ACCOUNT_VERIFICATION' + ACCOUNT_VERIFICATION = 'ACCOUNT_VERIFICATION', } /** @@ -89,7 +89,7 @@ export enum MessageSource { USER = 'user', CHAT = 'chat', GROUP = 'group', - EMAIL = 'email' + EMAIL = 'email', } /** @@ -98,7 +98,7 @@ export enum MessageSource { export enum ResourceType { USER = 'user', GROUP = 'group', - APPLICATION = 'application' + APPLICATION = 'application', } /** @@ -107,7 +107,7 @@ export enum ResourceType { export enum UpdateSource { POLLING = 'POLLING', WEBHOOK = 'WEBHOOK', - WEBSOCKET = 'WEBSOCKET' + WEBSOCKET = 'WEBSOCKET', } /** @@ -117,7 +117,7 @@ export enum UploadErrorCode { MISSING_PARAMETERS = 'MISSING_PARAMETERS', NO_FILES_TO_UPLOAD = 'NO_FILES_TO_UPLOAD', EXCEEDED_MAX_FILES = 'EXCEEDED_MAX_FILES', - UNSUPPORTED_SOURCE_TYPE = 'UNSUPPORTED_SOURCE_TYPE' + UNSUPPORTED_SOURCE_TYPE = 'UNSUPPORTED_SOURCE_TYPE', } /** @@ -125,14 +125,14 @@ export enum UploadErrorCode { */ export enum UpdatesErrorCode { NEED_RESTART = 'NEED_RESTART', - POLLING_REQUEST_FAILED = 'POLLING_REQUEST_FAILED' + POLLING_REQUEST_FAILED = 'POLLING_REQUEST_FAILED', } /** * Collect error codes */ export enum CollectErrorCode { - EXECUTE_ERROR = 'EXECUTE_ERROR' + EXECUTE_ERROR = 'EXECUTE_ERROR', } /** @@ -141,7 +141,7 @@ export enum CollectErrorCode { export enum ResourceErrorCode { INVALID_URL = 'INVALID_URL', INVALID_RESOURCE = 'INVALID_RESOURCE', - RESOURCE_NOT_FOUND = 'RESOURCE_NOT_FOUND' + RESOURCE_NOT_FOUND = 'RESOURCE_NOT_FOUND', } /** @@ -149,7 +149,7 @@ export enum ResourceErrorCode { */ export enum SharedErrorCode { MISSING_CAPTCHA_HANDLER = 'MISSING_CAPTCHA_HANDLER', - MISSING_TWO_FACTOR_HANDLER = 'MISSING_TWO_FACTOR_HANDLER' + MISSING_TWO_FACTOR_HANDLER = 'MISSING_TWO_FACTOR_HANDLER', } /** diff --git a/packages/vk-io/src/utils/fetch.ts b/packages/vk-io/src/utils/fetch.ts index 98a12b9a8..9d29297fc 100644 --- a/packages/vk-io/src/utils/fetch.ts +++ b/packages/vk-io/src/utils/fetch.ts @@ -9,6 +9,5 @@ export type RequestInfo = import('node-fetch').RequestInfo | URL; export type RequestInit = import('node-fetch').RequestInit; export type Response = import('node-fetch').Response; -export const fetch = (url: RequestInfo, init?: RequestInit): Promise => ( - Promise.resolve(fetchPromise).then(fn => fn(url as string, init)) -); +export const fetch = (url: RequestInfo, init?: RequestInit): Promise => + Promise.resolve(fetchPromise).then(fn => fn(url as string, init)); diff --git a/packages/vk-io/src/utils/helpers.ts b/packages/vk-io/src/utils/helpers.ts index 8f7bc9f28..20131900c 100644 --- a/packages/vk-io/src/utils/helpers.ts +++ b/packages/vk-io/src/utils/helpers.ts @@ -3,30 +3,21 @@ import { MessageSource, PEER_CHAT_ID_OFFSET } from './constants'; /** * Returns params for execute */ -export const getExecuteParams = (params: Record): string => ( - JSON.stringify(params, (key, value) => ( - typeof value === 'object' && value !== params - ? String(value) - : value as unknown - )) -); +export const getExecuteParams = (params: Record): string => + JSON.stringify(params, (key, value) => + typeof value === 'object' && value !== params ? String(value) : (value as unknown), + ); /** * Returns method for execute */ -export const getExecuteMethod = ( - method: string, - params: Record = {}, -): string => ( - `API.${method}(${getExecuteParams(params)})` -); +export const getExecuteMethod = (method: string, params: Record = {}): string => + `API.${method}(${getExecuteParams(params)})`; /** * Returns chain for execute */ -export const getChainReturn = (methods: string[]): string => ( - `return [${methods.join(',')}];` -); +export const getChainReturn = (methods: string[]): string => `return [${methods.join(',')}];`; /** * Resolve task @@ -59,18 +50,15 @@ export const resolveExecuteTask = ( /** * Returns random ID */ -export const getRandomId = (): number => ( - Math.floor(Math.random() * 10_000) * Date.now() -); +export const getRandomId = (): number => Math.floor(Math.random() * 10_000) * Date.now(); /** * Delay N-ms */ -export const delay = (delayed: number): Promise => ( +export const delay = (delayed: number): Promise => new Promise((resolve): void => { setTimeout(resolve, delayed); - }) -); + }); const lt = /</g; const qt = />/g; @@ -81,22 +69,13 @@ const quot = /"/g; /** * Decodes HTML entities */ -export const unescapeHTML = (text: string): string => ( - text - .replace(lt, '<') - .replace(qt, '>') - .replace(br, '\n') - .replace(amp, '&') - .replace(quot, '"') -); +export const unescapeHTML = (text: string): string => + text.replace(lt, '<').replace(qt, '>').replace(br, '\n').replace(amp, '&').replace(quot, '"'); /** * Copies object params to new object */ -export const pickProperties = < - T, - K extends keyof T ->(params: T, properties: K[]): Pick => { +export const pickProperties = (params: T, properties: K[]): Pick => { const copies: Pick = {} as Pick; for (const property of properties) { diff --git a/packages/vk-io/src/utils/resource-resolver.ts b/packages/vk-io/src/utils/resource-resolver.ts index a057b9c64..7fad4e91e 100644 --- a/packages/vk-io/src/utils/resource-resolver.ts +++ b/packages/vk-io/src/utils/resource-resolver.ts @@ -1,7 +1,7 @@ import type { API } from '../api'; import { ResourceError } from '../errors'; -import { ResourceType, ResourceErrorCode } from './constants'; +import { ResourceErrorCode, ResourceType } from './constants'; export interface IResolveResourceOptions { resource: string | number; @@ -26,7 +26,8 @@ const isHttpsRe = /^https:\/\//i; const isVKUrlRe = /^(?:https?:\/\/)?(?:m\.)?(?:vk\.(?:com|me|ru)|vkontakte\.ru)\//i; const parseTargetResourceRe = /^(id|club|public|albums|tag|app)(-?\d+)$/i; -const parseOwnerResourceRe = /^(album|topic|page|photo|video|audio|doc|audio_message|graffiti|wall|market|poll|gift)(-?\d+)_(\d+)/i; +const parseOwnerResourceRe = + /^(album|topic|page|photo|video|audio|doc|audio_message|graffiti|wall|market|poll|gift)(-?\d+)_(\d+)/i; const enumResourceTypes: Record = { id: ResourceType.USER, @@ -35,11 +36,8 @@ const enumResourceTypes: Record = { app: ResourceType.APPLICATION, }; -const transformNumberResourceToTarget = (resource: number): string => ( - resource < 0 - ? `club${-resource}` - : `id${resource}` -); +const transformNumberResourceToTarget = (resource: number): string => + resource < 0 ? `club${-resource}` : `id${resource}`; const transformMentionResourceToTarget = (resource: string): string => { // biome-ignore lint/style/noNonNullAssertion: we already check by test pattern @@ -53,7 +51,7 @@ const resolveTargetResouce = (resource: string): IResolvedTargetResource => { const { 1: rawType, 2: rawId } = resource.match(parseTargetResourceRe)! as [ never, IResolvedTargetResource['type'], - number + number, ]; return { @@ -73,10 +71,7 @@ const resolveOwnerResource = (resource: string): IResolvedOwnerResource => { }; }; -const resolveSlugResource = async ( - resource: string, - api?: API, -): Promise => { +const resolveSlugResource = async (resource: string, api?: API): Promise => { if (api === undefined) { throw new Error('API object is not passed'); } @@ -109,19 +104,11 @@ export const resolveResource = async ({ const resource = String(rawResource).trim(); if (onlyNumberRe.test(resource)) { - return resolveTargetResouce( - transformNumberResourceToTarget( - Number(resource), - ), - ); + return resolveTargetResouce(transformNumberResourceToTarget(Number(resource))); } if (systemMentionRe.test(resource)) { - return resolveTargetResouce( - transformMentionResourceToTarget( - resource, - ), - ); + return resolveTargetResouce(transformMentionResourceToTarget(resource)); } if (parseOwnerResourceRe.test(resource)) { @@ -136,9 +123,7 @@ export const resolveResource = async ({ return resolveSlugResource(resource, api); } - const resourceUrl = !isHttpsRe.test(resource) - ? `https://${resource}` - : resource; + const resourceUrl = !isHttpsRe.test(resource) ? `https://${resource}` : resource; const { pathname: rawPathname, searchParams } = new URL(resourceUrl); diff --git a/packages/vk-io/src/vk.ts b/packages/vk-io/src/vk.ts index a8ab1e99b..160d547b6 100644 --- a/packages/vk-io/src/vk.ts +++ b/packages/vk-io/src/vk.ts @@ -1,8 +1,8 @@ import { inspectable } from 'inspectable'; import { API } from './api'; -import { Upload } from './upload'; import { Updates } from './updates'; +import { Upload } from './upload'; import { CallbackService } from './utils/callback-service'; import type { VKOptions } from './types'; @@ -23,8 +23,7 @@ export class VK { * Constructor */ public constructor(options: Partial & { token: string }) { - this.callbackService = options.callbackService - || new CallbackService(); + this.callbackService = options.callbackService || new CallbackService(); this.api = new API({ ...options, diff --git a/packages/vk-io/test/attachments.test.ts b/packages/vk-io/test/attachments.test.ts index b04407f3b..c2c45fe0e 100644 --- a/packages/vk-io/test/attachments.test.ts +++ b/packages/vk-io/test/attachments.test.ts @@ -1,23 +1,22 @@ -import { describe, it } from 'node:test'; import { strictEqual, throws } from 'node:assert'; +import { describe, it } from 'node:test'; import { - VK, Attachment, - - WallAttachment, - PhotoAttachment, AudioAttachment, + DocumentAttachment, + MarketAlbumAttachment, + MarketAttachment, + PhotoAttachment, StoryAttachment, + VK, VideoAttachment, - MarketAttachment, - DocumentAttachment, - MarketAlbumAttachment + WallAttachment, } from '..'; const vk = new VK({ // biome-ignore lint/style/noNonNullAssertion: to be honest, they're just tests - token: process.env.TOKEN! + token: process.env.TOKEN!, }); describe('Attachments', (): void => { @@ -27,8 +26,8 @@ describe('Attachments', (): void => { type: 'photo', payload: { id: 5678, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'photo1234_5678'); @@ -41,8 +40,8 @@ describe('Attachments', (): void => { payload: { id: 5678, owner_id: 1234, - access_key: 'ACCESS_KEY' - } + access_key: 'ACCESS_KEY', + }, }); strictEqual(String(attachment), 'photo1234_5678_ACCESS_KEY'); @@ -59,17 +58,17 @@ describe('Attachments', (): void => { it('should be correct parse', (): void => { const photo1 = Attachment.fromString('photo1234_5678', vk.api); - strictEqual(photo1.type, 'photo'); - strictEqual(photo1.ownerId, 1234); - strictEqual(photo1.id, 5678); - strictEqual(photo1.accessKey, undefined); + strictEqual(photo1.type, 'photo'); + strictEqual(photo1.ownerId, 1234); + strictEqual(photo1.id, 5678); + strictEqual(photo1.accessKey, undefined); const photo2 = Attachment.fromString('photo1234_5678_ACCESS_KEY', vk.api); - strictEqual(photo2.type, 'photo'); - strictEqual(photo2.ownerId, 1234); - strictEqual(photo2.id, 5678); - strictEqual(photo2.accessKey, 'ACCESS_KEY'); + strictEqual(photo2.type, 'photo'); + strictEqual(photo2.ownerId, 1234); + strictEqual(photo2.id, 5678); + strictEqual(photo2.accessKey, 'ACCESS_KEY'); }); }); @@ -80,8 +79,8 @@ describe('Attachments', (): void => { type: 'photo', payload: { id: 5678, - owner_id: 1234 - } + owner_id: 1234, + }, }); throws((): boolean => attachment.equals('ascbas_baasd')); @@ -95,34 +94,40 @@ describe('Attachments', (): void => { type: 'photo', payload: { id: 5678, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(attachment.equals('photo1234_1234'), false); - strictEqual(attachment.equals( - new Attachment({ - api: vk.api, - type: 'photo', - payload: { - id: 1234, - owner_id: 1234 - } - }) - ), false); - - strictEqual(attachment.equals( - new Attachment({ - api: vk.api, - type: 'photo', - payload: { - id: 1234, - owner_id: 1234, - access_key: 'ACCESS_KEY' - } - }) - ), false); + strictEqual( + attachment.equals( + new Attachment({ + api: vk.api, + type: 'photo', + payload: { + id: 1234, + owner_id: 1234, + }, + }), + ), + false, + ); + + strictEqual( + attachment.equals( + new Attachment({ + api: vk.api, + type: 'photo', + payload: { + id: 1234, + owner_id: 1234, + access_key: 'ACCESS_KEY', + }, + }), + ), + false, + ); }); it('should be return true', (): void => { @@ -131,34 +136,40 @@ describe('Attachments', (): void => { type: 'photo', payload: { id: 5678, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(attachment.equals('photo1234_5678'), true); - strictEqual(attachment.equals( - new Attachment({ - api: vk.api, - type: 'photo', - payload: { - id: 5678, - owner_id: 1234 - } - }) - ), true); - - strictEqual(attachment.equals( - new Attachment({ - api: vk.api, - type: 'photo', - payload: { - id: 5678, - owner_id: 1234, - access_key: 'ACCESS_KEY' - } - }) - ), true); + strictEqual( + attachment.equals( + new Attachment({ + api: vk.api, + type: 'photo', + payload: { + id: 5678, + owner_id: 1234, + }, + }), + ), + true, + ); + + strictEqual( + attachment.equals( + new Attachment({ + api: vk.api, + type: 'photo', + payload: { + id: 5678, + owner_id: 1234, + access_key: 'ACCESS_KEY', + }, + }), + ), + true, + ); }); }); @@ -168,8 +179,8 @@ describe('Attachments', (): void => { api: vk.api, payload: { id: 4567, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'wall1234_4567'); @@ -180,8 +191,8 @@ describe('Attachments', (): void => { api: vk.api, payload: { id: 4567, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'photo1234_4567'); @@ -192,8 +203,8 @@ describe('Attachments', (): void => { api: vk.api, payload: { id: 4567, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'audio1234_4567'); @@ -204,8 +215,8 @@ describe('Attachments', (): void => { api: vk.api, payload: { id: 4567, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'story1234_4567'); @@ -216,8 +227,8 @@ describe('Attachments', (): void => { api: vk.api, payload: { id: 4567, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'video1234_4567'); @@ -228,8 +239,8 @@ describe('Attachments', (): void => { api: vk.api, payload: { id: 4567, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'market1234_4567'); @@ -240,8 +251,8 @@ describe('Attachments', (): void => { api: vk.api, payload: { id: 4567, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'doc1234_4567'); @@ -252,8 +263,8 @@ describe('Attachments', (): void => { api: vk.api, payload: { id: 4567, - owner_id: 1234 - } + owner_id: 1234, + }, }); strictEqual(String(attachment), 'market_album1234_4567'); diff --git a/packages/vk-io/test/contexts.test.ts b/packages/vk-io/test/contexts.test.ts index d8ec9e87f..cb0c194cd 100644 --- a/packages/vk-io/test/contexts.test.ts +++ b/packages/vk-io/test/contexts.test.ts @@ -1,16 +1,11 @@ -import { describe, it } from 'node:test'; import { strictEqual } from 'node:assert'; +import { describe, it } from 'node:test'; -import { - VK, - - Context, - UpdateSource -} from '..'; +import { Context, UpdateSource, VK } from '..'; const vk = new VK({ // biome-ignore lint/style/noNonNullAssertion: to be honest, they're just tests - token: process.env.TOKEN! + token: process.env.TOKEN!, }); const { api, upload } = vk; @@ -27,7 +22,7 @@ describe('Contexts', (): void => { subTypes: ['edit_message', 'text'], payload: {}, updateType: 'test', - source: UpdateSource.POLLING + source: UpdateSource.POLLING, }); return context; diff --git a/packages/vk-io/test/resource-resolver.test.ts b/packages/vk-io/test/resource-resolver.test.ts index ee573881a..946bbea93 100644 --- a/packages/vk-io/test/resource-resolver.test.ts +++ b/packages/vk-io/test/resource-resolver.test.ts @@ -1,14 +1,7 @@ -import { describe, it } from 'node:test'; import { deepStrictEqual } from 'node:assert'; +import { describe, it } from 'node:test'; -import { - type IResolvedTargetResource, - type IResolvedOwnerResource, - - VK, - - resolveResource -} from '..'; +import { type IResolvedOwnerResource, type IResolvedTargetResource, VK, resolveResource } from '..'; const { TOKEN } = process.env; @@ -17,18 +10,18 @@ const vk = new VK({ token: TOKEN! }); const durovUser: IResolvedTargetResource = { id: 1, - type: 'user' + type: 'user', }; const durovPhoto: IResolvedOwnerResource = { id: 456264771, ownerId: 1, - type: 'photo' + type: 'photo', }; const apiclubGroup: IResolvedTargetResource = { id: 1, - type: 'group' + type: 'group', }; const dataset: [string | number, IResolvedTargetResource | IResolvedOwnerResource][] = [ @@ -57,40 +50,59 @@ const dataset: [string | number, IResolvedTargetResource | IResolvedOwnerResourc ['[public1|APICLUB]', apiclubGroup], ['public1', apiclubGroup], ['apiclub', apiclubGroup], - ['app1', { - id: 1, - type: 'application' - }], - ['albums1', { - id: 1, // User ID - type: 'albums' - }], - ['album1_0', { - id: 0, - ownerId: 1, - type: 'album' - }], - ['https://vk.com/id1?w=wall1_32279', { - id: 32279, - ownerId: 1, - type: 'wall' - }], - ['https://vk.com/club1?w=wall-1_49296', { - id: 49296, - ownerId: -1, - type: 'wall' - }] + [ + 'app1', + { + id: 1, + type: 'application', + }, + ], + [ + 'albums1', + { + id: 1, // User ID + type: 'albums', + }, + ], + [ + 'album1_0', + { + id: 0, + ownerId: 1, + type: 'album', + }, + ], + [ + 'https://vk.com/id1?w=wall1_32279', + { + id: 32279, + ownerId: 1, + type: 'wall', + }, + ], + [ + 'https://vk.com/club1?w=wall-1_49296', + { + id: 49296, + ownerId: -1, + type: 'wall', + }, + ], ]; describe('resolveResource', (): void => { for (const [resource, result] of dataset) { - it(`should resolve correctly "${resource}"`, { timeout: 60_000, skip: TOKEN === undefined ? 'not set env TOKEN=' : undefined }, async (): Promise => { - const resolvedResource = await resolveResource({ - resource, - api: vk.api - }); + it( + `should resolve correctly "${resource}"`, + { timeout: 60_000, skip: TOKEN === undefined ? 'not set env TOKEN=' : undefined }, + async (): Promise => { + const resolvedResource = await resolveResource({ + resource, + api: vk.api, + }); - deepStrictEqual(resolvedResource, result); - }); + deepStrictEqual(resolvedResource, result); + }, + ); } }); diff --git a/packages/vk-io/test/types/updates-http-webhook.ts b/packages/vk-io/test/types/updates-http-webhook.ts index 354445a63..eb2f584d9 100644 --- a/packages/vk-io/test/types/updates-http-webhook.ts +++ b/packages/vk-io/test/types/updates-http-webhook.ts @@ -6,7 +6,7 @@ import { createServer } from 'http'; import { VK } from '../..'; const vk = new VK({ - token: '12345' + token: '12345', }); const app = express(); diff --git a/packages/vk-io/test/types/updates-koa-webhook copy.ts b/packages/vk-io/test/types/updates-koa-webhook copy.ts index c64c4d817..1c0e58b13 100644 --- a/packages/vk-io/test/types/updates-koa-webhook copy.ts +++ b/packages/vk-io/test/types/updates-koa-webhook copy.ts @@ -4,7 +4,7 @@ import Koa from 'koa'; import { VK } from '../..'; const vk = new VK({ - token: '12345' + token: '12345', }); const app = new Koa(); diff --git a/packages/vk-io/test/uploads.test.ts b/packages/vk-io/test/uploads.test.ts index 4999f99bc..d565d587f 100644 --- a/packages/vk-io/test/uploads.test.ts +++ b/packages/vk-io/test/uploads.test.ts @@ -1,14 +1,7 @@ +import { notStrictEqual, ok, strictEqual } from 'node:assert'; import { describe, it } from 'node:test'; -import { strictEqual, notStrictEqual, ok } from 'node:assert'; -import { - VK, - - UploadError, - UploadErrorCode, - - PhotoAttachment -} from '..'; +import { PhotoAttachment, UploadError, UploadErrorCode, VK } from '..'; import { fetch } from '../src/utils/fetch'; @@ -44,8 +37,8 @@ describe('Uploads', { timeout: 30_000 }, (): void => { try { await upload.messagePhoto({ source: { - values: [] - } + values: [], + }, }); } catch (error) { ok(error instanceof UploadError); @@ -59,13 +52,13 @@ describe('Uploads', { timeout: 30_000 }, (): void => { source: { values: [ { - value: IMAGE_URL + value: IMAGE_URL, }, { - value: IMAGE_URL - } - ] - } + value: IMAGE_URL, + }, + ], + }, }); } catch (error) { ok(error instanceof UploadError); @@ -73,15 +66,13 @@ describe('Uploads', { timeout: 30_000 }, (): void => { } }); - const skip = TOKEN === undefined - ? 'not set env TOKEN=' - : undefined; + const skip = TOKEN === undefined ? 'not set env TOKEN=' : undefined; it('should upload image to message from url', { skip }, async (): Promise => { const photo = await upload.messagePhoto({ source: { - value: IMAGE_URL - } + value: IMAGE_URL, + }, }); ok(photo instanceof PhotoAttachment); @@ -95,8 +86,8 @@ describe('Uploads', { timeout: 30_000 }, (): void => { const photo = await upload.messagePhoto({ source: { - value: buffer - } + value: buffer, + }, }); ok(photo instanceof PhotoAttachment); @@ -112,8 +103,8 @@ describe('Uploads', { timeout: 30_000 }, (): void => { // biome-ignore lint/style/noNonNullAssertion: testing... value: response.body!, // @ts-expect-error - contentLength: response.headers.get('content-length') - } + contentLength: response.headers.get('content-length'), + }, }); ok(photo instanceof PhotoAttachment);