Skip to content

Commit

Permalink
linting, formatting, most of the way there for express receiver specs
Browse files Browse the repository at this point in the history
  • Loading branch information
filmaj committed Sep 25, 2024
1 parent 8f6e625 commit 5785beb
Show file tree
Hide file tree
Showing 34 changed files with 287 additions and 501 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"prepare": "npm run build",
"build": "npm run build:clean && tsc",
"build:clean": "shx rm -rf ./dist ./coverage",
"lint": "npx @biomejs/biome check --write docs src types-tests",
"lint": "npx @biomejs/biome check --write docs src test types-tests",
"test": "npm run build && npm run lint && npm run test:types && npm run test:coverage",
"test:unit": "TS_NODE_PROJECT=tsconfig.json mocha --config test/unit/.mocharc.json",
"test:coverage": "c8 npm run test:unit",
Expand Down
37 changes: 15 additions & 22 deletions src/receivers/ExpressReceiver.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import crypto from 'crypto';
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { type Server, type ServerOptions, createServer } from 'http';
import type { IncomingMessage, ServerResponse } from 'http';
import crypto from 'node:crypto';
import { type Server, type ServerOptions, createServer } from 'node:http';
import type { IncomingMessage, ServerResponse } from 'node:http';
import {
type Server as HTTPSServer,
type ServerOptions as HTTPSServerOptions,
createServer as createHttpsServer,
} from 'https';
import type { ListenOptions } from 'net';
import querystring from 'querystring';
} from 'node:https';
import type { ListenOptions } from 'node:net';
import querystring from 'node:querystring';
import { ConsoleLogger, LogLevel, type Logger } from '@slack/logger';
import {
type CallbackOptions,
Expand All @@ -32,12 +30,7 @@ import type App from '../App';
import { type CodedError, ReceiverAuthenticityError, ReceiverInconsistentStateError } from '../errors';
import type { AnyMiddlewareArgs, Receiver, ReceiverEvent } from '../types';
import type { StringIndexed } from '../types/helpers';
import {
type ReceiverDispatchErrorHandlerArgs,
type ReceiverProcessEventErrorHandlerArgs,
type ReceiverUnhandledRequestHandlerArgs,
HTTPModuleFunctions as httpFunc,
} from './HTTPModuleFunctions';
import * as httpFunc from './HTTPModuleFunctions';
import { HTTPResponseAck } from './HTTPResponseAck';
import { verifyRedirectOpts } from './verify-redirect-opts';

Expand Down Expand Up @@ -79,15 +72,15 @@ const missingServerErrorDescription =
'The receiver cannot be started because private state was mutated. Please report this to the maintainers.';

export const respondToSslCheck: RequestHandler = (req, res, next) => {
if (req.body && req.body.ssl_check) {
if (req.body?.ssl_check) {
res.send();
return;
}
next();
};

export const respondToUrlVerification: RequestHandler = (req, res, next) => {
if (req.body && req.body.type && req.body.type === 'url_verification') {
if (req.body?.type && req.body.type === 'url_verification') {
res.json({ challenge: req.body.challenge });
return;
}
Expand Down Expand Up @@ -117,12 +110,12 @@ export interface ExpressReceiverOptions {
app?: Application;
router?: IRouter;
customPropertiesExtractor?: (request: Request) => StringIndexed;
dispatchErrorHandler?: (args: ReceiverDispatchErrorHandlerArgs) => Promise<void>;
processEventErrorHandler?: (args: ReceiverProcessEventErrorHandlerArgs) => Promise<boolean>;
dispatchErrorHandler?: (args: httpFunc.ReceiverDispatchErrorHandlerArgs) => Promise<void>;
processEventErrorHandler?: (args: httpFunc.ReceiverProcessEventErrorHandlerArgs) => Promise<boolean>;
// NOTE: for the compatibility with HTTPResponseAck, this handler is not async
// If we receive requests to provide async version of this handler,
// we can add a different name function for it.
unhandledRequestHandler?: (args: ReceiverUnhandledRequestHandlerArgs) => void;
unhandledRequestHandler?: (args: httpFunc.ReceiverUnhandledRequestHandlerArgs) => void;
unhandledRequestTimeoutMillis?: number;
}

Expand Down Expand Up @@ -171,11 +164,11 @@ export default class ExpressReceiver implements Receiver {

private customPropertiesExtractor: (request: Request) => StringIndexed;

private dispatchErrorHandler: (args: ReceiverDispatchErrorHandlerArgs) => Promise<void>;
private dispatchErrorHandler: (args: httpFunc.ReceiverDispatchErrorHandlerArgs) => Promise<void>;

private processEventErrorHandler: (args: ReceiverProcessEventErrorHandlerArgs) => Promise<boolean>;
private processEventErrorHandler: (args: httpFunc.ReceiverProcessEventErrorHandlerArgs) => Promise<boolean>;

private unhandledRequestHandler: (args: ReceiverUnhandledRequestHandlerArgs) => void;
private unhandledRequestHandler: (args: httpFunc.ReceiverUnhandledRequestHandlerArgs) => void;

private unhandledRequestTimeoutMillis: number;

Expand Down
2 changes: 1 addition & 1 deletion src/receivers/HTTPModuleFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export const defaultUnhandledRequestHandler = (args: ReceiverUnhandledRequestHan
const { logger, response } = args;
logger.error(
'An incoming event was not acknowledged within 3 seconds. ' +
'Ensure that the ack() argument is called in a listener.',
'Ensure that the ack() argument is called in a listener.',
);

// Check if the response has already been sent
Expand Down
2 changes: 1 addition & 1 deletion test/types/action.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expectAssignable, expectError, expectType } from 'tsd';
import type { SlackAction, BlockElementAction, DialogSubmitAction, InteractiveAction } from '../../';
import type { BlockElementAction, DialogSubmitAction, InteractiveAction, SlackAction } from '../../';
import App from '../../src/App';

const app = new App({ token: 'TOKEN', signingSecret: 'Signing Secret' });
Expand Down
2 changes: 1 addition & 1 deletion test/types/event.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { expectType } from 'tsd';
import type {
AppMentionEvent,
PinAddedEvent,
Expand All @@ -9,6 +8,7 @@ import type {
UserProfileChangedEvent,
UserStatusChangedEvent,
} from '@slack/types';
import { expectType } from 'tsd';
import type { SayFn } from '../../';
import App from '../../src/App';

Expand Down
2 changes: 1 addition & 1 deletion test/types/message.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { expectAssignable, expectError, expectNotType, expectType } from 'tsd';
import type {
AllMessageEvents,
BotMessageEvent,
Expand All @@ -11,6 +10,7 @@ import type {
MessageRepliedEvent,
ThreadBroadcastMessageEvent,
} from '@slack/types';
import { expectAssignable, expectError, expectNotType, expectType } from 'tsd';
import App from '../../src/App';

const app = new App({ token: 'TOKEN', signingSecret: 'Signing Secret' });
Expand Down
4 changes: 2 additions & 2 deletions test/types/options.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import type { Option } from '@slack/types';
import { expectAssignable, expectType } from 'tsd';
import App from '../../src/App';
import type {
AckFn,
BlockOptions,
BlockSuggestion,
DialogOptions,
DialogOptionGroups,
DialogOptions,
DialogSuggestion,
InteractiveMessageSuggestion,
MessageOptions,
OptionGroups,
} from '../..';
import App from '../../src/App';

const app = new App({ token: 'TOKEN', signingSecret: 'Signing Secret' });

Expand Down
2 changes: 1 addition & 1 deletion test/types/use.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import App from '../../src/App';
import { expectAssignable } from 'tsd';
import App from '../../src/App';
import { onlyCommands, onlyViewActions } from '../../src/middleware/builtin';

const app = new App({ token: 'TOKEN', signingSecret: 'Signing Secret' });
Expand Down
4 changes: 2 additions & 2 deletions test/types/view.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ expectError(
type: 'view_submission',
unknown_key: 'should be detected',
},
async () => { },
async () => {},
),
);
expectError(
Expand All @@ -22,7 +22,7 @@ expectError(
type: undefined,
unknown_key: 'should be detected',
},
async () => { },
async () => {},
),
);
// view_submission
Expand Down
6 changes: 2 additions & 4 deletions test/unit/.mocharc.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
{
"require": [
"ts-node/register",
"source-map-support/register"
],
"require": ["ts-node/register", "source-map-support/register"],
"spec": [
"test/unit/App/*.spec.ts",
"test/unit/receivers/ExpressReceiver.spec.ts",
"test/unit/receivers/HTTPModuleFunctions.spec.ts",
"test/unit/receivers/HTTPReceiver.spec.ts",
"test/unit/receivers/HTTPResponseAck.spec.ts",
Expand Down
6 changes: 3 additions & 3 deletions test/unit/App/basic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ErrorCode } from '../../../src/errors';
import SocketModeReceiver from '../../../src/receivers/SocketModeReceiver';
import {
FakeReceiver,
createFakeConversationStore,
createFakeLogger,
importApp,
mergeOverrides,
Expand All @@ -15,7 +16,6 @@ import {
withNoopAppMetadata,
withNoopWebClient,
withSuccessfulBotUserFetchingWebClient,
createFakeConversationStore,
} from '../helpers';

const fakeAppToken = 'xapp-1234';
Expand Down Expand Up @@ -46,11 +46,11 @@ describe('App basic features', () => {

describe('with a custom port value in Socket Mode', () => {
const installationStore = {
storeInstallation: async () => { },
storeInstallation: async () => {},
fetchInstallation: async () => {
throw new Error('Failed fetching installation');
},
deleteInstallation: async () => { },
deleteInstallation: async () => {},
};
it('should accept a port value at the top-level', async () => {
const MockApp = await importApp(overrides);
Expand Down
24 changes: 12 additions & 12 deletions test/unit/App/middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import type { WebClient } from '@slack/web-api';
import { assert } from 'chai';
import sinon, { type SinonSpy } from 'sinon';
import type { WebClient } from '@slack/web-api';
import type App from '../../../src/App';
import { type ExtendedErrorHandlerArgs, LogLevel } from '../../../src/App';
import { AuthorizationError, type CodedError, ErrorCode, UnknownError, isCodedError } from '../../../src/errors';
import type { NextFn, ReceiverEvent, SayFn } from '../../../src/types';
import {
FakeReceiver,
type Override,
Expand All @@ -27,7 +28,6 @@ import {
withPostMessage,
withSuccessfulBotUserFetchingWebClient,
} from '../helpers';
import type { NextFn, ReceiverEvent, SayFn } from '../../../src/types';

describe('App middleware processing', () => {
let fakeReceiver: FakeReceiver;
Expand Down Expand Up @@ -188,16 +188,16 @@ describe('App middleware processing', () => {
*/
const assertOrderMiddleware =
(orderDown: number, orderUp: number) =>
async ({ next }: { next?: NextFn }) => {
await delay(10);
middlewareCount += 1;
assert.equal(middlewareCount, orderDown);
if (next !== undefined) {
await next();
}
middlewareCount += 1;
assert.equal(middlewareCount, orderUp);
};
async ({ next }: { next?: NextFn }) => {
await delay(10);
middlewareCount += 1;
assert.equal(middlewareCount, orderDown);
if (next !== undefined) {
await next();
}
middlewareCount += 1;
assert.equal(middlewareCount, orderUp);
};

app.use(assertOrderMiddleware(1, 8));
app.message(message, assertOrderMiddleware(3, 6), assertOrderMiddleware(4, 5));
Expand Down
4 changes: 2 additions & 2 deletions test/unit/App/routing-action.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import sinon, { type SinonSpy } from 'sinon';
import type App from '../../../src/App';
import {
FakeReceiver,
type Override,
createFakeLogger,
createDummyBlockActionEventMiddlewareArgs,
createFakeLogger,
importApp,
mergeOverrides,
noopMiddleware,
Expand All @@ -12,7 +13,6 @@ import {
withNoopAppMetadata,
withNoopWebClient,
} from '../helpers';
import type App from '../../../src/App';

function buildOverrides(secondOverrides: Override[]): Override {
return mergeOverrides(
Expand Down
4 changes: 2 additions & 2 deletions test/unit/App/routing-command.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import sinon, { type SinonSpy } from 'sinon';
import type App from '../../../src/App';
import {
FakeReceiver,
type Override,
createFakeLogger,
createDummyCommandMiddlewareArgs,
createFakeLogger,
importApp,
mergeOverrides,
noopMiddleware,
Expand All @@ -13,7 +14,6 @@ import {
withNoopAppMetadata,
withNoopWebClient,
} from '../helpers';
import type App from '../../../src/App';

function buildOverrides(secondOverrides: Override[]): Override {
return mergeOverrides(
Expand Down
12 changes: 6 additions & 6 deletions test/unit/App/routing-event.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import assert from 'node:assert';
import sinon, { type SinonSpy } from 'sinon';
import type App from '../../../src/App';
import {
FakeReceiver,
type Override,
createFakeLogger,
createDummyAppMentionEventMiddlewareArgs,
createFakeLogger,
importApp,
mergeOverrides,
noopMiddleware,
Expand All @@ -14,7 +15,6 @@ import {
withNoopAppMetadata,
withNoopWebClient,
} from '../helpers';
import type App from '../../../src/App';

function buildOverrides(secondOverrides: Override[]): Override {
return mergeOverrides(
Expand Down Expand Up @@ -62,9 +62,9 @@ describe('App event() routing', () => {
sinon.assert.called(fakeHandler);
});
it('should throw if provided invalid message subtype event names', async () => {
app.event('app_mention', async () => { });
app.event('message', async () => { });
assert.throws(() => app.event('message.channels', async () => { }));
assert.throws(() => app.event(/message\..+/, async () => { }));
app.event('app_mention', async () => {});
app.event('message', async () => {});
assert.throws(() => app.event('message.channels', async () => {}));
assert.throws(() => app.event(/message\..+/, async () => {}));
});
});
4 changes: 2 additions & 2 deletions test/unit/App/routing-message.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import sinon, { type SinonSpy } from 'sinon';
import type App from '../../../src/App';
import {
FakeReceiver,
type Override,
createFakeLogger,
createDummyMessageEventMiddlewareArgs,
createFakeLogger,
importApp,
mergeOverrides,
noopMiddleware,
Expand All @@ -13,7 +14,6 @@ import {
withNoopAppMetadata,
withNoopWebClient,
} from '../helpers';
import type App from '../../../src/App';

function buildOverrides(secondOverrides: Override[]): Override {
return mergeOverrides(
Expand Down
4 changes: 2 additions & 2 deletions test/unit/App/routing-options.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import sinon, { type SinonSpy } from 'sinon';
import type App from '../../../src/App';
import {
FakeReceiver,
type Override,
createFakeLogger,
createDummyBlockSuggestionsMiddlewareArgs,
createFakeLogger,
importApp,
mergeOverrides,
noopMiddleware,
Expand All @@ -12,7 +13,6 @@ import {
withNoopAppMetadata,
withNoopWebClient,
} from '../helpers';
import type App from '../../../src/App';

function buildOverrides(secondOverrides: Override[]): Override {
return mergeOverrides(
Expand Down
Loading

0 comments on commit 5785beb

Please sign in to comment.