diff --git a/README.md b/README.md index 9ba11f9..b0a9d01 100644 --- a/README.md +++ b/README.md @@ -35,15 +35,21 @@ Adventure quest game by [@Teoreez](https://github.com/Teoreez) #### Getting Started -```javascript -const { Alice, Reply, Markup } = require('yandex-dialogs-sdk') +```js +const { Alice, render } = require('yandex-dialogs-sdk') + const alice = new Alice(); +const { reply, pause, buttons } = render -const M = Markup; -alice.command('', async ctx => Reply.text('Look, what i can!')); -alice.command('Give a piece of advice', async ctx => - Reply.text('Make const not var'), -); +alice.command('', async ctx => { + return reply` + ${['Здравствуйте', 'Добрый день']}! ${pause(500)} Как дел+а? + ${buttons(['Отлично', 'Супер'])} + ` +}); +alice.command('Give a piece of advice', async ctx => { + return reply`Make const not var` +}); alice.command( ['What is trending now?', 'Watch films', 'Whats in the theatre?'], ctx => { @@ -53,15 +59,21 @@ alice.command( }; }, ); -alice.command(/(https?:\/\/[^\s]+)/g, ctx => Reply.text('Matched a link!')); -alice.any(async ctx => Reply.text(`I don't understand`)); +alice.command(/(https?:\/\/[^\s]+)/g, ctx => reply`Matched a link!`)); +alice.any(async ctx => { + return reply`I don't understand` +}); const server = alice.listen(3001, '/'); ``` -#### Hot middlewares from maintainer +```js +const { render } = require('yandex-dialogs-sdk') +const { reply, pause, buttons } = render +``` +This library uses [https://github.com/vitalets/alice-renderer](https://github.com/vitalets/alice-renderer) for rendering. + +Full documentation is [here](https://github.com/vitalets/alice-renderer) -- **[yandex-dialogs-sdk-lowdb](https://github.com/fletcherist/yandex-dialogs-sdk-lowdb)** - store your users sessions in file -- **[yandex-dialogs-sdk-chatbase](https://github.com/popstas/yandex-dialogs-sdk-chatbase)** - send events to Google Chatbase by **[@popstas](https://github.com/popstas)** #### Handle non-trivial scenarios @@ -72,11 +84,11 @@ const alice = new Alice(); const SCENE_AT_BAR = 'SCENE_AT_BAR'; const atBar = new Scene(SCENE_AT_BAR); -atBar.command('show menu', ctx => - Reply.text('only vodka here', { +atBar.command('show menu', ctx => { + return Reply.text('only vodka here', { buttons: ['buy vodka', 'go away'], - }), -); + }), +}); atBar.command('buy vodka', ctx => Reply.text(`you're dead`)); atBar.command('go away', ctx => { ctx.leave(); @@ -194,45 +206,11 @@ const createMessagesCounterMiddleware = () => { alice.use(createMessagesCounterMiddleware()) ``` -###### Reply -```javascript -const { Reply } = require('yandex-dialogs-sdk') -IMAGE_ID = '213044/d13b0d86a41daf9de232' -EXTRA_PARAMS = { // Extra params are optional - tts: 'Hi the+re', - buttons: ['one', Markup.button('two')], - end_session: true -} -``` -- `Reply.text` -```javascript -// Second argument is optional -alice.any(ctx => Reply.text('text'), EXTRA_PARAMS) -``` -- `Reply.bigImageCard` - One big image -```javascript -Reply.bigImageCard('text', { - image_id: IMAGE_ID, - title: string, // optional - description: string, // optional - button: M.button('click'), // optional -}, EXTRA_PARAMS) -``` -- `Reply.itemsListCard` - Gallery -```javascript -Reply.itemsListCard('text', [IMAGE_ID, IMAGE_ID], EXTRA_PARAMS); -Reply.itemsListCard('test', { - header: 'header', - footer: { - text: 'test', - button: Markup.button('button'), - }, - items: [ - IMAGE_ID, - { image_id: IMAGE_ID, title: 'title', description: 'description' }, - ], - }); -``` +#### Hot middlewares + +- **[yandex-dialogs-sdk-lowdb](https://github.com/fletcherist/yandex-dialogs-sdk-lowdb)** - store your users sessions in file +- **[yandex-dialogs-sdk-chatbase](https://github.com/popstas/yandex-dialogs-sdk-chatbase)** - send events to Google Chatbase by **[@popstas](https://github.com/popstas)** + ###### Events ```javascript @@ -244,21 +222,6 @@ alice.on('response', ctx => { ``` -###### Markup -```javascript -const { Markup } = require('yandex-dialogs-sdk') -``` -- `Markup.button` -```javascript -const M = Markup -M.button('string') -M.button({ - title: string; - url: string; - payload: object; - hide: boolean; -}) -``` ## CONTRIBUTING `git clone` diff --git a/package.json b/package.json index 217eb1f..84eef7f 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,8 @@ "@types/node-fetch": "^2.1.2", "fast-levenshtein": "^2.0.6", "node-fetch": "^2.1.2", - "debug": "^4.1.0" + "debug": "^4.1.0", + "alice-renderer": "1.0.0" }, "devDependencies": { "@types/debug": "0.0.31", @@ -72,9 +73,8 @@ "npm-run-all": "^4.1.3", "shx": "^0.3.2", "sinon": "^7.1.0", - "ts-jest": "^23.0.0", - "tslint": "^5.10.0", - "typescript": "^3.0.1", + "ts-jest": "25.4.0", + "typescript": "3.8.3", "vrsource-tslint-rules": "^5.8.2" } } diff --git a/src/alice-renderer.d.ts b/src/alice-renderer.d.ts new file mode 100644 index 0000000..ea6a70c --- /dev/null +++ b/src/alice-renderer.d.ts @@ -0,0 +1,78 @@ +declare module 'alice-renderer' { + export interface Button { + title: string; + url?: string; + payload?: string; + hide?: boolean; + } + + export interface Response { + text: string; + tts?: string; + card?: { + type: 'BigImage'; + image_id?: string; + title?: string; + descriptions?: string; + }; + buttons?: Button[]; + end_session: boolean; + } + + export function reply(stringParts: string[]): Response; + export function buttons( + items: Array, + defaults?: Button, + ): Button[]; + export function audio(name: string): void; + export function effect(name: string): void; + export function pause(ms?: number): void; + export function br(count?: number): void; + export function text(value: string | string[]): void; + export function tts(value: string | string[]): void; + export function textTts( + textValue: string | string[], + ttsValue: string | string[], + ): void; + export function plural( + number: number, + one: string, + two: string, + five: string, + ): void; + export function enumerate(list: any[]): void; + + export function userify(userId: string, target: typeof reply): typeof reply; + export function userify( + userId: string, + target: { [key: string]: typeof reply }, + ): { [key: string]: typeof reply }; + + export function select(array: string[]): string; + + export function once( + options: { + calls?: number; + seconds?: number; + leading: boolean; + }, + response: any, + ): void; + + export function configure(options: { disableRandom?: boolean }): void; + + export function image( + imageId: string, + options?: { + title?: string; + description?: string; + appendDescription?: string; + button?: Button; + }, + ): { + type: 'BigImage'; + image_id: string; + title?: string; + description?: string; + }; +} diff --git a/src/alice.ts b/src/alice.ts index 81445a0..48fed92 100644 --- a/src/alice.ts +++ b/src/alice.ts @@ -1,41 +1,28 @@ import { EventEmitter } from 'events'; -import { IImagesApiConfig, IImagesApi, ImagesApi } from './imagesApi'; -import { WebhookServer, IWebhookServer } from './server/webhookServer'; +import { ImagesApiConfig, ImagesApi } from './imagesApi'; +import { WebhookServer } from './server/webhookServer'; import { Middleware } from './middleware/middleware'; -import { IApiRequest } from './api/request'; -import { IContext } from './context'; -import { IApiResponse } from './api/response'; +import { ApiRequest } from './api/request'; +import { Context } from './context'; +import { ApiResponse } from './api/response'; import { ALICE_PROTOCOL_VERSION } from './constants'; import { CommandCallback, CommandDeclaration } from './command/command'; -import { InMemorySessionStorage } from './session/inMemorySessionStorage'; -import { sessionMiddleware } from './session/sessionMiddleware'; import debug from './debug'; import { MainStage } from './stage/mainScene'; -import { ISessionStorage } from './session/session'; -import { IScene } from './stage/scene'; +import { Scene } from './stage/scene'; -export interface IAliceConfig extends IImagesApiConfig { - sessionStorage?: ISessionStorage; -} - -export interface IAlice { - readonly imagesApi: IImagesApi; - handleRequest(data: IApiRequest): Promise; - use(middleware: Middleware): void; - listen(port: number, webhookUrl: string, options: object): IWebhookServer; -} +export type AliceConfig = ImagesApiConfig -export class Alice implements IAlice { - private readonly _config: IAliceConfig; +export class Alice { + private readonly _config: AliceConfig; private readonly _middlewares: Middleware[]; - private readonly _imagesApi: IImagesApi; + private readonly _imagesApi: ImagesApi; private readonly _mainStage: MainStage; - private readonly _sessionStorage: ISessionStorage; private _eventEmitter: EventEmitter; - constructor(config: IAliceConfig = {}) { + constructor(config: AliceConfig = {}) { this._eventEmitter = new EventEmitter(); this._config = config; this.handleRequest = this.handleRequest.bind(this); @@ -43,13 +30,9 @@ export class Alice implements IAlice { this._middlewares = []; this._imagesApi = new ImagesApi(this._config); this._mainStage = new MainStage(); - - this._sessionStorage = - config.sessionStorage || new InMemorySessionStorage(); - this.use(sessionMiddleware(this._sessionStorage)); } - private _buildContext(request: IApiRequest): IContext { + private _buildContext(request: ApiRequest): Context { return { data: request, message: request.request.command, @@ -62,7 +45,7 @@ export class Alice implements IAlice { }; } - private async _runMiddlewares(context: IContext): Promise { + private async _runMiddlewares(context: Context): Promise { const middlewares = Array.from(this._middlewares); // mainStage middleware should always be the latest one middlewares.push(this._mainStage.middleware); @@ -71,7 +54,7 @@ export class Alice implements IAlice { } let index = 0; - const next = async (middlewareContext: IContext): Promise => { + const next = async (middlewareContext: Context): Promise => { const middleware = middlewares[index]; index++; return middleware( @@ -82,11 +65,11 @@ export class Alice implements IAlice { return next(context); } - get imagesApi(): IImagesApi { + get imagesApi(): ImagesApi { return this._imagesApi; } - public async handleRequest(data: IApiRequest): Promise { + public async handleRequest(data: ApiRequest): Promise { if (data.version !== ALICE_PROTOCOL_VERSION) { throw new Error('Unknown protocol version'); } @@ -140,23 +123,23 @@ export class Alice implements IAlice { } public command( - declaration: CommandDeclaration, - callback: CommandCallback, + declaration: CommandDeclaration, + callback: CommandCallback, ): void { this._mainStage.scene.command(declaration, callback); } - public any(callback: CommandCallback): void { + public any(callback: CommandCallback): void { this._mainStage.scene.any(callback); } - public registerScene(scene: IScene): void { + public registerScene(scene: Scene): void { this._mainStage.stage.addScene(scene); } public on( type: 'response' | 'request', - callback: (context: IContext) => any, + callback: (context: Context) => any, ): void { this._eventEmitter.addListener(type, callback); } diff --git a/src/api/image.ts b/src/api/image.ts index c024efc..cf80cbb 100644 --- a/src/api/image.ts +++ b/src/api/image.ts @@ -1,14 +1,14 @@ -export interface IApiImageItem { +export interface ApiImageItem { id: string; origUrl?: string; } -export interface IApiImageUploadResponse { - image: IApiImageItem; +export interface ApiImageUploadResponse { + image: ApiImageItem; } export interface IApiImageListResponse { - images: IApiImageItem[]; + images: ApiImageItem[]; } export interface IApiImageQuotaResponse { diff --git a/src/api/nlu.ts b/src/api/nlu.ts index a0d6a5f..6b9e880 100644 --- a/src/api/nlu.ts +++ b/src/api/nlu.ts @@ -1,10 +1,10 @@ -export interface IApiEntityYandexFioValue { +export interface ApiEntityYandexFioValue { first_name?: string; patronymic_name?: string; last_name?: string; } -export interface IApiEntityYandexGeoValue { +export interface ApiEntityYandexGeoValue { country?: string; city?: string; street?: string; @@ -12,7 +12,7 @@ export interface IApiEntityYandexGeoValue { airport?: string; } -export interface IApiEntityYandexDateTimeValue { +export interface ApiEntityYandexDateTimeValue { year?: number; month?: number; day?: number; @@ -24,45 +24,45 @@ export interface IApiEntityYandexDateTimeValue { minute_is_relative?: boolean; } -export type IApiEntityYandexNumberValue = number; +export type ApiEntityYandexNumberValue = number; -export type IApiEntityType = +export type ApiEntityType = | 'YANDEX.FIO' | 'YANDEX.GEO' | 'YANDEX.DATETIME' | 'YANDEX.NUMBER'; -export interface IApiEntityBase { - type: IApiEntityType; +export interface ApiEntityBase { + type: ApiEntityType; } -export interface IApiEntityYandexFio extends IApiEntityBase { +export interface ApiEntityYandexFio extends ApiEntityBase { type: 'YANDEX.FIO'; - value: IApiEntityYandexFioValue; + value: ApiEntityYandexFioValue; } -export interface IApiEntityYandexGeo extends IApiEntityBase { +export interface ApiEntityYandexGeo extends ApiEntityBase { type: 'YANDEX.GEO'; - value: IApiEntityYandexGeoValue; + value: ApiEntityYandexGeoValue; } -export interface IApiEntityYandexDateTime extends IApiEntityBase { +export interface IApiEntityYandexDateTime extends ApiEntityBase { type: 'YANDEX.DATETIME'; - value: IApiEntityYandexDateTimeValue; + value: ApiEntityYandexDateTimeValue; } -export interface IApiEntityYandexNumber extends IApiEntityBase { +export interface IApiEntityYandexNumber extends ApiEntityBase { type: 'YANDEX.NUMBER'; - value: IApiEntityYandexNumberValue; + value: ApiEntityYandexNumberValue; } -export type IApiEntity = - | IApiEntityYandexFio - | IApiEntityYandexGeo +export type ApiEntity = + | ApiEntityYandexFio + | ApiEntityYandexGeo | IApiEntityYandexDateTime | IApiEntityYandexNumber; -export interface IApiRequestNlu { - entities: IApiEntity[]; +export interface ApiRequestNlu { + entities: ApiEntity[]; tokens: string[]; } diff --git a/src/api/request.ts b/src/api/request.ts index 3f7ab3d..a2ae042 100644 --- a/src/api/request.ts +++ b/src/api/request.ts @@ -1,12 +1,12 @@ -import { IApiRequestNlu } from './nlu'; +import { ApiRequestNlu } from './nlu'; -export interface IApiRequestMeta { +export interface ApiRequestMeta { locale: string; timezone: string; client_id: string; } -export interface IApiRequestBody { +export interface ApiRequestBody { command: string; original_utterance: string; type: 'SimpleUtterance' | 'ButtonPressed'; @@ -14,10 +14,10 @@ export interface IApiRequestBody { dangerous_context?: true; }; payload?: object; - nlu?: IApiRequestNlu; + nlu?: ApiRequestNlu; } -export interface IApiRequesSession { +export interface ApiRequestSession { new: boolean; message_id: number; session_id: string; @@ -25,9 +25,9 @@ export interface IApiRequesSession { user_id: string; } -export interface IApiRequest { - meta: IApiRequestMeta; - request: IApiRequestBody; - session: IApiRequesSession; +export interface ApiRequest { + meta: ApiRequestMeta; + request: ApiRequestBody; + session: ApiRequestSession; version: string; } diff --git a/src/api/response.ts b/src/api/response.ts index a892dcd..35c5aa8 100644 --- a/src/api/response.ts +++ b/src/api/response.ts @@ -1,63 +1,63 @@ -export interface IApiResponseCardButton { +export interface ApiResponseCardButton { text: string; url?: string; payload?: object; } -export interface IApiResponseCardFooter { +export interface ApiResponseCardFooter { text: string; - button?: IApiResponseCardButton; + button?: ApiResponseCardButton; } export type ApiResponseCardType = 'BigImage' | 'ItemsList'; -export interface IApiResponseCardBase { +export interface ApiResponseCardBase { type: ApiResponseCardType; } -export interface IApiResponseBigImageCard extends IApiResponseCardBase { +export interface ApiResponseBigImageCard extends ApiResponseCardBase { type: 'BigImage'; image_id: string; title?: string; description?: string; - button?: IApiResponseCardButton; - footer?: IApiResponseCardFooter; + button?: ApiResponseCardButton; + footer?: ApiResponseCardFooter; } -export interface IApiResponseItemsListCardHeader { +export interface ApiResponseItemsListCardHeader { text: string; } -export interface IApiResponseItemsListCardImage { +export interface ApiResponseItemsListCardImage { image_id: string; title?: string; description?: string; - button?: IApiResponseCardButton; + button?: ApiResponseCardButton; } -export interface IApiResponseItemsListCard extends IApiResponseCardBase { +export interface ApiResponseItemsListCard extends ApiResponseCardBase { type: 'ItemsList'; - header?: IApiResponseItemsListCardHeader; - items: IApiResponseItemsListCardImage[]; - footer?: IApiResponseCardFooter; + header?: ApiResponseItemsListCardHeader; + items: ApiResponseItemsListCardImage[]; + footer?: ApiResponseCardFooter; } export type IApiResponseCard = - | IApiResponseBigImageCard - | IApiResponseItemsListCard; + | ApiResponseBigImageCard + | ApiResponseItemsListCard; -export interface IApiResponseBodyButton { +export interface ApiResponseBodyButton { title: string; url?: string; payload?: object; hide?: boolean; } -export interface IApiResponseBody { +export interface ApiResponseBody { text: string; tts?: string; card?: IApiResponseCard; - buttons?: IApiResponseBodyButton[]; + buttons?: ApiResponseBodyButton[]; end_session: boolean; } @@ -67,8 +67,8 @@ export interface IApiResponseSession { user_id: string; } -export interface IApiResponse { - response: IApiResponseBody; +export interface ApiResponse { + response: ApiResponseBody; session?: IApiResponseSession; version: string; } diff --git a/src/command/command.ts b/src/command/command.ts index fef84ab..6cc0373 100644 --- a/src/command/command.ts +++ b/src/command/command.ts @@ -1,54 +1,44 @@ -import { IContext } from '../context'; -import { IApiResponseBody } from '../api/response'; +import { Context } from '../context'; +import { ApiResponseBody } from '../api/response'; import { ITextRelevanceProvider, getLevenshteinRelevance, } from '../utils/textRelevance'; -export type CommandCallbackResult = IApiResponseBody; -export type CommandCallback = - | ((context: TContext) => CommandCallbackResult) - | ((context: TContext) => Promise); -export type CommandMatcher = - | ((ctx: TContext) => boolean | number) - | ((ctx: TContext) => Promise); -export type CommandDeclaration = - | CommandMatcher - | string[] - | string - | RegExp; - -export interface ICommand { - run(context: TContext): Promise; - getRelevance(context: TContext): Promise; -} +export type CommandCallbackResult = ApiResponseBody; +export type CommandCallback = + | ((context: Context) => CommandCallbackResult) + | ((context: Context) => Promise); +export type CommandMatcher = + | ((ctx: Context) => boolean | number) + | ((ctx: Context) => Promise); +export type CommandDeclaration = CommandMatcher | string[] | string | RegExp; -interface ICreateMatcherFromStringParams { +interface CreateMatcherFromStringParams { relevanceProvider?: ITextRelevanceProvider; } -export class Command - implements ICommand { - private readonly _callback: CommandCallback; +export class Command { + private readonly _callback: CommandCallback; private readonly _matcher: CommandMatcher; - constructor(matcher: CommandMatcher, callback: CommandCallback) { + constructor(matcher: CommandMatcher, callback: CommandCallback) { this._matcher = matcher; this._callback = callback; } - public async getRelevance(context: IContext): Promise { + public async getRelevance(context: Context): Promise { return this._matcher.call(null, context); } - public async run(context: TContext): Promise { + public async run(context: Context): Promise { return this._callback.call(null, context); } - public static createCommand( + public static createCommand( declaration: CommandDeclaration, - callback: CommandCallback, - ): ICommand { + callback: CommandCallback, + ): Command { if (typeof declaration === 'function') { return new Command(declaration, callback); } @@ -73,19 +63,18 @@ export class Command public static createMatcherFromString( pattern: string, - params: ICreateMatcherFromStringParams = {}, + params: CreateMatcherFromStringParams = {}, ): CommandMatcher { if (typeof pattern === undefined) { return () => 0; } pattern = pattern ? pattern.toLowerCase() : ''; - const { - relevanceProvider = getLevenshteinRelevance, - } = params; - return (context: IContext) => { - const commandLower = context.data.request.command ? - context.data.request.command.toLowerCase() : ''; + const { relevanceProvider = getLevenshteinRelevance } = params; + return (context: Context) => { + const commandLower = context.data.request.command + ? context.data.request.command.toLowerCase() + : ''; if (commandLower === pattern) { return 1; } @@ -95,29 +84,30 @@ export class Command public static createMatcherFromStrings( patterns: string[], - params: ICreateMatcherFromStringParams = {}, + params: CreateMatcherFromStringParams = {}, ): CommandMatcher { if (!patterns || !patterns.length) { return () => 0; } patterns = patterns.map(s => s.toLowerCase()); - const { - relevanceProvider = getLevenshteinRelevance, - } = params; - return (context: IContext) => { - const commandLower = context.data.request.command ? - context.data.request.command.toLowerCase() : ''; + const { relevanceProvider = getLevenshteinRelevance } = params; + return (context: Context) => { + const commandLower = context.data.request.command + ? context.data.request.command.toLowerCase() + : ''; return patterns.reduce( (r, pattern) => Math.max(r, relevanceProvider(pattern, commandLower)), - 0); + 0, + ); }; } public static createMatcherFromRegExp(regexp: RegExp): CommandMatcher { - return (context: IContext) => { - const commandLower = context.data.request.command ? - context.data.request.command.toLowerCase() : ''; + return (context: Context) => { + const commandLower = context.data.request.command + ? context.data.request.command.toLowerCase() + : ''; return regexp.test(commandLower) ? 1 : 0; }; } diff --git a/src/command/commandsGroup.ts b/src/command/commandsGroup.ts index a38a643..4e32106 100644 --- a/src/command/commandsGroup.ts +++ b/src/command/commandsGroup.ts @@ -1,31 +1,21 @@ -import { ICommand } from './command'; +import { Command } from './command'; +import { Context } from '../context'; -import { IContext } from '../context'; - -export interface ICommandRelevance { - readonly command: ICommand; +export interface CommandRelevance { + readonly command: Command; readonly relevance: number; } -export interface ICommandsGroup { - add(command: ICommand): void; - getRelevance( - context: TContext, - ): Promise> | null>; - getMostRelevant(context: TContext): Promise | null>; -} - -export class CommandsGroup - implements ICommandsGroup { - private readonly _commands: Array>; +export class CommandsGroup { + private readonly _commands: Command[]; constructor() { this._commands = []; } public async getRelevance( - context: TContext, - ): Promise { + context: Context, + ): Promise { return Promise.all( this._commands.map(async command => { return { command, relevance: await command.getRelevance(context) }; @@ -33,22 +23,20 @@ export class CommandsGroup ); } - public async getMostRelevant( - context: TContext, - ): Promise | null> { + public async getMostRelevant(context: Context): Promise { const relevances = await this.getRelevance(context); if (!relevances || !relevances.length) { return null; } - const mostRelevant = relevances.reduce>( + const mostRelevant = relevances.reduce( (last, current) => (current.relevance > last.relevance ? current : last), relevances[0], ); return mostRelevant.relevance > 0 ? mostRelevant.command : null; } - public add(command: ICommand): void { + public add(command: Command): void { this._commands.push(command); } } diff --git a/src/context.ts b/src/context.ts index 9bb0859..dfd90b2 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,17 +1,17 @@ -import { IApiRequest } from './api/request'; -import { IApiRequestNlu } from './api/nlu'; -import { IApiResponseBody } from './api/response'; +import { ApiRequest } from './api/request'; +import { ApiRequestNlu } from './api/nlu'; +import { ApiResponseBody } from './api/response'; -export interface IContext { - readonly data: IApiRequest; +export interface Context { + readonly data: ApiRequest; readonly message: string; readonly originalUtterance: string; readonly sessionId: string; readonly messageId: number; readonly userId: string; readonly payload?: object; - readonly nlu?: IApiRequestNlu; + readonly nlu?: ApiRequestNlu; // param response appears in context when all // middlewares have been done and we got some response - response?: IApiResponseBody; + response?: ApiResponseBody; } diff --git a/src/imagesApi.ts b/src/imagesApi.ts index 868529e..fb653d9 100644 --- a/src/imagesApi.ts +++ b/src/imagesApi.ts @@ -1,45 +1,37 @@ import fetch from 'node-fetch'; import { ALICE_API_URL } from './constants'; import { - IApiImageUploadResponse, - IApiImageItem, + ApiImageUploadResponse, + ApiImageItem, IApiImageListResponse, IApiImageQuota, IApiImageQuotaResponse, IApiImageDeleteResponse, } from './api/image'; -export interface IImagesApiConfig { +export interface ImagesApiConfig { oAuthToken?: string; skillId?: string; } -interface IImagesApiRequestParams { +interface ImagesApiRequestParams { path?: string; url?: string; method?: 'GET' | 'POST' | 'DELETE'; body?: object; } -export interface IImagesApi { - uploadImageByUrl(url: string): Promise; - uploadImageFile(): Promise; - getImages(): Promise; - getImagesQuota(): Promise; - deleteImage(imageId: string): Promise; -} - -export class ImagesApi implements IImagesApi { +export class ImagesApi { private readonly _skillId: string | undefined; private readonly _oAuthToken: string | undefined; - constructor(params: IImagesApiConfig) { + constructor(params: ImagesApiConfig) { this._skillId = params.skillId; this._oAuthToken = params.oAuthToken; } - public async uploadImageByUrl(url: string): Promise { - const response = await this._makeRequest({ + public async uploadImageByUrl(url: string): Promise { + const response = await this._makeRequest({ path: 'images', method: 'POST', body: { url }, @@ -47,11 +39,11 @@ export class ImagesApi implements IImagesApi { return response.image; } - public async uploadImageFile(): Promise { + public async uploadImageFile(): Promise { throw new Error('Not implemented'); } - public async getImages(): Promise { + public async getImages(): Promise { const response = await this._makeRequest({ path: 'images', method: 'GET', @@ -76,7 +68,7 @@ export class ImagesApi implements IImagesApi { } private async _makeRequest( - params: IImagesApiRequestParams, + params: ImagesApiRequestParams, ): Promise { if (!this._oAuthToken) { throw new Error( @@ -90,11 +82,11 @@ export class ImagesApi implements IImagesApi { const response = await fetch(url, { method: method, headers: { - 'Authorization': `OAuth ${this._oAuthToken}`, + Authorization: `OAuth ${this._oAuthToken}`, 'Content-type': 'application/json', }, body: body, }); - return await response.json() as TResult; + return (await response.json()) as TResult; } } diff --git a/src/index.ts b/src/index.ts index b69ed1b..cbb8a0a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,27 +11,20 @@ export { import { Alice } from './alice'; -export { Reply } from './reply/reply'; -export { Markup } from './reply/markup'; +import * as render from 'alice-renderer' +export { render } -export { InMemorySession } from './session/inMemorySession'; -export { InMemorySessionStorage } from './session/inMemorySessionStorage'; -export { ISession, ISessionStorage } from './session/session'; -export { ISessionContext } from './session/sessionContext'; -export { sessionMiddleware } from './session/sessionMiddleware'; +export { Scene } from './stage/scene'; +export { Stage } from './stage/stage'; +export { StageContext } from './stage/stageContext'; -export { IStageCompere } from './stage/compere'; -export { IScene, Scene } from './stage/scene'; -export { IStage, Stage } from './stage/stage'; -export { IStageContext } from './stage/stageContext'; -export { - Middleware, - MiddlewareNext, -} from './middleware/middleware'; +export { Middleware, MiddlewareNext } from './middleware/middleware'; +export { Session, SessionStorage } from './session/session' +export { sessionMiddleware } from './session/sessionMiddleware'; -export { Alice, IAlice } from './alice'; -export { IContext } from './context'; -export { IImagesApi } from './imagesApi'; +export { Alice } from './alice'; +export { Context } from './context'; +export { ImagesApi } from './imagesApi'; export default Alice; diff --git a/src/middleware/middleware.ts b/src/middleware/middleware.ts index 4a6a0b1..148b17f 100644 --- a/src/middleware/middleware.ts +++ b/src/middleware/middleware.ts @@ -1,12 +1,12 @@ -import { IContext } from '../context'; +import { Context } from '../context'; -export type MiddlewareNext = ( +export type MiddlewareNext = ( context: TContext, ) => Promise; export type Middleware< - TContextFrom extends IContext = IContext, - TContextTo extends IContext = TContextFrom + TContextFrom extends Context = Context, + TContextTo extends Context = TContextFrom > = ( context: TContextFrom, next: MiddlewareNext | null, diff --git a/src/reply/bodyButtonBuilder.ts b/src/reply/bodyButtonBuilder.ts index 045e5ab..9f49b87 100644 --- a/src/reply/bodyButtonBuilder.ts +++ b/src/reply/bodyButtonBuilder.ts @@ -1,4 +1,4 @@ -import { IApiResponseBodyButton } from '../api/response'; +import { ApiResponseBodyButton } from '../api/response'; export interface IBodyButtonReply { title: string; @@ -12,7 +12,7 @@ export type BodyButtonDeclaration = IBodyButtonReply | string; export class BodyButtonBuilder { public static createBodyButton( declaration: BodyButtonDeclaration, - ): IApiResponseBodyButton { + ): ApiResponseBodyButton { if (typeof declaration === 'object') { return declaration; } diff --git a/src/reply/cards/bigImageCardBuilder.ts b/src/reply/cards/bigImageCardBuilder.ts index 842391f..21c3b1e 100644 --- a/src/reply/cards/bigImageCardBuilder.ts +++ b/src/reply/cards/bigImageCardBuilder.ts @@ -1,4 +1,4 @@ -import { IApiResponseBigImageCard } from '../../api/response'; +import { ApiResponseBigImageCard } from '../../api/response'; import { CardFooterDeclaration, CardFooterBuilder } from './cardFooterBuilder'; import { CardButtonDeclaration, CardButtonBuilder } from './cardButtonBuilder'; @@ -15,9 +15,9 @@ export type BigImageCardDeclaration = IBigImageCardReply | string; export class BigImageCardBuilder { public static createBigImageCard( declaration: BigImageCardDeclaration, - ): IApiResponseBigImageCard { + ): ApiResponseBigImageCard { if (typeof declaration === 'object') { - const result: IApiResponseBigImageCard = { + const result: ApiResponseBigImageCard = { type: 'BigImage', image_id: declaration.image_id, title: declaration.title, diff --git a/src/reply/cards/cardButtonBuilder.ts b/src/reply/cards/cardButtonBuilder.ts index c162fc9..75a649f 100644 --- a/src/reply/cards/cardButtonBuilder.ts +++ b/src/reply/cards/cardButtonBuilder.ts @@ -1,4 +1,4 @@ -import { IApiResponseCardButton } from '../../api/response'; +import { ApiResponseCardButton } from '../../api/response'; export interface ICardButtonReply { text: string; @@ -11,7 +11,7 @@ export type CardButtonDeclaration = ICardButtonReply | string; export class CardButtonBuilder { public static createCardButton( declaration: CardButtonDeclaration, - ): IApiResponseCardButton { + ): ApiResponseCardButton { if (typeof declaration === 'object') { return declaration; } diff --git a/src/reply/cards/cardFooterBuilder.ts b/src/reply/cards/cardFooterBuilder.ts index d6bc328..30beaa6 100644 --- a/src/reply/cards/cardFooterBuilder.ts +++ b/src/reply/cards/cardFooterBuilder.ts @@ -1,4 +1,4 @@ -import { IApiResponseCardFooter } from '../../api/response'; +import { ApiResponseCardFooter } from '../../api/response'; import { CardButtonDeclaration, CardButtonBuilder } from './cardButtonBuilder'; export interface ICardFooterReply { @@ -11,9 +11,9 @@ export type CardFooterDeclaration = ICardFooterReply | string; export class CardFooterBuilder { public static createCardFooter( declaration: CardFooterDeclaration, - ): IApiResponseCardFooter { + ): ApiResponseCardFooter { if (typeof declaration === 'object') { - const result: IApiResponseCardFooter = { + const result: ApiResponseCardFooter = { text: declaration.text, }; if (declaration.button) { diff --git a/src/reply/cards/itemsListCardBuilder.ts b/src/reply/cards/itemsListCardBuilder.ts index f7509b4..2fb5dbf 100644 --- a/src/reply/cards/itemsListCardBuilder.ts +++ b/src/reply/cards/itemsListCardBuilder.ts @@ -1,4 +1,4 @@ -import { IApiResponseItemsListCard } from '../../api/response'; +import { ApiResponseItemsListCard } from '../../api/response'; import { CardFooterDeclaration, CardFooterBuilder } from './cardFooterBuilder'; import { ItemsListCardHeaderDeclaration, @@ -34,7 +34,7 @@ function isItemsListImageArray( export class ItemsListCardBuilder { public static createItemsListCard( declaration: ItemsListCardDeclaration, - ): IApiResponseItemsListCard { + ): ApiResponseItemsListCard { if (isItemsListImageArray(declaration)) { return { type: 'ItemsList', @@ -45,7 +45,7 @@ export class ItemsListCardBuilder { } if (isItemsListCard(declaration)) { - const result: IApiResponseItemsListCard = { + const result: ApiResponseItemsListCard = { type: 'ItemsList', items: declaration.items.map(item => ItemsListCardImageBuilder.createItemsListCardImage(item), diff --git a/src/reply/cards/itemsListCardHeaderBuilder.ts b/src/reply/cards/itemsListCardHeaderBuilder.ts index d768bda..f55fe52 100644 --- a/src/reply/cards/itemsListCardHeaderBuilder.ts +++ b/src/reply/cards/itemsListCardHeaderBuilder.ts @@ -1,4 +1,4 @@ -import { IApiResponseItemsListCardHeader } from '../../api/response'; +import { ApiResponseItemsListCardHeader } from '../../api/response'; export interface IItemsListCardHeaderReply { text: string; @@ -9,7 +9,7 @@ export type ItemsListCardHeaderDeclaration = IItemsListCardHeaderReply | string; export class ItemsListCardHeaderBuilder { public static createItemsListCardHeader( declaration: ItemsListCardHeaderDeclaration, - ): IApiResponseItemsListCardHeader { + ): ApiResponseItemsListCardHeader { if (typeof declaration === 'object') { return declaration; } diff --git a/src/reply/cards/itemsListCardImageBuilder.ts b/src/reply/cards/itemsListCardImageBuilder.ts index b39fdc9..5c1b74a 100644 --- a/src/reply/cards/itemsListCardImageBuilder.ts +++ b/src/reply/cards/itemsListCardImageBuilder.ts @@ -1,4 +1,4 @@ -import { IApiResponseItemsListCardImage } from '../../api/response'; +import { ApiResponseItemsListCardImage } from '../../api/response'; import { CardButtonDeclaration, CardButtonBuilder } from './cardButtonBuilder'; export interface IItemsListCardImageReply { @@ -13,9 +13,9 @@ export type ItemsListCardImageDeclaration = IItemsListCardImageReply | string; export class ItemsListCardImageBuilder { public static createItemsListCardImage( declaration: ItemsListCardImageDeclaration, - ): IApiResponseItemsListCardImage { + ): ApiResponseItemsListCardImage { if (typeof declaration === 'object') { - const result: IApiResponseItemsListCardImage = { + const result: ApiResponseItemsListCardImage = { image_id: declaration.image_id, title: declaration.title, description: declaration.description, diff --git a/src/reply/extraParamsBuilder.ts b/src/reply/extraParamsBuilder.ts index 9208269..d586e86 100644 --- a/src/reply/extraParamsBuilder.ts +++ b/src/reply/extraParamsBuilder.ts @@ -1,10 +1,10 @@ -import { IApiResponseBodyButton } from '../api/response'; +import { ApiResponseBodyButton } from '../api/response'; import { BodyButtonDeclaration } from './bodyButtonBuilder'; import { BodyButtonBuilder } from './bodyButtonBuilder'; export interface IExtraParams { tts?: string; - buttons?: IApiResponseBodyButton[]; + buttons?: ApiResponseBodyButton[]; end_session: boolean; } diff --git a/src/reply/markup.ts b/src/reply/markup.ts index e5c16bc..1d2f31e 100644 --- a/src/reply/markup.ts +++ b/src/reply/markup.ts @@ -1,10 +1,10 @@ import { BodyButtonBuilder, BodyButtonDeclaration } from './bodyButtonBuilder'; -import { IApiResponseBodyButton } from '../api/response'; +import { ApiResponseBodyButton } from '../api/response'; export class Markup { public static button( declaration: BodyButtonDeclaration, - ): IApiResponseBodyButton { + ): ApiResponseBodyButton { return BodyButtonBuilder.createBodyButton(declaration); } } diff --git a/src/reply/reply.ts b/src/reply/reply.ts index 8ecef0f..1cded72 100644 --- a/src/reply/reply.ts +++ b/src/reply/reply.ts @@ -1,4 +1,4 @@ -import { IApiResponseBody } from '../api/response'; +import { ApiResponseBody } from '../api/response'; import { TextReplyDeclaration, TextReplyBuilder } from './textReplyBuilder'; import { ExtraParamsDeclaration, @@ -17,9 +17,9 @@ export class Reply { public static text( textDeclaration: TextReplyDeclaration, extraParamsDeclaration?: ExtraParamsDeclaration, - ): IApiResponseBody { + ): ApiResponseBody { const textReply = TextReplyBuilder.createTextReply(textDeclaration); - const result: IApiResponseBody = { + const result: ApiResponseBody = { text: textReply.text, tts: textReply.tts, end_session: false, @@ -45,10 +45,10 @@ export class Reply { textDeclaration: TextReplyDeclaration, cardDeclaration: BigImageCardDeclaration, extraParamsDeclaration?: ExtraParamsDeclaration, - ): IApiResponseBody { + ): ApiResponseBody { const textReply = TextReplyBuilder.createTextReply(textDeclaration); const card = BigImageCardBuilder.createBigImageCard(cardDeclaration); - const result: IApiResponseBody = { + const result: ApiResponseBody = { text: textReply.text, tts: textReply.tts, card: card, @@ -72,10 +72,10 @@ export class Reply { textDeclaration: TextReplyDeclaration, cardDeclaration: ItemsListCardDeclaration, extraParamsDeclaration?: ExtraParamsDeclaration, - ): IApiResponseBody { + ): ApiResponseBody { const textReply = TextReplyBuilder.createTextReply(textDeclaration); const card = ItemsListCardBuilder.createItemsListCard(cardDeclaration); - const result: IApiResponseBody = { + const result: ApiResponseBody = { text: textReply.text, tts: textReply.tts, card: card, diff --git a/src/server/webhookServer.ts b/src/server/webhookServer.ts index 70e799b..6acaad9 100644 --- a/src/server/webhookServer.ts +++ b/src/server/webhookServer.ts @@ -1,20 +1,16 @@ import * as http from 'http'; import debug from '../debug'; -import { IApiRequest } from '../api/request'; -import { IApiResponse } from '../api/response'; +import { ApiRequest } from '../api/request'; +import { ApiResponse } from '../api/response'; -type HandleAliceRequestType = (request: IApiRequest) => Promise; +type HandleAliceRequestType = (request: ApiRequest) => Promise; -export interface IWebhookServerConfig { +export interface WebhookServerConfig { port: number; webhookUrl: string; options: object; handleRequest: HandleAliceRequestType; } -export interface IWebhookServer { - start(): void; - stop(): void; -} function isAvailableMethod(method: string | undefined): boolean { if (method === undefined) { @@ -37,7 +33,7 @@ export class WebhookServer { private _isStarted: boolean; private _handleAliceRequest: HandleAliceRequestType; - constructor(config: IWebhookServerConfig) { + constructor(config: WebhookServerConfig) { this._port = config.port; this._webhookUrl = formatWebhookUrl(config.webhookUrl); this._handleAliceRequest = config.handleRequest; @@ -53,8 +49,10 @@ export class WebhookServer { request: http.IncomingMessage, response: http.ServerResponse, ): Promise { - if (!isAvailableMethod(request.method) || - request.url !== this._webhookUrl) { + if ( + !isAvailableMethod(request.method) || + request.url !== this._webhookUrl + ) { response.statusCode = 400; return response.end(); } @@ -66,7 +64,7 @@ export class WebhookServer { private static _readRequest( request: http.IncomingMessage, - ): Promise { + ): Promise { return new Promise((resolve, reject) => { const body: Buffer[] = []; request @@ -86,7 +84,7 @@ export class WebhookServer { } private static async _sendResponse( response: http.ServerResponse, - responseBody: IApiResponse, + responseBody: ApiResponse, ) { response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); diff --git a/src/session/inMemorySession.ts b/src/session/inMemorySession.ts index d8aec6d..e28581a 100644 --- a/src/session/inMemorySession.ts +++ b/src/session/inMemorySession.ts @@ -1,6 +1,6 @@ -import { ISession } from './session'; +import { Session } from './session'; -export class InMemorySession implements ISession { +export class InMemorySession implements Session { public readonly id: string; private readonly _data: Map; diff --git a/src/session/inMemorySessionStorage.ts b/src/session/inMemorySessionStorage.ts index e883c4c..abed4d9 100644 --- a/src/session/inMemorySessionStorage.ts +++ b/src/session/inMemorySessionStorage.ts @@ -1,22 +1,22 @@ -import { ISessionStorage, ISession } from './session'; +import { SessionStorage, Session } from './session'; import { InMemorySession } from './inMemorySession'; -interface IInMemorySessionsStorageItem { +interface InMemorySessionsStorageItem { readonly creationTime: number; - readonly session: ISession; + readonly session: Session; } -export interface IInMemorySessionsStorageParams { +export interface InMemorySessionsStorageParams { ttl?: number; } -export class InMemorySessionStorage implements ISessionStorage { +export class InMemorySessionStorage implements SessionStorage { private readonly _ttl: number; - private readonly _sessions: Map; + private readonly _sessions: Map; - constructor(params?: IInMemorySessionsStorageParams) { + constructor(params?: InMemorySessionsStorageParams) { this._ttl = (params && params.ttl) || Infinity; - this._sessions = new Map(); + this._sessions = new Map(); } private _flushOutdatedSessions(): void { @@ -29,7 +29,7 @@ export class InMemorySessionStorage implements ISessionStorage { } } - public async getOrCreate(id: string): Promise { + public async getOrCreate(id: string): Promise { this._flushOutdatedSessions(); let sessionItem = this._sessions.get(id); diff --git a/src/session/session.ts b/src/session/session.ts index 7ccfe54..aec3ae0 100644 --- a/src/session/session.ts +++ b/src/session/session.ts @@ -1,4 +1,4 @@ -export interface ISession { +export interface Session { readonly id: string; has(key: string): boolean; delete(key: string): void; @@ -6,6 +6,6 @@ export interface ISession { set(key: string, value: TValue): void; } -export interface ISessionStorage { - getOrCreate(id: string): Promise; +export interface SessionStorage { + getOrCreate(id: string): Promise; } diff --git a/src/session/sessionContext.ts b/src/session/sessionContext.ts index 376df88..a86df14 100644 --- a/src/session/sessionContext.ts +++ b/src/session/sessionContext.ts @@ -1,6 +1,6 @@ -import { IContext } from '../context'; -import { ISession } from './session'; +import { Context } from '../context'; +import { Session } from './session'; -export interface ISessionContext extends IContext { - readonly session: ISession; +export interface SessionContext extends Context { + readonly session: Session; } diff --git a/src/session/sessionKeyProvider.ts b/src/session/sessionKeyProvider.ts index 20a43d5..109a855 100644 --- a/src/session/sessionKeyProvider.ts +++ b/src/session/sessionKeyProvider.ts @@ -1,16 +1,16 @@ -import { IContext } from '../context'; +import { Context } from '../context'; -export type ISessionKeyProvider = ( +export type ISessionKeyProvider = ( context: TContext, ) => Promise | string; -export function sessionKeySessionIdProvider( +export function sessionKeySessionIdProvider( context: TContext, ) { return context.data.session.session_id; } -export function sessionKeyUserIdProvider( +export function sessionKeyUserIdProvider( context: TContext, ) { return context.data.session.user_id; diff --git a/src/session/sessionMiddleware.ts b/src/session/sessionMiddleware.ts index bb8c4d2..402d5ec 100644 --- a/src/session/sessionMiddleware.ts +++ b/src/session/sessionMiddleware.ts @@ -1,7 +1,7 @@ import { Middleware } from '../middleware/middleware'; -import { ISessionStorage } from './session'; -import { IContext } from '../context'; -import { ISessionContext } from './sessionContext'; +import { SessionStorage } from './session'; +import { Context } from '../context'; +import { SessionContext } from './sessionContext'; import { ISessionKeyProvider, sessionKeyUserIdProvider, @@ -16,13 +16,13 @@ interface ISessionMiddlewareParams { * to store user sessions */ export function sessionMiddleware( - storage: ISessionStorage, + storage: SessionStorage, { keyProvider = sessionKeyUserIdProvider }: ISessionMiddlewareParams = {}, -): Middleware { - return async (context, next): Promise => { +): Middleware { + return async (context, next): Promise => { const id = await keyProvider(context); const session = await storage.getOrCreate(id); - const sessionContext: ISessionContext = { + const sessionContext: SessionContext = { ...context, session, }; diff --git a/src/stage/compere.ts b/src/stage/compere.ts index cbfeca4..08227a2 100644 --- a/src/stage/compere.ts +++ b/src/stage/compere.ts @@ -1,16 +1,11 @@ -import { ISessionContext } from '../session/sessionContext'; +import { SessionContext } from '../session/sessionContext'; import { CURRENT_SCENE_SESSION_KEY, DEFAULT_SCENE_NAME } from './constants'; import debug from '../debug'; -export interface IStageCompere { - enter(name: string): Promise; - leave(): Promise; -} - -export class StageCompere implements IStageCompere { - private readonly _context: ISessionContext; +export class StageCompere { + private readonly _context: SessionContext; - constructor(context: ISessionContext) { + constructor(context: SessionContext) { this._context = context; } diff --git a/src/stage/mainScene.ts b/src/stage/mainScene.ts index d22a477..397444c 100644 --- a/src/stage/mainScene.ts +++ b/src/stage/mainScene.ts @@ -1,11 +1,11 @@ -import { Stage, IStage } from './stage'; -import { Scene, IScene } from './scene'; +import { Stage } from './stage'; +import { Scene } from './scene'; import { Middleware } from '../middleware/middleware'; import { DEFAULT_SCENE_NAME } from './constants'; export class MainStage { - public scene: IScene; - public stage: IStage; + public scene: Scene; + public stage: Stage; public middleware: Middleware; constructor() { diff --git a/src/stage/scene.ts b/src/stage/scene.ts index f8976f2..7d627ac 100644 --- a/src/stage/scene.ts +++ b/src/stage/scene.ts @@ -4,25 +4,13 @@ import { CommandDeclaration, CommandCallbackResult, } from '../command/command'; -import { ICommandsGroup, CommandsGroup } from '../command/commandsGroup'; +import { CommandsGroup } from '../command/commandsGroup'; +import { Context } from '../context'; -import { IStageContext } from './stageContext'; - -export interface IScene { - readonly name: string; - command( - declaration: CommandDeclaration, - callback: CommandCallback, - ): void; - any(callback: CommandCallback): void; - run(context: TContext): Promise; -} - -export class Scene - implements IScene { +export class Scene { public readonly name: string; - private readonly _commands: ICommandsGroup; - private _anyCommand: Command | null; + private readonly _commands: CommandsGroup; + private _anyCommand: Command | null; constructor(name: string) { this.name = name; @@ -31,17 +19,17 @@ export class Scene } public command( - declaration: CommandDeclaration, - callback: CommandCallback, + declaration: CommandDeclaration, + callback: CommandCallback, ): void { this._commands.add(Command.createCommand(declaration, callback)); } - public any(callback: CommandCallback): void { + public any(callback: CommandCallback): void { this._anyCommand = new Command(Command.createMatcherAlways(), callback); } - public async run(context: TContext): Promise { + public async run(context: Context): Promise { const command = await this._commands.getMostRelevant(context); if (command) { return command.run(context); diff --git a/src/stage/stage.ts b/src/stage/stage.ts index 92bcc03..5fc6a67 100644 --- a/src/stage/stage.ts +++ b/src/stage/stage.ts @@ -1,26 +1,19 @@ -import { IScene, Scene } from './scene'; +import { Scene } from './scene'; import { Middleware } from '../middleware/middleware'; -import { ISessionContext } from '../session/sessionContext'; -import { IStageContext } from './stageContext'; +import { SessionContext } from '../session/sessionContext'; +import { StageContext } from './stageContext'; import { StageCompere } from './compere'; import { CURRENT_SCENE_SESSION_KEY, DEFAULT_SCENE_NAME } from './constants'; import debug from '../debug'; -export interface IStage { - addScene(scene: IScene): void; - removeScene(name: string): void; - - getMiddleware(): Middleware; -} - -export class Stage implements IStage { - private readonly _scenes: Map; +export class Stage implements Stage { + private readonly _scenes: Map; constructor() { - this._scenes = new Map(); + this._scenes = new Map(); } - public addScene(scene: IScene): void { + public addScene(scene: Scene): void { if (!(scene instanceof Scene)) { throw new Error( 'Incorrect argument scene. Please provide Scene instance', @@ -41,8 +34,8 @@ export class Stage implements IStage { debug(`scene removed "${name}"`); } - public getMiddleware(): Middleware { - return async (context, next): Promise => { + public getMiddleware(): Middleware { + return async (context, next): Promise => { if (!context.session) { throw new Error( 'You have to add some session middelware to use scenes', @@ -61,7 +54,7 @@ export class Stage implements IStage { } const compere = new StageCompere(context); - const stageContext: IStageContext = { + const stageContext: StageContext = { ...context, enter: (name: string) => compere.enter(name), leave: () => compere.leave(), diff --git a/src/stage/stageContext.ts b/src/stage/stageContext.ts index 482f236..51a26d9 100644 --- a/src/stage/stageContext.ts +++ b/src/stage/stageContext.ts @@ -1,7 +1,7 @@ -import { IStageCompere } from './compere'; -import { ISessionContext } from '../session/sessionContext'; +import { StageCompere } from './compere'; +import { SessionContext } from '../session/sessionContext'; -export interface IStageContext extends ISessionContext { - readonly enter: IStageCompere['enter']; - readonly leave: IStageCompere['leave']; +export interface StageContext extends SessionContext { + readonly enter: StageCompere['enter']; + readonly leave: StageCompere['leave']; } diff --git a/tslint.json b/tslint.json deleted file mode 100644 index 18c7914..0000000 --- a/tslint.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "defaultSeverity": "error", - "extends": ["tslint:recommended"], - "jsRules": {}, - "rules": { - "arrow-parens": false, - "ext-variable-name": [ - true, - ["class", "pascal"], - ["interface", "pascal", {"regex": "^I.*$"}], - ["parameter", "camel"], - ["property", "static", "camel"], - ["property", "private", "camel", "require-leading-underscore"], - ["property", "protected", "camel", "allow-leading-underscore"], - ["variable", "local", "camel"], - ["variable", "const", "upper"], - ["variable", "camel"], - ["method", "private", "camel", "require-leading-underscore"], - ["method", "protected", "camel", "allow-leading-underscore"], - ["function", "camel"], - ["default", "camel"] - ], - "file-name-casing": [true, "camel-case"], - "indent": [true, "spaces", 2], - "interface-name": [true, "always-prefix"], - "member-ordering": false, - "no-var-requires": false, - "object-literal-shorthand": false, - "object-literal-sort-keys": false, - "only-arrow-functions": false, - "ordered-imports": false, - "quotemark": [true, "single"], - "semicolon": [true, "always"], - "trailing-comma": [true, {"multiline": "always", "singleline": "never"}], - "variable-name": [ - true, - "ban-keywords", - "check-format", - "allow-leading-underscore" - ] - }, - "rulesDirectory": ["node_modules/vrsource-tslint-rules/rules"] -}