repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
kevinelliott/acars-backend
src/leaderboard/leaderboard.service.ts
<filename>src/leaderboard/leaderboard.service.ts<gh_stars>1-10 import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Leaderboard } from '../entities/leaderboard.entity'; @Injectable() export class LeaderboardService { constructor( @InjectRepository(Leaderboard, 'readonly') private readonly leaderboardRepository: Repository<Leaderboard>, ) { } async getCurrentLeaderboard(): Promise<Leaderboard> { return await this.leaderboardRepository .findOne({ relations: ["ranks", 'ranks.station'], order: { date: 'DESC', createdAt: 'DESC' } }); } async getCurrentRankForStation(stationId: Number): Promise<Object> { let leaderboard = await this.getCurrentLeaderboard(); return leaderboard.ranks.find((rank) => rank.station.id === stationId); } async getLeaderboardForDate(date): Promise<Object> { const previous = await this.leaderboardRepository .findOne({ relations: ['ranks', 'ranks.station'], where: `date = DATE '${date.toDateString()}' - interval '1 month'`, order: { updatedAt: 'DESC' } }); const current = await this.leaderboardRepository .findOne({ relations: ['ranks', 'ranks.station'], where: { date: date }, order: { updatedAt: 'DESC' } }); const next = await this.leaderboardRepository .findOne({ relations: ['ranks', 'ranks.station'], where: `date = DATE '${date.toDateString()}' + interval '1 month'`, order: { updatedAt: 'ASC' } }); let output = { previous: previous, current: current, next: next } return output; } }
kevinelliott/acars-backend
src/app.controller.ts
import { Controller, Get, Post, Request, UseGuards } from '@nestjs/common'; import { AppService } from './app.service'; import { LocalAuthGuard } from './auth/local-auth.guard'; import { AuthService } from './auth/auth.service'; import { MailReportService } from './mail_report.service'; import { StationsService } from './user/stations/stations.service'; import { UsersService } from './users/users.service'; import { LeaderboardService } from './leaderboard/leaderboard.service'; @Controller() export class AppController { constructor( private readonly appService: AppService, private authService: AuthService, private leaderboardService: LeaderboardService, private stationService: StationsService, private usersService: UsersService, private reportService: MailReportService, ) {} @Get() getHello(): string { return this.appService.getHello(); } @Get('/stations/:id/send_leaderboard_report') async leaderboardReport(@Request() req) { console.log(req.params.id); let station = await this.stationService.findOne(req.params.id); console.log(station); if (!station) return false; let user = await this.usersService.findOneById(station.userId); console.log(user); if (!user) return false; let currentLeaderboardRank = await this.leaderboardService.getCurrentRankForStation(station.id); console.log(currentLeaderboardRank); this.reportService.stationLeaderboardReport(user, station, currentLeaderboardRank); return true; } @Post('auth/confirm') async confirm(@Request() req) { return this.authService.confirm(req.body.token); } @UseGuards(LocalAuthGuard) @Post('auth/login') async login(@Request() req) { return this.authService.login(req.user); } @Post('auth/register') async register(@Request() req) { return this.authService.register(req.body); } }
kevinelliott/acars-backend
src/nats/nats.module.ts
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { EventsModule } from '../events/events.module'; import { NatsController } from './nats.controller'; import { Message } from '../entities/message.entity'; import { MessageDecoding } from '../entities/message_decoding.entity'; @Module({ imports: [ EventsModule, TypeOrmModule.forFeature([Message]), TypeOrmModule.forFeature([MessageDecoding]) ], controllers: [NatsController], }) export class NatsModule {}
kevinelliott/acars-backend
src/messages/messages.service.ts
<filename>src/messages/messages.service.ts import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Like, Repository } from 'typeorm'; import { Message } from '../entities/message.entity'; @Injectable() export class MessagesService { constructor( @InjectRepository(Message, 'readonly') private readonly messageRepository: Repository<Message>, ) { } async getMessage(id): Promise<Object> { return await this.messageRepository .findOne(id, { relations: ['airframe', 'flight', 'station', 'message_decodings'] }); } async getMessages(params): Promise<Object> { let query = this.messageRepository.createQueryBuilder('messages') .leftJoinAndSelect('messages.airframe', 'airframe') .leftJoinAndSelect('messages.flight', 'flight') .leftJoinAndSelect('messages.station', 'station'); if (params.text) query = query.andWhere('messages.text ILIKE :text', { text: `%${params.text}%` }); if (params.airframe_ids) query = query.andWhere('messages.airframe_id IN (:...ids)', { ids: params.airframe_ids.split(',').map((id: string) => Number(id)) } ); if (params.flight_id) query = query.andWhere('messages.flight_id = :id', { id: params.flight_id }); if (params.station_ids) query = query.andWhere('messages.station_id IN (:...ids)', { ids: params.station_ids.split(',').map((id: string) => Number(id)) }); if (params.exclude_errors) query = query.andWhere('messages.error NOT IN (:...errors)', { errors: params.exclude_errors.split(',').map((id: string) => Number(id)) }); if (params.exclude_labels) query = query.andWhere('messages.label NOT IN (:...labels)', { labels: params.exclude_labels.split(',') }); if (params.labels) query = query.andWhere('messages.label IN (:...labels)', { labels: params.labels.split(',') }); query = query .orderBy({ 'messages.created_at': 'DESC' }) .limit(100); return await query.getMany(); } }
kevinelliott/acars-backend
src/flights/flights.module.ts
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { FlightsController } from './flights.controller'; import { FlightsService } from './flights.service'; import { Flight } from '../entities/flight.entity'; import { OgmaModule } from '@ogma/nestjs-module'; @Module({ imports: [ TypeOrmModule.forFeature([Flight], 'readonly'), OgmaModule.forFeature(FlightsService), ], controllers: [FlightsController], providers: [FlightsService], }) export class FlightsModule {}
kevinelliott/acars-backend
src/entities/leaderboard.entity.ts
<filename>src/entities/leaderboard.entity.ts import { AfterLoad, Entity, Column, CreateDateColumn, UpdateDateColumn, PrimaryGeneratedColumn, OneToMany, RelationCount, ManyToMany, JoinTable, Timestamp, } from 'typeorm'; import { LeaderboardRank } from './leaderboard_rank.entity'; @Entity('leaderboards') export class Leaderboard { @PrimaryGeneratedColumn() id: number; @Column({ name: 'date' }) date: Date; @OneToMany(type => LeaderboardRank, rank => rank.leaderboard) ranks: LeaderboardRank[]; @CreateDateColumn({ name: 'created_at' }) createdAt: Date; @UpdateDateColumn({ name: 'updated_at' }) updatedAt: Date; }
kevinelliott/acars-backend
src/entities/station_message_count.entity.ts
import { Column, Entity, JoinColumn, PrimaryGeneratedColumn, OneToOne, } from 'typeorm'; import { Station } from './station.entity'; @Entity('station_message_counts') export class StationMessageCount { @PrimaryGeneratedColumn() id: number; @OneToOne(type => Station, station => station.stationMessageCount) @JoinColumn({ name: 'station_id' }) station: Station; @Column({ name: 'station_id' }) stationId: number; @Column({ name: 'messages_count' }) messagesCount: number; }
Goytai/NasaAPI
src/shared/graphql/index.ts
import path from 'path'; import Container from 'typedi'; import { ApolloServer } from 'apollo-server'; import { buildSchemaSync } from 'type-graphql'; import { useContainer } from 'typeorm'; const port = Number(process.env.PORT) || 4000; const schema = buildSchemaSync({ container: Container, resolvers: [ path.join(__dirname, '..', '..', 'modules', '**', '*.resolver.{ts,js}') ] }); const app = new ApolloServer({ schema }); useContainer(Container); app.listen(port).then(({ url }) => { // eslint-disable-next-line console.log(`Server up in ${url}`); });
Goytai/NasaAPI
src/modules/planets/services/suitablePlanets.service.ts
import { MongoRepository } from 'typeorm'; import { InjectRepository } from 'typeorm-typedi-extensions'; import { Service } from 'typedi'; import { Stations } from '../../stations/entities/stations.entity'; import { SuitablePlanetsResponse } from '../types/suitablePlanets.type'; import { NasaAPI } from '../../../shared/rest/index'; @Service() export class SuitablePlanetsService { constructor( @InjectRepository(Stations) private readonly stationRepository: MongoRepository<Stations>, private readonly api: NasaAPI ) {} public async execute(): Promise<SuitablePlanetsResponse[]> { const remoteResponse = await this.api.getPlanets(); const suitablePlanets = remoteResponse.filter( planet => planet.mass && planet.mass > 10 ); const response: SuitablePlanetsResponse[] = []; for (const planet of suitablePlanets) { const verifyExists = await this.stationRepository.findOne({ planetName: planet.name }); response.push({ ...planet, hasStation: !!verifyExists }); } return response; } }
Goytai/NasaAPI
src/modules/stations/services/installStation.service.ts
<filename>src/modules/stations/services/installStation.service.ts import { Service } from 'typedi'; import { MongoRepository } from 'typeorm'; import { InjectRepository } from 'typeorm-typedi-extensions'; import { Stations } from '../entities/stations.entity'; import { InstallStationInput } from '../input/installStation.input'; import { InstallStationResponse } from '../types/installStation.type'; @Service() export class InstallStationService { constructor( @InjectRepository(Stations) private readonly stationRepository: MongoRepository<Stations> ) {} public async execute( planet: InstallStationInput ): Promise<InstallStationResponse> { const checkStationExist = await this.stationRepository.findOne({ planetName: planet.name }); if (checkStationExist) { return checkStationExist; } const newStation = this.stationRepository.create({ planetName: planet.name }); const saveStation = await this.stationRepository.save(newStation); return saveStation; } }
Goytai/NasaAPI
src/modules/stations/services/stations.service.ts
import { Service } from 'typedi'; import { MongoRepository } from 'typeorm'; import { InjectRepository } from 'typeorm-typedi-extensions'; import { Stations } from '../entities/stations.entity'; import { StationsResponse } from '../types/station.type'; @Service() export class StationsService { constructor( @InjectRepository(Stations) private readonly stationRepository: MongoRepository<Stations> ) {} public async execute(): Promise<StationsResponse[]> { const allStations = await this.stationRepository.find({}); return allStations; } }
Goytai/NasaAPI
src/modules/stations/stations.resolver.ts
<reponame>Goytai/NasaAPI import { Arg, Mutation, Query } from 'type-graphql'; import { Service } from 'typedi'; import { InstallStationResponse } from './types/installStation.type'; import { InstallStationInput } from './input/installStation.input'; import { InstallStationService } from './services/installStation.service'; import { StationsResponse } from './types/station.type'; import { StationsService } from './services/stations.service'; @Service() export class PlanetsResolver { constructor( private readonly installStationService: InstallStationService, private readonly stationsService: StationsService ) {} @Query(() => [StationsResponse]) public async stations(): Promise<StationsResponse[]> { return this.stationsService.execute(); } @Mutation(() => InstallStationResponse) public async installStation( @Arg('planet') planet: InstallStationInput ): Promise<InstallStationResponse> { return this.installStationService.execute(planet); } }
Goytai/NasaAPI
src/modules/stations/entities/stations.entity.ts
import { Column, CreateDateColumn, Entity, ObjectID, ObjectIdColumn } from 'typeorm'; @Entity('stations') export class Stations { @ObjectIdColumn() id: ObjectID; @Column() planetName: string; @CreateDateColumn({ type: 'timestamp' }) createdAt: Date; }
Goytai/NasaAPI
src/modules/stations/types/station.type.ts
<reponame>Goytai/NasaAPI import { Field, ID, ObjectType } from 'type-graphql'; import { ObjectID } from 'typeorm'; @ObjectType() export class StationsResponse { @Field(() => ID) id: ObjectID; @Field() planetName: string; @Field() createdAt: Date; }
Goytai/NasaAPI
src/shared/rest/index.ts
<filename>src/shared/rest/index.ts<gh_stars>1-10 import { RESTDataSource } from 'apollo-datasource-rest'; import { SuitablePlanetsResponse } from 'modules/planets/types/suitablePlanets.type'; // eslint-disable-next-line import/no-extraneous-dependencies import { DataSourceConfig } from 'apollo-datasource'; import { Service } from 'typedi'; type SuitablePlanetsRemoteResponse = Omit< SuitablePlanetsResponse, 'hasStation' >; @Service() export class NasaAPI extends RESTDataSource { constructor() { super(); this.baseURL = 'https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI'; this.initialize({} as DataSourceConfig<any>); } public async getPlanets(): Promise<SuitablePlanetsRemoteResponse[]> { const response: string = await this.get('/', { table: 'exoplanets', format: 'json' }); const startIndex = response.search(/\[/); const planetsString = response.slice(startIndex); // eslint-disable-next-line @typescript-eslint/no-explicit-any const objectData: any[] = JSON.parse(planetsString); const planets: SuitablePlanetsRemoteResponse[] = []; objectData.forEach(planet => planets.push({ name: planet.pl_name, mass: planet.pl_bmassj }) ); return planets; } }
Goytai/NasaAPI
src/shared/index.ts
<filename>src/shared/index.ts import 'reflect-metadata'; import './typeorm'; import './graphql';
Goytai/NasaAPI
src/modules/planets/planets.resolver.ts
import { Query } from 'type-graphql'; import { Service } from 'typedi'; import { SuitablePlanetsService } from './services/suitablePlanets.service'; import { SuitablePlanetsResponse } from './types/suitablePlanets.type'; @Service() export class PlanetsResolver { constructor( private readonly suitablePlanetsServices: SuitablePlanetsService ) {} @Query(() => [SuitablePlanetsResponse]) public async suitablePlanets(): Promise<SuitablePlanetsResponse[]> { const response = await this.suitablePlanetsServices.execute(); return response; } }
Goytai/NasaAPI
src/modules/planets/types/suitablePlanets.type.ts
<filename>src/modules/planets/types/suitablePlanets.type.ts import { Field, Float, ObjectType } from 'type-graphql'; @ObjectType() export class SuitablePlanetsResponse { @Field() name: string; @Field(() => Float, { nullable: true }) mass?: number; @Field() hasStation: boolean; }
VON-Development-Studio/angular-rest-service
src/lib/von-rest.service.ts
<reponame>VON-Development-Studio/angular-rest-service<filename>src/lib/von-rest.service.ts import { HttpClient, HttpHeaders } from '@angular/common/http'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; import { Observable } from 'rxjs'; import { map, share, take } from 'rxjs/operators'; import { VonHttpOptionsModel } from './model/von-http-options.model'; export abstract class VonRestService { constructor( protected http: HttpClient, protected sanitizer: DomSanitizer ) { } private setHeaders = (contentType: string = 'application/json'): HttpHeaders => { return new HttpHeaders({ 'Content-Type': 'application/json', Accept: contentType }); } private setOptions = (params?: { [key: string]: any }): VonHttpOptionsModel => { return { headers: this.setHeaders(), params, withCredentials: true }; } private setUrlParams = (url: string, params?: { [key: string]: any }) => { if (params != null) { for (const p in params) { if (p != null) { url = url.replace(`{${p}}`, params[p]); } } } return url; } authenticate = (url: string, username: string, password: string): Observable<any> => { const authorization = btoa(`${username}:${password}`); const headers = new HttpHeaders({ authorization: `Basic ${authorization}`, }); return this.http.get(url, { headers, withCredentials: true }).pipe( take(1), share() ); } logout = (url: string): Observable<any> => { return this.http.delete<string>(url, this.setOptions()).pipe( take(1), share() ); } get = <T = any>(url: string, urlParams?: any, queryParams?: any): Observable<T> => { url = this.setUrlParams(url, urlParams); return this.http.get<T>(url, this.setOptions(queryParams)); } delete = <T = any>(url: string, urlParams?: any, queryParams?: any): Observable<T> => { url = this.setUrlParams(url, urlParams); return this.http.delete<T>(url, this.setOptions(queryParams)); } post = <T = any>(url: string, body: any, urlParams?: any, queryParams?: any): Observable<T> => { url = this.setUrlParams(url, urlParams); return this.http.post<T>(url, body, this.setOptions(queryParams)); } put = <T = any>(url: string, body: any, urlParams?: any, queryParams?: any): Observable<T> => { url = this.setUrlParams(url, urlParams); return this.http.put<T>(url, body, this.setOptions(queryParams)); } patch = <T = any>(url: string, body: any, urlParams?: any, queryParams?: any): Observable<T> => { url = this.setUrlParams(url, urlParams); return this.http.patch<T>(url, body, this.setOptions(queryParams)); } private setFileOptions = (contentType: string, queryParams?: { [key: string]: any }): VonHttpOptionsModel => { return { ...this.setOptions(queryParams), headers: this.setHeaders(contentType), responseType: 'blob' as 'json' }; } getFile = (contentType: string, url: string, urlParams?: any, queryParams?: any): Observable<SafeResourceUrl> => { url = this.setUrlParams(url, urlParams); return this.http.get(url, this.setFileOptions(contentType, queryParams)).pipe( map((res: any) => { const fileBlob = new Blob([res], { type: contentType }); const objUrl = URL.createObjectURL(fileBlob); const sanitized = this.sanitizer.bypassSecurityTrustResourceUrl(objUrl); return sanitized; }) ); } postFile = (contentType: string, url: string, body: any, urlParams?: any, queryParams?: any): Observable<any> => { url = this.setUrlParams(url, urlParams); return this.http.post(url, body, this.setFileOptions(contentType, queryParams)); } putFile = (contentType: string, url: string, body: any, urlParams?: any, queryParams?: any): Observable<any> => { url = this.setUrlParams(url, urlParams); return this.http.put(url, body, this.setFileOptions(contentType, queryParams)); } patchFile = (contentType: string, url: string, body: any, urlParams?: any, queryParams?: any): Observable<any> => { url = this.setUrlParams(url, urlParams); return this.http.patch(url, body, this.setFileOptions(contentType, queryParams)); } }
VON-Development-Studio/angular-rest-service
src/public-api.ts
<filename>src/public-api.ts export * from './lib/model/von-error-response.model'; export * from './lib/model/von-error-rest-interceptor.model'; export * from './lib/model/von-page-response.model'; export * from './lib/model/von-page-response.model'; export * from './lib/von-rest-interceptor.service'; export * from './lib/von-rest.service';
VON-Development-Studio/angular-rest-service
src/lib/model/von-error-response.model.ts
<reponame>VON-Development-Studio/angular-rest-service<filename>src/lib/model/von-error-response.model.ts export interface VonErrorResponseModel { code?: string | null; message?: string | null; payload?: any | null; }
VON-Development-Studio/angular-rest-service
src/lib/von-rest-interceptor.service.ts
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http'; import { Router } from '@angular/router'; import { Observable, throwError } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { VonErrorRestInterceptorModel } from './model/von-error-rest-interceptor.model'; export abstract class VonRestInterceptorService implements HttpInterceptor { protected consoleDebug = false; protected errorResponseUnknown = 'Unknown Error'; protected errorResponseForbidden = 'Forbidden Error'; protected urlWhoAmI = 'api/who-am-i'; constructor( protected router: Router ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).pipe( map((event: HttpEvent<any>) => { if (event instanceof HttpResponse) { if (event.status === 200 || event.status === 204) { this.postHttpRequest(); return event; } if (event.status !== 200) { const error: VonErrorRestInterceptorModel = { status: event.status, message: event.statusText }; if (this.consoleDebug) { console.error('[ErrorWS]: ', error); } throw error; } } this.postHttpRequest(); return event; }), catchError((errorResponse: HttpErrorResponse) => { if (this.consoleDebug) { console.error('[Fatal]: ', errorResponse); } const error: VonErrorRestInterceptorModel = { status: errorResponse.status, message: '' }; if (errorResponse.status === 0) { error.message = this.errorResponseUnknown; } if (errorResponse.status === 401) { error.message = errorResponse.error ? errorResponse.error : this.errorResponseForbidden; } if (errorResponse.status === 403 || (errorResponse.url && errorResponse.url.indexOf(this.urlWhoAmI) > -1)) { this.router.navigate(['403']); } return throwError(error); }) ); } protected postHttpRequest = () => { } }
hasantezcan/PerfAnalytics-Dashboard
src/util/text.utils.tsx
<filename>src/util/text.utils.tsx import { Tooltip } from 'antd' /* Function to generate the text inside Tooltip with ellipsis when text exceeds given length */ function getClippedText(text: string, maxLength: number) { return text.length > maxLength ? ( <Tooltip title={text}>{text.substr(0, maxLength)}...</Tooltip> ) : ( text ) } export { getClippedText }
hasantezcan/PerfAnalytics-Dashboard
src/components/UrlFilter/index.spec.tsx
<gh_stars>1-10 import { render } from '@testing-library/react' import UrlFilter from '.' describe('UrlFilter specs', () => { it('Should render when urls is exist', () => { let chosenUrls: string[] = ['hasantezcan.dev'] function setChosenUrls(urls: string[]) { chosenUrls = urls } const urls: string[] = [ 'hasantezcan.dev', 'github.com/hasantezcan', 'linkedin/hasantezcan' ] const { container, getByText } = render( <UrlFilter urls={urls} onSelect={setChosenUrls} selectedUrls={chosenUrls} /> ) expect(container.getElementsByClassName('ant-typography').length).toBe(1) expect(getByText('Check all')).toBeInTheDocument() expect(container.getElementsByClassName('ant-checkbox-group').length).toBe( 1 ) }) it('Should render when urls is not exist', () => { let chosenUrls: string[] = [] function setChosenUrls(urls: string[]) { chosenUrls = urls } const urls: string[] = [] const { container, getByText } = render( <UrlFilter urls={urls} onSelect={setChosenUrls} selectedUrls={chosenUrls} /> ) expect(container.getElementsByClassName('ant-typography').length).toBe(1) expect( getByText('There is not metric found in this time range') ).toBeInTheDocument() expect(container.getElementsByClassName('ant-empty-footer').length).toBe(1) }) })
hasantezcan/PerfAnalytics-Dashboard
src/components/LineChartWidget/index.tsx
import { ResponsiveContainer, LineChart, Line, CartesianGrid, XAxis, YAxis, Tooltip } from 'recharts' import { Col, Card, Empty } from 'antd' import { ChartMetric } from '~/models/Metric' import { stringToColor } from '../../util/color.utils' import moment from 'moment' interface LineChartWidgetProps { title?: string data?: ChartMetric[] selectedUrls: string[] } function LineChartWidget({ data, selectedUrls, title }: LineChartWidgetProps) { return ( <Col xs={{ span: 24 }} md={{ span: 12 }}> <Card title={title}> {selectedUrls.length > 0 ? ( <ResponsiveContainer width="100%" height={220}> <LineChart margin={{ top: 5, right: 20, bottom: 5, left: 20 }}> {data ?.filter((item) => selectedUrls.includes(item.url)) .map((url) => ( <Line key={url.url} type="monotone" stroke={stringToColor(url.url)} dot={false} dataKey="value" name={url.url} data={url.data} /> ))} <CartesianGrid stroke="#ccc" strokeDasharray="3 3" /> <XAxis domain={['auto', 'auto']} dataKey="time" name="Time" type="number" tickFormatter={(unixTime) => moment(unixTime).format('HH:mm:ss') } /> <YAxis dataKey="value" type="number" tickFormatter={(value) => `${value} ms`} /> <Tooltip labelFormatter={(name: any) => moment(name).format('HH:mm:ss')} /> </LineChart> </ResponsiveContainer> ) : ( <Empty /> )} </Card> </Col> ) } export default LineChartWidget
hasantezcan/PerfAnalytics-Dashboard
src/factories/metricfactory.tsx
import faker from 'faker' import { Metric } from '~/models/Metric' const { datatype: { number }, lorem: { word } } = faker function metricFactory(times: number = 1): Metric[] { return Array.from({ length: times }, (value, index: number) => { return { URL: word(), UserAgent: word(), TTFB: number(), FCP: number(), DomLoad: number(), WindowLoad: number(), Entries: Array.from({ length: times }, () => { return { name: word(), initiatorType: word(), responseEnd: number(), transferSize: number() } }), _id: word(), createdAt: new Date(Date.now() + index * 24) } }) } export { metricFactory }
hasantezcan/PerfAnalytics-Dashboard
src/components/TitleWidget/index.spec.tsx
<reponame>hasantezcan/PerfAnalytics-Dashboard<gh_stars>1-10 import { render } from '@testing-library/react' import TitleWidget from '.' describe('LineChartWidget specs', () => { it('Should render', () => { const { container } = render(<TitleWidget />) expect(container.getElementsByClassName('ant-typography').length).toBe(1) }) })
hasantezcan/PerfAnalytics-Dashboard
src/service/service.spec.ts
<reponame>hasantezcan/PerfAnalytics-Dashboard<gh_stars>1-10 import axios from './axios' import sinon, { SinonStub } from 'sinon' import { waitFor } from '@testing-library/react' import { metricFactory } from '../factories/metricfactory' import { urlMetricFactory } from '../factories/urlMetricFactory' import { fetchMetricByTimeRange, fetchMetricByURL } from '.' const sandbox = sinon.createSandbox() describe('Service specs', () => { let getStub: SinonStub beforeEach(() => { getStub = sandbox.stub(axios, 'get') }) afterEach(() => { sandbox.verifyAndRestore() }) it('Should fetch metrics', () => { const data = metricFactory() const start = new Date() const end = new Date() getStub .withArgs('/api/metrics', { params: { start, end } }) .returns({ data }) waitFor(() => { expect(fetchMetricByTimeRange(start, end)).toBe(data) }) }) it('Should fetch URLmetrics', () => { const data = urlMetricFactory() const start = new Date() const end = new Date() getStub .withArgs('/api/metrics-by-url', { params: { start, end } }) .returns({ data }) waitFor(() => { expect(fetchMetricByURL(start, end)).toBe(data) }) }) })
hasantezcan/PerfAnalytics-Dashboard
src/util/util.spec.tsx
import { lorem } from 'faker' import { render } from '@testing-library/react' import { stringToColor } from './color.utils' import { getClippedText } from './text.utils' describe('Color specs', () => { it('Should return #000000 for empty input', () => { expect(stringToColor('')).toEqual('#000000') }) it('Should return #35E8E6 for hasantezcan.dev ', () => { expect(stringToColor('hasantezcan.dev')).toEqual('#35e8e6') }) }) describe('Text specs', () => { const { words, word } = lorem it('Should return Tooltip', () => { const input = words(20) const maxLength = 40 const { container } = render( getClippedText(input, maxLength) as JSX.Element ) expect(container.getElementsByTagName('span')[0].innerHTML).toEqual( `${input.substr(0, maxLength)}...` ) }) it('Should return string', () => { const input = word() expect(getClippedText(input, 40)).toEqual(input) }) })
hasantezcan/PerfAnalytics-Dashboard
src/service/axios.ts
import Axios from 'axios' const axios = Axios.create({ baseURL: 'https://perfanalytics-api-ht.herokuapp.com', headers: { 'Content-Type': 'application/json' } }) export default axios
hasantezcan/PerfAnalytics-Dashboard
src/components/UrlFilter/index.tsx
import { Checkbox, Typography, Form, Empty, Button } from 'antd' import { getClippedText } from '../../util/text.utils' const { Title } = Typography const CheckboxGroup = Checkbox.Group interface UrlFilterProps { urls: string[] onSelect: (urls: string[]) => void selectedUrls: string[] } function UrlFilter({ urls, onSelect, selectedUrls }: UrlFilterProps) { const onChange = (list: any) => { onSelect(list) } const onCheckAllChange = (e: any) => { onSelect(e.target.checked ? urls : []) } const urlOptions = urls.map((url) => ({ label: getClippedText(url, 40), value: url })) return ( <Form> <Title level={3}>Select URL</Title> {urls.length > 0 ? ( <> <Form.Item labelCol={{ span: 6, offset: 6 }}> <Checkbox indeterminate={ selectedUrls.length > 0 && selectedUrls.length !== urls.length } onChange={onCheckAllChange} checked={selectedUrls.length > 0} > Check all </Checkbox> </Form.Item> <Form.Item> <CheckboxGroup options={urlOptions} value={selectedUrls} onChange={onChange} /> </Form.Item> </> ) : ( <Empty image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg" imageStyle={{ height: 60 }} description={ <span>There is not metric found in this time range</span> } > <Button href="https://github.com/hasantezcan/PerfAnalytics-Dashboard#:~:text=You%20can%20create%20analytics%20metric%20data%20from%20those%20sites:" target="_blank" rel="noreferrer" type="primary" > Create Now </Button> </Empty> )} </Form> ) } export default UrlFilter
hasantezcan/PerfAnalytics-Dashboard
src/layouts/BaseLayout.tsx
<filename>src/layouts/BaseLayout.tsx import { PropsWithChildren } from 'react' import { Layout, Row, Col } from 'antd' import classNames from 'classnames/bind' import styles from './styles.module.scss' const { Footer, Content } = Layout const cx = classNames.bind(styles) interface BaseLayoutProps {} function BaseLayout({ children }: PropsWithChildren<BaseLayoutProps>) { return ( <Layout className={cx('base-layout')}> <Content> <Row justify={'center'} style={{ paddingTop: 25 }}> <Col lg={{ span: 18 }}>{children}</Col> </Row> </Content> <Footer> <Row justify={'center'}> <p> Made by{' '} <a target="_blank" rel="noreferrer" href="https://github.com/hasantezcan" > @hasantezcan{' '} </a> </p> <p></p> <p> , Source code{' '} <a target="_blank" rel="noreferrer" href="https://github.com/hasantezcan/PerfAnalytics-Dashboard" > in GitHub </a> </p> </Row> </Footer> </Layout> ) } export default BaseLayout
hasantezcan/PerfAnalytics-Dashboard
src/context/AppProviders/index.tsx
import { PropsWithChildren } from 'react' import { MetricProvider } from '../MetricProvider' function AppProviders({ children }: PropsWithChildren<any>) { return <MetricProvider>{children}</MetricProvider> } export default AppProviders
hasantezcan/PerfAnalytics-Dashboard
src/components/TitleWidget/index.tsx
<filename>src/components/TitleWidget/index.tsx import { Typography } from 'antd' import classNames from 'classnames/bind' import styles from './styles.module.scss' const { Title } = Typography const cx = classNames.bind(styles) function TitleWidget() { return <Title className={cx('title-widget')}>PerfAnalytics Dashboard</Title> } export default TitleWidget
hasantezcan/PerfAnalytics-Dashboard
src/routes/Main/Entries/index.tsx
import { useMetricContext } from '~/context/MetricProvider' import EntriesWidget from '~/components/EntriesWidget' function Entries() { const { metrics, selectedUrls } = useMetricContext() return <EntriesWidget metrics={metrics} selectedUrls={selectedUrls} /> } export default Entries
hasantezcan/PerfAnalytics-Dashboard
src/components/TimeRangeFilter/index.tsx
import { useState } from 'react' import { DatePicker, TimePicker, Button, Form, Typography } from 'antd' import moment from 'moment' const { Title } = Typography interface TimeRangeFilterProps { setTimeRange: (start: any, end: any) => void } function TimeRangeFilter({ setTimeRange }: TimeRangeFilterProps) { const [date, setDate] = useState(moment().format('YYYY-MM-DD')) const [startTime, setStartTime] = useState( moment().subtract(30, 'minutes').format('HH:mm:ss') ) const [endTime, setEndTime] = useState(moment().format('HH:mm:ss')) const handleTimeRange = () => { const start = moment(`${date} ${startTime}`).toISOString() const end = moment(`${date} ${endTime}`).toISOString() setTimeRange(start, end) } return ( <Form> <Title level={3}>Select Time Range</Title> <Form.Item> <DatePicker onChange={(value, dateString) => setDate(dateString)} defaultValue={moment()} /> </Form.Item> <Form.Item> <TimePicker.RangePicker onChange={(value, dateString) => { setStartTime(dateString[0]) setEndTime(dateString[1]) }} defaultValue={[moment().subtract(30, 'minutes'), moment()]} /> </Form.Item> <Form.Item> <Button type="primary" onClick={handleTimeRange}> Get Metrics </Button> </Form.Item> </Form> ) } export default TimeRangeFilter
hasantezcan/PerfAnalytics-Dashboard
src/service/index.ts
<gh_stars>1-10 import axios from './axios' import { Metric, MetricByURL } from '~/models/Metric' async function fetchMetricByTimeRange(start?: Date, end?: Date) { const { data } = await axios.get('/api/metrics', { params: { start, end } }) return data as Metric[] } async function fetchMetricByURL(start?: Date, end?: Date) { const { data } = await axios.get('/api/metrics-by-url', { params: { start, end } }) return data as MetricByURL[] } export { fetchMetricByTimeRange, fetchMetricByURL }
hasantezcan/PerfAnalytics-Dashboard
src/routes/Main/Filter/index.tsx
import { useEffect } from 'react' import { Row, Col, Card } from 'antd' import TimeRangeFilter from '@components/TimeRangeFilter/index' import UrlFilter from '~/components/UrlFilter' import { fetchMetricByTimeRange, fetchMetricByURL } from '~/service' import { useMetricContext } from '~/context/MetricProvider' function Filter() { const { setUrlMetrics, setMetrics, urlMetrics, setSelectedUrls, selectedUrls } = useMetricContext() const urls = urlMetrics.map((url) => url.URL) const setTimeRange = async (start: any, end: any) => { const metricUrl = await fetchMetricByURL(start, end) const metricByTimeRange = await fetchMetricByTimeRange(start, end) setUrlMetrics(metricUrl) setMetrics(metricByTimeRange) } useEffect(() => { setSelectedUrls(urls) // eslint-disable-next-line }, [urlMetrics]) return ( <Card> <Row gutter={16}> <Col md={12}> <TimeRangeFilter setTimeRange={setTimeRange} /> </Col> <Col md={12}> <UrlFilter urls={urls} onSelect={setSelectedUrls} selectedUrls={selectedUrls} /> </Col> </Row> </Card> ) } export default Filter
hasantezcan/PerfAnalytics-Dashboard
src/components/TimeRangeFilter/index.spec.tsx
import { render, fireEvent, waitFor } from '@testing-library/react' import sinon, { SinonSpy } from 'sinon' import TimeRangeFilter from '.' const sandbox = sinon.createSandbox() describe('TimeRangeFilter specs', () => { const handleTimeRange = (start: any, end: any) => {} let handleTimeRangeSpy: SinonSpy beforeEach(() => { handleTimeRangeSpy = sandbox.spy(handleTimeRange) }) afterEach(() => { sandbox.verifyAndRestore() }) it('Should render time range control form ', () => { const { container } = render( <TimeRangeFilter setTimeRange={handleTimeRange} /> ) expect(container.getElementsByClassName('ant-form').length).toBe(1) }) it('Should render date picker when click on it', () => { const { container } = render( <TimeRangeFilter setTimeRange={handleTimeRange} /> ) const datePicker = container.getElementsByClassName('ant-picker-input')[0] fireEvent.click(datePicker) waitFor(() => { expect( container.getElementsByClassName('ant-picker-dropdown').length ).toBe(1) }) }) it('Should render time picker when click on it', () => { const { container } = render( <TimeRangeFilter setTimeRange={handleTimeRange} /> ) const timePicker = container.getElementsByClassName('ant-picker-range')[0] fireEvent.click(timePicker) waitFor(() => { expect( container.getElementsByClassName('ant-picker-panel-container').length ).toBe(1) }) }) it('Should call handleTimeRange function', () => { const { container } = render( <TimeRangeFilter setTimeRange={handleTimeRange} /> ) const button = container.getElementsByClassName('ant-btn')[0] fireEvent.click(button) waitFor(() => { expect(handleTimeRangeSpy.calledOnce).toBe(true) }) }) })
hasantezcan/PerfAnalytics-Dashboard
src/models/Metric.ts
interface MetricTypes { TTFB: string FCP: string DomLoad: string WindowLoad: string } type MetricType = keyof MetricTypes interface Metric { URL: string UserAgent: string TTFB: number FCP: number DomLoad: number WindowLoad: number Entries: Entry[] createdAt: Date _id: string } interface TimeValue { value: number time: Date } interface MetricByURL { URL: string TTFB: TimeValue[] FCP: TimeValue[] DomLoad: TimeValue[] WindowLoad: TimeValue[] } interface TimeStampValue { value: number time: number } interface ChartMetric { url: string data: TimeStampValue[] } export interface Entry { name: string initiatorType: string responseEnd: number transferSize: number } export type { Metric, MetricByURL, TimeValue, MetricType, ChartMetric, TimeStampValue }
hasantezcan/PerfAnalytics-Dashboard
src/context/MetricProvider.tsx
import { createContext, useContext, PropsWithChildren, useState, useEffect, Dispatch, SetStateAction } from 'react' import { Metric, MetricByURL } from '../models/Metric' import { fetchMetricByTimeRange, fetchMetricByURL } from '../service' interface MetricContextModel { metrics: Metric[] setMetrics: Dispatch<SetStateAction<Metric[]>> urlMetrics: MetricByURL[] setUrlMetrics: Dispatch<SetStateAction<MetricByURL[]>> selectedUrls: string[] setSelectedUrls: Dispatch<SetStateAction<string[]>> } const MetricContext = createContext<MetricContextModel>( {} as MetricContextModel ) function MetricProvider({ children }: PropsWithChildren<any>) { const [metrics, setMetrics] = useState<Metric[]>([]) const [urlMetrics, setUrlMetrics] = useState<MetricByURL[]>([]) const [selectedUrls, setSelectedUrls] = useState<string[]>([]) useEffect(() => { const initializeMetrics = async () => { setMetrics(await fetchMetricByTimeRange()) setUrlMetrics(await fetchMetricByURL()) } initializeMetrics().then() }, []) const context: MetricContextModel = { metrics, setMetrics, urlMetrics, setUrlMetrics, selectedUrls, setSelectedUrls } return ( <MetricContext.Provider value={context}>{children}</MetricContext.Provider> ) } const useMetricContext = () => useContext(MetricContext) export { MetricContext, MetricProvider, useMetricContext }
hasantezcan/PerfAnalytics-Dashboard
src/components/LineChartWidget/index.spec.tsx
import { render, waitFor } from '@testing-library/react' import LineChartWidget from '.' import { ChartMetric } from '~/models/Metric' import { chartMetricFactory } from '../../factories/chartMetricFactory' import moment from 'moment' describe('LineChartWidget specs', () => { let data: ChartMetric[] beforeEach(() => { data = chartMetricFactory(2) }) it('Should render', () => { const { container } = render( <LineChartWidget selectedUrls={[]} title="FCP" /> ) expect(container.getElementsByClassName('ant-card').length).toBe(1) expect(container.getElementsByClassName('ant-card-head').length).toBe(1) expect(container.getElementsByClassName('ant-card-body').length).toBe(1) }) it('Should show empty dummy when data is not exist', () => { const { container } = render(<LineChartWidget selectedUrls={[]} />) expect(container.getElementsByClassName('ant-empty').length).toBe(1) }) it('Should show line chart when data is exist', () => { const { container } = render(<LineChartWidget selectedUrls={['url']} />) expect( container.getElementsByClassName('recharts-responsive-container').length ).toBe(1) }) it('Should show two line chart if selected url count is two ', () => { data[0].url = 'url0' data[1].url = 'url1' const { container } = render( <LineChartWidget selectedUrls={['url0, url1']} data={data} /> ) waitFor(() => { expect(container.getElementsByClassName('recharts-line').length).toBe(2) }) }) it('Should format date', () => { const date = new Date().getTime() data[0].data[0].time = date const { getByText } = render( <LineChartWidget selectedUrls={['url0, url1']} data={data} /> ) waitFor(() => { expect(getByText(moment(date).format('HH:mm:ss'))).toBe(true) }) }) })
hasantezcan/PerfAnalytics-Dashboard
src/routes/Main/index.tsx
<gh_stars>1-10 import { Row, Col } from 'antd' import BaseLayout from '~/layouts/BaseLayout' import PerfCharts from './PerfCharts' import Filter from './Filter' import Entries from './Entries/index' import TitleWidget from '~/components/TitleWidget' function Main() { return ( <BaseLayout> <Row gutter={[16, 16]}> <Col span={24}> <TitleWidget /> </Col> <Col span={24}> <Filter /> </Col> <Col span={24}> <PerfCharts /> </Col> <Col span={24}> <Entries /> </Col> </Row> </BaseLayout> ) } export default Main
hasantezcan/PerfAnalytics-Dashboard
src/App.tsx
<filename>src/App.tsx<gh_stars>1-10 import AppProviders from '~/context/AppProviders' import Main from '~/routes/Main' import '~/styles/App.less' function App() { return ( <AppProviders> <Main /> </AppProviders> ) } export default App
hasantezcan/PerfAnalytics-Dashboard
src/routes/Main/PerfCharts/index.tsx
<reponame>hasantezcan/PerfAnalytics-Dashboard import { Row } from 'antd' import LineChartWidget from '@components/LineChartWidget' import { useMetricContext } from '~/context/MetricProvider' import { ChartMetric, MetricType, TimeStampValue } from '~/models/Metric' function PerfCharts() { const { urlMetrics, selectedUrls } = useMetricContext() const mapMetrics = (type: MetricType): ChartMetric[] => urlMetrics.map((url) => ({ url: url.URL, data: url[type].map( (i): TimeStampValue => ({ value: i.value, time: new Date(i.time).getTime() }) ) })) return ( <Row gutter={[16, 16]}> <LineChartWidget data={mapMetrics('TTFB')} title="TTFB" selectedUrls={selectedUrls} /> <LineChartWidget data={mapMetrics('FCP')} title="FCP" selectedUrls={selectedUrls} /> <LineChartWidget data={mapMetrics('DomLoad')} title="DomLoad" selectedUrls={selectedUrls} /> <LineChartWidget data={mapMetrics('WindowLoad')} title="WindowLoad" selectedUrls={selectedUrls} /> </Row> ) } export default PerfCharts
hasantezcan/PerfAnalytics-Dashboard
src/components/EntriesWidget/index.tsx
import { useState } from 'react' import { Table, Typography } from 'antd' import moment from 'moment' import { getClippedText } from '../../util/text.utils' import { Metric } from '~/models/Metric' import './style.css' const { Title } = Typography interface EntriesWidgetProps { metrics: Metric[] selectedUrls: string[] } function EntriesWidget({ metrics, selectedUrls }: EntriesWidgetProps) { const [expandedRowKeys, setExpandedRowKeys] = useState([]) const [expandedRowEntries, setExpandedRowEntries] = useState([]) const onTableRowExpand = (expanded: any, record: any) => { const keys = [] if (expanded) { keys.push(record._id) } setExpandedRowEntries(record.Entries) setExpandedRowKeys(keys as any) } const expandedRowRender = () => { const columns = [ { title: 'Name', dataIndex: 'name', key: 'name', ellipsis: { showTitle: false }, render: (name: any) => ( <a href={name} target="_blank" rel="noreferrer"> {getClippedText(name, 50)} </a> ) }, { title: 'Initiator Type', dataIndex: 'initiatorType', key: 'initiatorType' }, { title: 'Response End', dataIndex: 'responseEnd', key: 'responseEnd', ellipsis: true }, { title: 'Transfer Size', dataIndex: 'transferSize', key: 'transferSize', render: (transferSize: any) => `${transferSize} B` }, { title: 'Time', dataIndex: 'createdAt', key: 'createdAt', render: (createdAt: any) => moment(createdAt).format('HH:mm:ss') } ] return ( <Table columns={columns} dataSource={expandedRowEntries} pagination={false} tableLayout="auto" /> ) } /* istanbul ignore next */ const columns = [ { title: 'Url', dataIndex: 'URL', key: 'URL', ellipsis: { showTitle: false }, render: (URL: any) => ( <a href={URL} target="_blank" rel="noreferrer"> {getClippedText(URL, 65)} </a> ), sorter: (a: any, b: any) => a.URL.length - b.URL.length }, { title: 'UserAgent', dataIndex: 'UserAgent', key: 'UserAgent', ellipsis: { showTitle: false }, render: (UserAgent: any) => getClippedText(UserAgent, 20) }, { title: 'FCP', dataIndex: 'FCP', key: 'FCP', ellipsis: true, render: (FCP: any) => getClippedText(FCP.toString(), 9), sorter: (a: any, b: any) => a.FCP - b.FCP }, { title: 'TTFB', dataIndex: 'TTFB', key: 'TTFB', ellipsis: true, render: (TTFB: any) => getClippedText(TTFB.toString(), 9), sorter: (a: any, b: any) => a.TTFB - b.TTFB }, { title: 'DomLoad', dataIndex: 'DomLoad', key: 'DomLoad', ellipsis: true, render: (DomLoad: any) => getClippedText(DomLoad.toString(), 9), sorter: (a: any, b: any) => a.DomLoad - b.DomLoad }, { title: 'WindowLoad', dataIndex: 'WindowLoad', key: 'WindowLoad', ellipsis: true, render: (WindowLoad: any) => getClippedText(WindowLoad.toString(), 9), sorter: (a: any, b: any) => a.WindowLoad - b.WindowLoad }, { title: 'Time', dataIndex: 'createdAt', key: 'createdAt', render: (createdAt: any) => moment(createdAt).format('HH:mm:ss'), sorter: (a: any, b: any) => { const timestampA = moment(a.createdAt).format('X') const timestampB = moment(b.createdAt).format('X') return parseInt(timestampA) - parseInt(timestampB) } } ] return ( <> <Title level={2}>Metrics and Entries</Title> <Table rowKey="_id" className="table-striped-rows" columns={columns} expandable={{ expandedRowRender }} dataSource={metrics?.filter((item) => selectedUrls.includes(item.URL))} expandedRowKeys={expandedRowKeys} onExpand={onTableRowExpand} scroll={{ y: 400, x: 1024 }} tableLayout="auto" /> </> ) } export default EntriesWidget
hasantezcan/PerfAnalytics-Dashboard
src/factories/chartMetricFactory.tsx
<filename>src/factories/chartMetricFactory.tsx import faker from 'faker' import { ChartMetric } from '~/models/Metric' const { datatype: { number }, lorem: { word }, date: { past } } = faker function chartMetricFactory(times: number = 1): ChartMetric[] { return Array.from({ length: times }, (index: number) => { return { url: word(), data: Array.from({ length: times }, () => { return { value: number(), time: new Date(past()).getTime() } }) } }) } export { chartMetricFactory }
hasantezcan/PerfAnalytics-Dashboard
src/factories/urlMetricFactory.tsx
import faker from 'faker' import { MetricByURL } from '~/models/Metric' const { datatype: { number }, lorem: { word }, date: { past } } = faker function urlMetricFactory(times: number = 1): MetricByURL[] { return Array.from({ length: times }, (index: number) => { return { URL: word(), TTFB: Array.from({ length: times }, () => { return { value: number(), time: new Date(past()) } }), FCP: Array.from({ length: times }, () => { return { value: number(), time: new Date(past()) } }), DomLoad: Array.from({ length: times }, () => { return { value: number(), time: new Date(past()) } }), WindowLoad: Array.from({ length: times }, () => { return { value: number(), time: new Date(past()) } }) } }) } export { urlMetricFactory }
hasantezcan/PerfAnalytics-Dashboard
src/components/EntriesWidget/index.spec.tsx
import { render, fireEvent, waitFor } from '@testing-library/react' import EntriesWidget from '.' import { Metric } from '~/models/Metric' import { metricFactory } from '../../factories/metricfactory' describe('EntriesWidget specs', () => { let metrics: Metric[] let chosenUrls: string[] beforeEach(() => { metrics = metricFactory(2) chosenUrls = [] }) it('Should render', () => { const { container, getByText } = render( <EntriesWidget metrics={metrics} selectedUrls={chosenUrls} /> ) expect(getByText('Metrics and Entries')).toBeInTheDocument() expect(container.getElementsByClassName('ant-table-wrapper').length).toBe(1) }) it('Should show empty data component when data not exist', () => { const { container } = render( <EntriesWidget metrics={[]} selectedUrls={chosenUrls} /> ) expect(container.getElementsByClassName('ant-empty').length).toBe(1) }) it('Should expend and show data', () => { chosenUrls = ['hasantezcan.dev'] metrics[0].URL = 'hasantezcan.dev' metrics[1].URL = 'github.com/hasantezcan' const { container, getAllByLabelText } = render( <EntriesWidget metrics={metrics} selectedUrls={chosenUrls} /> ) fireEvent.click(getAllByLabelText('Expand row')[0]) expect( container.getElementsByClassName( 'ant-table-expanded-row ant-table-expanded-row-level-1' ).length ).toBe(1) }) describe('Sort specs', () => { it('Should sort by URL', () => { chosenUrls = ['hasantezcan.dev', 'github.com/hasantezcan'] metrics[0].URL = 'github.com/hasantezcan' metrics[1].URL = 'hasantezcan.dev' const { container, getByText } = render( <EntriesWidget metrics={metrics} selectedUrls={chosenUrls} /> ) fireEvent.click(getByText('Url')) expect( container .getElementsByClassName('ant-table-row ant-table-row-level-0')[0] .getAttribute('data-row-key') ).toEqual(metrics[1]._id) }) it('Should sort by FCP', () => { chosenUrls = ['hasantezcan.dev', 'github.com/hasantezcan'] metrics[0].FCP = 500 metrics[1].FCP = 100 const { container, getByText } = render( <EntriesWidget metrics={metrics} selectedUrls={chosenUrls} /> ) fireEvent.click(getByText('FCP')) waitFor(() => { expect( container .getElementsByClassName('ant-table-row ant-table-row-level-0')[0] .getAttribute('data-row-key') ).toEqual(metrics[1]._id) }) }) it('Should sort by TTFB', () => { chosenUrls = ['hasantezcan.dev', 'github.com/hasantezcan'] metrics[0].TTFB = 500 metrics[1].TTFB = 100 const { container, getByText } = render( <EntriesWidget metrics={metrics} selectedUrls={chosenUrls} /> ) fireEvent.click(getByText('TTFB')) waitFor(() => { expect( container .getElementsByClassName('ant-table-row ant-table-row-level-0')[0] .getAttribute('data-row-key') ).toEqual(metrics[1]._id) }) }) it('Should sort by DomLoad', () => { chosenUrls = ['hasantezcan.dev', 'github.com/hasantezcan'] metrics[0].DomLoad = 500 metrics[1].DomLoad = 100 const { container, getByText } = render( <EntriesWidget metrics={metrics} selectedUrls={chosenUrls} /> ) fireEvent.click(getByText('DomLoad')) waitFor(() => { expect( container .getElementsByClassName('ant-table-row ant-table-row-level-0')[0] .getAttribute('data-row-key') ).toEqual(metrics[1]._id) }) }) it('Should sort by WindowLoad', () => { chosenUrls = ['hasantezcan.dev', 'github.com/hasantezcan'] metrics[0].WindowLoad = 500 metrics[1].WindowLoad = 100 const { container, getByText } = render( <EntriesWidget metrics={metrics} selectedUrls={chosenUrls} /> ) fireEvent.click(getByText('WindowLoad')) waitFor(() => { expect( container .getElementsByClassName('ant-table-row ant-table-row-level-0')[0] .getAttribute('data-row-key') ).toEqual(metrics[1]._id) }) }) it('Should sort by Time', () => { chosenUrls = ['hasantezcan.dev', 'github.com/hasantezcan'] const { container, getByText } = render( <EntriesWidget metrics={metrics} selectedUrls={chosenUrls} /> ) fireEvent.click(getByText('Time')) fireEvent.click(getByText('Time')) waitFor(() => { expect( container .getElementsByClassName('ant-table-row ant-table-row-level-0')[0] .getAttribute('data-row-key') ).toEqual(metrics[1]._id) }) }) }) })
supersoniko/aws-secrets-dotenv
src/__tests__/secrets-manager.ts
<reponame>supersoniko/aws-secrets-dotenv import SecretsManager from 'aws-sdk/clients/secretsmanager'; import fs from 'fs'; import secretsManagerFunctionFactoryImpl from '../secrets-manager'; import { Config, SecretManagerFunctionFactory } from '../types'; describe('SecretsManagerFunctionFactory', (): void => { let secretsManagerFunctionFactory: SecretManagerFunctionFactory; let secretManager: SecretsManager; const config: Config = { Name: 'Beep', Description: 'Boop', SecretString: JSON.stringify({ beep: 'boop' }) }; beforeEach(async () => { secretManager = new SecretsManager(); secretsManagerFunctionFactory = secretsManagerFunctionFactoryImpl( secretManager, fs, config ); }); describe('createOrUpdateSecret', (): void => { it('successfully calls createSecret once', async (): Promise<void> => { // Prepare const secretMock = jest.fn(); const { createOrUpdateSecret } = secretsManagerFunctionFactory; jest.spyOn(secretManager, 'createSecret').mockImplementation(() => { return { promise: secretMock } as any; }); // Execute await createOrUpdateSecret(); // Assert expect(secretMock).toHaveBeenCalled(); expect(secretMock.mock.calls.length).toBe(1); }); }); describe('createLocalEnvironment', (): void => { it('successfully calls getSecretValue once', async (): Promise<void> => { // Prepare const { createLocalEnvironment } = secretsManagerFunctionFactory; const secretMock = jest .fn() .mockReturnValue( Promise.resolve({ SecretString: JSON.stringify({ beep: 'boop' }) }) ); jest.spyOn(secretManager, 'getSecretValue').mockImplementation(() => { return { promise: secretMock } as any; }); jest .spyOn(fs, 'writeFileSync') .mockImplementation((_fileName, _fileContent) => { return `${_fileContent} ${_fileName}`; }); // Execute await createLocalEnvironment(); // Assert expect(secretMock).toHaveBeenCalled(); expect(secretMock.mock.calls.length).toBe(1); }); it('succeeds without an error thrown', async (): Promise<void> => { // Prepare let errorThrown = false; const secretMock = jest .fn() .mockReturnValue( Promise.resolve({ SecretString: JSON.stringify({ beep: 'boop' }) }) ); const { createLocalEnvironment } = secretsManagerFunctionFactory; jest.spyOn(secretManager, 'getSecretValue').mockImplementation(() => { return { promise: secretMock } as any; }); jest .spyOn(fs, 'writeFileSync') .mockImplementation((_fileName, _fileContent) => { return `${_fileContent} ${_fileName}`; }); // Execute try { await createLocalEnvironment(); } catch (error) { errorThrown = true; } // Assert expect(secretMock).toHaveBeenCalled(); expect(secretMock.mock.calls.length).toBe(1); expect(errorThrown).toBe(false); }); it('fails with correct error message', async (): Promise<void> => { // Prepare let errorMessage; const secretMock = jest .fn() .mockReturnValue(Promise.resolve({ SecretString: undefined })); const { createLocalEnvironment } = secretsManagerFunctionFactory; jest.spyOn(secretManager, 'getSecretValue').mockImplementation(() => { return { promise: secretMock } as any; }); // Execute try { await createLocalEnvironment(); } catch (error) { errorMessage = error.message; } // Assert expect(secretMock).toHaveBeenCalled(); expect(secretMock.mock.calls.length).toBe(1); expect(errorMessage).toBe('No data in secret.'); }); it('successfully parses and writes .env', async (): Promise<void> => { let content; const { createLocalEnvironment } = secretsManagerFunctionFactory; const secretMock = jest .fn() .mockReturnValue( Promise.resolve({ SecretString: JSON.stringify({ beep: 'boop' }) }) ); jest.spyOn(secretManager, 'getSecretValue').mockImplementation(() => { return { promise: secretMock } as any; }); jest .spyOn(fs, 'writeFileSync') .mockImplementation((_fileName, fileContent) => { content = fileContent; }); // Execute await createLocalEnvironment(); // Assert expect(secretMock).toHaveBeenCalled(); expect(secretMock.mock.calls.length).toBe(1); expect(content).toBe('beep=boop \n'); }); }); });
supersoniko/aws-secrets-dotenv
src/types.ts
export interface Config { Name: string; Description: string; SecretString: string; } export interface SecretManagerFunctionFactory { createOrUpdateSecret: (stage?: string) => Promise<void>; createLocalEnvironment: (stage?: string) => Promise<void>; }
supersoniko/aws-secrets-dotenv
src/index.ts
#!/usr/bin/env node import AWS from 'aws-sdk'; import fs from 'fs'; AWS.config.update({ region: process.env.AWS_DEFAULT_REGION }); import secretsManagerFunctionFactory from './secrets-manager'; import getConfig from './get-config'; const secretsManager = new AWS.SecretsManager(); const config = getConfig('secrets'); export const { createLocalEnvironment, createOrUpdateSecret } = secretsManagerFunctionFactory(secretsManager, fs, config); export default secretsManagerFunctionFactory; export const cli = (args: string[]): void => { const command = args.slice(2)[0]; const stage = args.slice(2)[1]; switch (command) { case 'createOrUpdateSecret': createOrUpdateSecret(stage).catch(err => console.error('An error occured', err) ); break; case 'createLocalEnvironment': createLocalEnvironment(stage).catch(err => console.error('An error occured', err) ); break; default: console.log( 'Please read the README at https://github.com/supersoniko/aws-secrets-dotenv' ); } };
WrathChaos/react-native-dynamic-rate
example/App.style.ts
import { ViewStyle, TextStyle, StyleSheet, Dimensions } from "react-native"; const { width: ScreenWidth } = Dimensions.get("window"); interface Style { container: ViewStyle; titleContainer: ViewStyle; titleTextStyle: TextStyle; cardsExampleContainer: ViewStyle; cardStyle: ViewStyle; dividerStyle: ViewStyle; cardTitleTextStyle: TextStyle; cardValueTextStyle: TextStyle; } export default StyleSheet.create<Style>({ container: { marginTop: "30%", alignItems: "center", justifyContent: "center" }, titleContainer: { marginLeft: 32, marginRight: 32 }, titleTextStyle: { fontSize: 40, color: "#290404", fontWeight: "bold", textAlign: "center" }, cardsExampleContainer: { marginTop: 32 }, cardStyle: { padding: 16, margin: 16, borderRadius: 8, width: ScreenWidth * 0.8, backgroundColor: "#fdfdfd", shadowRadius: 8, shadowOpacity: 0.3, shadowColor: "#757575", shadowOffset: { width: 0, height: 3 } }, dividerStyle: { height: 1, width: "100%", marginTop: 16, marginBottom: 16, backgroundColor: "#ccc" }, cardTitleTextStyle: { color: "gray" }, cardValueTextStyle: { fontWeight: "600", color: "#290404" } });
WrathChaos/react-native-dynamic-rate
example/App.tsx
<gh_stars>0 import * as React from "react"; import { View, Text, StatusBar, SafeAreaView } from "react-native"; import DynamicRate from "./lib/DynamicRate"; /** * ? Local Imports */ import styles from "./App.style"; interface IProps {} interface IState { rate: number; value: number; } class App extends React.Component<IProps, IState> { numberFormat = (value) => new Intl.NumberFormat("tr", {}).format(value); renderExampleCard = (value, rate) => ( <View style={styles.cardStyle}> <DynamicRate value={value} rate={rate} /> <View style={styles.dividerStyle} /> <View> <Text style={styles.cardTitleTextStyle}> <Text style={styles.cardValueTextStyle}>Starting Value:</Text>{" "} {this.numberFormat(value)} </Text> <Text style={styles.cardTitleTextStyle}> <Text style={styles.cardValueTextStyle}>Change Rate Per Hour:</Text>{" "} {this.numberFormat(rate)} </Text> </View> </View> ); render() { return ( <> <StatusBar barStyle="dark-content" /> <SafeAreaView> <View style={styles.container}> <View style={styles.titleContainer}> <Text style={styles.titleTextStyle}> React Native Dynamic Rate </Text> </View> <View style={styles.cardsExampleContainer}> {this.renderExampleCard(150000, 3600)} {this.renderExampleCard(501394014, 50300)} {this.renderExampleCard(105, 305)} {this.renderExampleCard(0, 5014)} </View> </View> </SafeAreaView> </> ); } } export default App;
vv13/leetcode-problems-crawler
src/index.ts
#!/usr/bin/env node import program from 'commander' import path from 'path' import request from 'superagent' import config from './config' import { IPair } from './types' import { writeDirectory, writeInformation, writeQuestion, writeSolution } from './utils' program .name('leetcode-problem-crawler') .option('-r, --rule <string>', 'crawling rule, eg1: 1-10, eg2: 1,2,3, eg3: 5') .option( '-i, --i18n <string>', 'currently support en and cn, default is en.', 'en' ) .option( '-l, --lang <string>', 'generate code snippet with language, default is python3.', 'python3' ) program.parse(process.argv) const rule = program.rule as string if (rule) { const ids = [] if (rule.includes('-')) { const [start, end] = rule.split('-').map(idnumber => Number(idnumber)) for (let i = start; i <= end; i++) { ids.push(i) } } else if (rule.includes(',')) { ids.push(...rule.split(',').map(Number)) } else { ids.push(Number(rule)) } main(ids, program.lang, program.i18n) } else { program.help() } async function main(ids: number[], langSlug: string, i18n: 'cn' | 'en') { const { domain } = config[i18n] const problems = await getAllProblems(domain) problems.stat_status_pairs.forEach(async (pair: IPair) => { const { difficulty: { level }, stat: { frontend_question_id, question__title_slug } } = pair if (!ids.includes(Number(frontend_question_id))) { return } const question = await getQuestion(domain, question__title_slug) const dirname = path.join( process.cwd(), `${frontend_question_id .toString() .padStart(3, '0')}.${question__title_slug}` ) const questionConfig = { title: i18n === 'en' ? question.title : question.translatedTitle, content: i18n === 'en' ? question.content : question.translatedContent, questionFrontendId: question.questionFrontendId, titleSlug: question.titleSlug, hints: question.hints, domain, i18n } writeDirectory(dirname) writeQuestion(dirname, questionConfig) if (langSlug) { const { codeSnippets } = question const snippet = codeSnippets.find( (s: { langSlug: string }) => s.langSlug === langSlug ) if (!snippet) { return } writeSolution(dirname, langSlug, snippet.code) } writeInformation(dirname, { question, difficulty: config.levelMap[level] }) }) } async function getAllProblems(domain: string) { const { text } = await request.get(`${domain}/api/problems/all/`) return JSON.parse(text) } async function getQuestion(domain: string, titleSlug: string) { const { body: { data: { question } } } = await request .post(`${domain}/graphql`) .send(config.questionDataQL(titleSlug)) return question }
vv13/leetcode-problems-crawler
src/config.ts
<reponame>vv13/leetcode-problems-crawler import path from 'path' export default { cn: { domain: 'https://leetcode-cn.com' }, en: { domain: 'https://leetcode.com' }, DEFAULT_DIRNAME: 'problems', langSlugMap: { csharp: '.cs', java: '.java', javascript: '.js', php: '.php', python: '.py', python3: '.py' }, levelMap: { 1: 'easy', 2: 'medium', 3: 'hard' }, questionDataQL: (titleSlug: any) => ({ operationName: 'questionData', query: ` query questionData($titleSlug: String!) { question(titleSlug: $titleSlug) { translatedTitle translatedContent content similarQuestions stats hints title titleSlug questionFrontendId codeSnippets { lang langSlug code __typename } } } `, variables: { titleSlug } }) }
vv13/leetcode-problems-crawler
src/types.ts
export interface IPair { difficulty: { level: number }, stat: { frontend_question_id: number, question__title_slug: string } }
vv13/leetcode-problems-crawler
src/utils.ts
import fs from 'fs' import path from 'path' import config from './config' export function writeDirectory(dirname: string) { if (!fs.existsSync(dirname)) { fs.mkdirSync(dirname, { recursive: true }) } } export function writeQuestion(dirname: string, questionConfig: any) { const filePath = path.join( dirname, questionConfig.i18n === 'cn' ? 'README_CN.md' : 'README.md' ) // tslint:disable-next-line: no-console console.log('created: ' + filePath) let fileContent = `## [${questionConfig.questionFrontendId}. ${questionConfig.title}](${questionConfig.domain}/problems/${questionConfig.titleSlug}/)\n` + questionConfig.content if (questionConfig.hints && questionConfig.hints.length) { fileContent += '\n\n## Hints\n' questionConfig.hints.forEach((hint: string, index: number) => { fileContent += `${index + 1}. ${hint}\n` }) } fileContent += fs.writeFileSync(filePath, fileContent) } export function writeSolution(dirname: string, langSlug: string, code: any) { const filePath = path.join(dirname, `solution${config.langSlugMap[langSlug]}`) if (!fs.existsSync(filePath)) { fs.writeFileSync(filePath, code) } } export function writeInformation( dirname: string, { question, difficulty }: any ) { const { similarQuestions } = question const data = { difficulty, similarQuestions: JSON.parse(similarQuestions) } const filePath = path.join(dirname, `information.json`) if (!fs.existsSync(filePath)) { fs.writeFileSync(filePath, JSON.stringify(data, undefined, 4)) } else { let jsonData = JSON.parse(fs.readFileSync(filePath, 'utf8')) jsonData = { ...jsonData, ...data } fs.writeFileSync(filePath, JSON.stringify(jsonData, undefined, 4)) } }
markylaing/nauth0
packages/nauth0/src/server/index.ts
import { NextApiHandler, NextApiRequest } from 'next'; import { GetSessionOpts, NAuth0Client } from '../client'; import { NAuth0Options } from './config'; import { Session } from '../lib'; import routes from './routes'; import { getSessionFromReq } from './session'; class ServerNAuth0Client implements NAuth0Client { constructor(private readonly opts: NAuth0Options) {} private getActionFromRequest(req: NextApiRequest): string { return req.query.auth as string; } handler(): NextApiHandler { const apiHandler: NextApiHandler = async (req, res) => { const action = this.getActionFromRequest(req); const handler = routes(action); await handler(req, res, this.opts); }; return apiHandler; } getSession(req: GetSessionOpts): Promise<Session | null> { return getSessionFromReq(req, this.opts); } } export default ServerNAuth0Client; export * from './config';
markylaing/nauth0
packages/nauth0/src/browser/useSession.ts
import { useContext, useEffect, useState } from 'react'; import { Session } from '../lib'; import { SessionContext } from './SessionProvider'; import fetch from 'unfetch'; export const useSession = (): [Session, boolean] => { const ssrSession = useContext(SessionContext); if (ssrSession) { return [ssrSession, false]; } return _useSessionHook(); }; const _useSessionHook = (): [Session, boolean] => { const [session, setSession] = useState<Session>({}); const [isLoading, setIsLoading] = useState(true); const getSession = async () => { setIsLoading(true); const res = await fetch('/api/auth/session'); if (res.ok) { const sessionBody = await res.json(); setSession(sessionBody); } else { setSession({}); } setIsLoading(false); }; useEffect(() => { getSession(); }, []); return [session, isLoading]; };
markylaing/nauth0
packages/nauth0/src/index.browser.ts
<reponame>markylaing/nauth0<filename>packages/nauth0/src/index.browser.ts import BrowserNAuth0Client from './browser'; import { NAuth0Client } from './client'; export default (): NAuth0Client => { return new BrowserNAuth0Client(); }; export * from './browser'; export * from './lib';
markylaing/nauth0
packages/nauth0/src/server/routes/session.ts
<reponame>markylaing/nauth0<filename>packages/nauth0/src/server/routes/session.ts import { NAuth0ApiRoute } from './route'; import { getSessionFromReq } from '../../server/session'; export const sessionRoute: NAuth0ApiRoute = async (req, res, opts) => { const session = await getSessionFromReq({ req }, opts); if (!session) { res.status(401).end(); return; } res.json(session); };
markylaing/nauth0
packages/nauth0/src/server/routes/login.ts
<gh_stars>0 import { NAuth0ApiRoute } from './route'; import { createClient, createState } from '../oidc'; import { setCookie } from 'nookies'; import { stateCookie } from '../cookies'; export const loginRoute: NAuth0ApiRoute = async (req, res, opts) => { const client = await createClient(opts); const state = createState(); const authorizationUrl = client.authorizationUrl({ redirect_uri: opts.redirectUri, scope: opts.scope, response_type: 'code', audience: opts.audience, state, }); setCookie({ res }, stateCookie, state, { maxAge: 60 * 60, httpOnly: true, }); res .writeHead(302, { Location: authorizationUrl, }) .end(); };
markylaing/nauth0
packages/nauth0/src/server/routes/logout.ts
import { destroyCookie } from 'nookies'; import { sessionCookie, stateCookie } from '../cookies'; import { NAuth0ApiRoute } from './route'; export const logoutRoute: NAuth0ApiRoute = async (req, res, opts) => { // TODO: This is very auth0 specific. If we want to make this work with any OIDC provider then it needs to change to use the end_session_url from .well-known const endSessionUrl = `https://${opts.domain}/v2/logout?client_id=${ opts.clientId }&returnTo=${encodeURIComponent(opts.logoutRedirectUri)}`; destroyCookie({ res }, stateCookie); destroyCookie({ res }, sessionCookie, { path: '/', }); res .writeHead(302, { Location: endSessionUrl, }) .end(); };
markylaing/nauth0
example/cypress/integration/login.spec.ts
<gh_stars>1-10 describe('Login', () => { beforeEach(() => { cy.clearCookies(); }); it('sets the state cookie', () => { cy.request('api/auth/login'); cy.getCookie('nauth0:state').should('exist'); }); });
markylaing/nauth0
packages/nauth0/src/lib/session.ts
<filename>packages/nauth0/src/lib/session.ts import { User } from './user'; export interface Session { user?: User; accessToken?: string; }
markylaing/nauth0
example/pages/api/auth/[auth].ts
import nauth0 from 'lib/nauth0'; export default nauth0.handler();
markylaing/nauth0
packages/nauth0/src/browser/index.ts
import { Session } from '../lib'; import { NAuth0Client } from '../client'; import { NextApiHandler } from 'next'; class BrowserNAuth0Client implements NAuth0Client { handler(): NextApiHandler { throw new Error('Handler only implemented for the server'); } getSession(): Promise<Session> { throw new Error('Method not implemented.'); } } export default BrowserNAuth0Client; export * from './SessionProvider'; export * from './useSession';
markylaing/nauth0
packages/nauth0/src/server/routes/index.ts
<filename>packages/nauth0/src/server/routes/index.ts import { callbackRoute } from './callback'; import { loginRoute } from './login'; import { logoutRoute } from './logout'; import { notFoundRoute } from './notFound'; import { NAuth0ApiRoute } from './route'; import { sessionRoute } from './session'; export default (action: string): NAuth0ApiRoute => { switch (action) { case 'login': return loginRoute; case 'callback': return callbackRoute; case 'logout': return logoutRoute; case 'session': return sessionRoute; default: return notFoundRoute; } };
markylaing/nauth0
example/pages/_app.tsx
import React from 'react'; import type { AppProps } from 'next/app'; import { SessionProvider } from 'nauth0'; function App({ Component, pageProps }: AppProps): JSX.Element { return ( <SessionProvider value={pageProps.session}> <Component {...pageProps} /> </SessionProvider> ); } export default App;
markylaing/nauth0
example/pages/index.tsx
<gh_stars>1-10 import React from 'react'; import { useSession } from 'nauth0'; const Home: React.FC = () => { const [session, isLoading] = useSession(); if (isLoading) { return <div>Loading...</div>; } const { user } = session; if (!user) { return <a href="/api/auth/login">Login</a>; } return ( <code> <pre>{JSON.stringify(user)}</pre> </code> ); }; export default Home;
markylaing/nauth0
packages/nauth0/src/browser/SessionProvider.ts
<gh_stars>1-10 import React from 'react'; import { Session } from '../lib'; export const SessionContext = React.createContext<Session | undefined>( undefined ); export const SessionProvider = SessionContext.Provider;
markylaing/nauth0
packages/nauth0/src/server/routes/callback.ts
import { NAuth0ApiRoute } from './route'; import { parseCookies, setCookie } from 'nookies'; import { sessionCookie, stateCookie } from '../cookies'; import { createClient } from '../oidc'; import { encodeSession, sessionFromTokenSet } from '../session'; export const callbackRoute: NAuth0ApiRoute = async (req, res, opts) => { const cookies = parseCookies({ req }); const state = cookies[stateCookie]; if (typeof state === undefined) { throw new Error('Missing state cookie'); } const client = await createClient(opts); const params = client.callbackParams(req); const tokenSet = await client.callback(opts.redirectUri, params, { state, }); const session = sessionFromTokenSet(tokenSet); const encodedSession = await encodeSession(session, opts); const eightHoursInSeconds = 60 * 60 * 8; // TODO: Handle optional config better setCookie({ res }, sessionCookie, encodedSession, { maxAge: opts.session.cookieLifetime ?? eightHoursInSeconds, httpOnly: true, path: '/', }); res .writeHead(302, { Location: '/', // TODO: Get the redirectUri }) .end(); };
markylaing/nauth0
packages/nauth0/src/server/routes/notFound.ts
import { NAuth0ApiRoute } from './route'; export const notFoundRoute: NAuth0ApiRoute = (req, res) => { res.status(404).end(); };
markylaing/nauth0
example/lib/nauth0.ts
<filename>example/lib/nauth0.ts import nauth0 from 'nauth0'; export default nauth0({ domain: process.env.AUTH0_DOMAIN, clientId: process.env.AUTH0_CLIENT_ID, clientSecret: process.env.AUTH0_CLIENT_SECRET, redirectUri: 'http://localhost:3000/api/auth/callback', logoutRedirectUri: 'http://localhost:3000/', scope: 'openid profile', session: { cookieSecret: '<PASSWORD>', }, });
markylaing/nauth0
packages/nauth0/src/index.ts
<filename>packages/nauth0/src/index.ts<gh_stars>0 import BrowserNAuth0Client from './browser'; import { NAuth0Client } from './client'; import ServerNAuth0Client, { NAuth0Options } from './server'; export default (opts: NAuth0Options): NAuth0Client => { const isBrowser = typeof window !== 'undefined'; if (isBrowser) { return new BrowserNAuth0Client(); } return new ServerNAuth0Client(opts); }; export * from './browser'; export * from './server'; export * from './lib';
markylaing/nauth0
packages/nauth0/src/server/session.ts
import { TokenSet } from 'openid-client'; import { NAuth0Options } from './config'; import { Session } from '../lib'; import SignJWT from 'jose/jwt/sign'; import jwtVerify from 'jose/jwt/verify'; import { parseCookies } from 'nookies'; import { sessionCookie } from './cookies'; import { GetSessionOpts } from '../client'; export interface Token { session: Session; } export const sessionFromTokenSet = (tokenSet: TokenSet): Session => { const claims = tokenSet.claims(); return { user: { id: claims.sub, }, accessToken: tokenSet.access_token, }; }; const encodeSecret = (secret: string): Uint8Array => { return new TextEncoder().encode(secret); }; export const encodeSession = async ( session: Session, opts: NAuth0Options ): Promise<string> => { const secret = encodeSecret(opts.session.cookieSecret); return await new SignJWT({ session }) .setProtectedHeader({ alg: 'HS256' }) .setIssuedAt() .sign(secret); }; export const getSessionFromReq = async ( req: GetSessionOpts, opts: NAuth0Options ): Promise<Session | null> => { const cookies = parseCookies(req); const rawToken = cookies[sessionCookie]; if (typeof rawToken === 'undefined') { return null; } const secret = encodeSecret(opts.session.cookieSecret); const { payload } = await jwtVerify(rawToken, secret); return payload.session; };
markylaing/nauth0
packages/nauth0/src/server/oidc.ts
<gh_stars>0 import base64url from 'base64url'; import { randomBytes } from 'crypto'; import { Client, Issuer } from 'openid-client'; import { NAuth0Options } from './config'; export const createState = ( stateObject: Record<string, unknown> = {} ): string => { stateObject.nonce = createNonce(); return encodeState(stateObject); }; export const createNonce = (): string => randomBytes(16).toString('hex'); export const encodeState = (stateObject: Record<string, unknown>): string => base64url.encode(JSON.stringify(stateObject)); export const decodeState = (stateValue: string): Record<string, unknown> => JSON.parse(base64url.decode(stateValue)); export const createClient = async ({ domain, clientId, clientSecret, redirectUri, }: NAuth0Options): Promise<Client> => { const issuer = await Issuer.discover(`https://${domain}/`); const client = new issuer.Client({ client_id: clientId, client_secret: clientSecret, redirect_uris: [redirectUri], response_types: ['code'], }); return client; };
markylaing/nauth0
packages/nauth0/src/server/config.ts
export interface NAuth0Options { domain: string; clientId: string; clientSecret: string; scope: string; redirectUri: string; logoutRedirectUri: string; audience?: string; session: { cookieSecret: string; cookieLifetime?: number; }; }
markylaing/nauth0
packages/nauth0/src/server/cookies.ts
export const stateCookie = 'nauth0:state'; export const sessionCookie = 'nauth0:session';
markylaing/nauth0
packages/nauth0/src/client.ts
import { NextApiHandler, NextApiRequest, NextPageContext } from 'next'; import { Session } from './lib'; export type GetSessionOpts = | Pick<NextPageContext, 'req'> | { req: NextApiRequest; }; export interface NAuth0Client { handler(): NextApiHandler; getSession(req: GetSessionOpts): Promise<Session | null>; }
markylaing/nauth0
example/pages/ssr.tsx
<gh_stars>1-10 import React from 'react'; import { useSession } from 'nauth0'; import { GetServerSideProps } from 'next'; import nauth0 from 'lib/nauth0'; const Home: React.FC = () => { const [session] = useSession(); const { user } = session; return ( <code> <pre>{JSON.stringify(user)}</pre> </code> ); }; export const getServerSideProps: GetServerSideProps = async (ctx) => { const session = await nauth0.getSession(ctx); if (!session) { return { redirect: { destination: '/', permanent: false, }, }; } return { props: { session, }, }; }; export default Home;
markylaing/nauth0
packages/nauth0/src/browser/useSession.test.tsx
import React from 'react'; import { render, screen, waitFor } from '@testing-library/react'; import { useSession } from './useSession'; import { SessionProvider } from './SessionProvider'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import { Session } from '../lib'; import '@testing-library/jest-dom'; // TODO: How can I import the type definitions for extend-expect automatically? const App: React.FC = () => { const [session, isLoading] = useSession(); if (isLoading) return <div>Loading...</div>; return <div>{session.user?.id}</div>; }; describe('useSession', () => { const id = 'user-id'; const server = setupServer( rest.get('/api/auth/session', (req, res, ctx) => { const session: Session = { user: { id, }, }; return res(ctx.json(session)); }) ); beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); it('works when SessionProvider is available', () => { render( <SessionProvider value={{ user: { id, }, }} > <App /> </SessionProvider> ); expect(screen.getByText(id)).toBeInTheDocument(); }); it('works when SessionContext is unavailable', async () => { render(<App />); expect(screen.getByText('Loading...')).toBeInTheDocument(); await waitFor(() => screen.getByText(id)); }); });
markylaing/nauth0
packages/nauth0/src/lib/index.ts
export * from './session'; export * from './user';
markylaing/nauth0
packages/nauth0/src/server/routes/route.ts
<reponame>markylaing/nauth0<filename>packages/nauth0/src/server/routes/route.ts<gh_stars>0 import { NextApiRequest, NextApiResponse } from 'next'; import { NAuth0Options } from '../config'; export type NAuth0ApiRoute = ( req: NextApiRequest, res: NextApiResponse, cfg: NAuth0Options ) => void | Promise<void>;
bhavyaw/connected
src/connected.ts
<reponame>bhavyaw/connected import PubSub from "./pubSub" class Connected extends PubSub { constructor() { super() console.log(this) } } new Connected()
bhavyaw/connected
src/pubSub.ts
<reponame>bhavyaw/connected export default class PubSub { _events = {} constructor() { console.log("inside pubsub constructor") } }
aequasi/fluent-behavior-tree
src/BehaviorTreeBuilder.ts
<reponame>aequasi/fluent-behavior-tree import Stack from "ts-data.stack"; import BehaviorTreeStatus from "./BehaviorTreeStatus"; import BehaviorTreeError from "./Error/BehaviorTreeError"; import Errors from "./Error/Errors"; import ActionNode from "./Node/ActionNode"; import BehaviorTreeNodeInterface from "./Node/BehaviorTreeNodeInterface"; import InverterNode from "./Node/InverterNode"; import ParallelNode from "./Node/ParallelNode"; import ParentBehaviorTreeNodeInterface from "./Node/ParentBehaviorTreeNodeInterface"; import SelectorNode from "./Node/SelectorNode"; import SequenceNode from "./Node/SequenceNode"; import StateData from "./StateData"; export default class BehaviorTreeBuilder { /** * Last node created */ private curNode?: BehaviorTreeNodeInterface; /** * Stack node nodes that we are build via the fluent API. * * @type {Stack<ParentBehaviorTreeNodeInterface>} */ private parentNodeStack: Stack<ParentBehaviorTreeNodeInterface> = new Stack<ParentBehaviorTreeNodeInterface>(); /** * Create an action node. * * @param {string} name * @param {(state: StateData) => BehaviorTreeStatus} fn * @returns {BehaviorTreeBuilder} */ public do(name: string, fn: (state: StateData) => Promise<BehaviorTreeStatus>): BehaviorTreeBuilder { if (this.parentNodeStack.isEmpty()) { throw new BehaviorTreeError(Errors.UNNESTED_ACTION_NODE); } const actionNode = new ActionNode(name, fn); this.parentNodeStack.peek().addChild(actionNode); return this; } /** * Like an action node... but the function can return true/false and is mapped to success/failure. * * @param {string} name * @param {(state: StateData) => boolean} fn * @returns {BehaviorTreeBuilder} */ public condition(name: string, fn: (state: StateData) => Promise<boolean>): BehaviorTreeBuilder { return this.do(name, async (t) => await fn(t) ? BehaviorTreeStatus.Success : BehaviorTreeStatus.Failure); } /** * Create an inverter node that inverts the success/failure of its children. * * @param {string} name * @returns {BehaviorTreeBuilder} */ public inverter(name: string): BehaviorTreeBuilder { return this.addParentNode(new InverterNode(name)); } /** * Create a sequence node. * * @param {string} name * @param {boolean} keepState * @returns {BehaviorTreeBuilder} */ public sequence(name: string, keepState: boolean = true): BehaviorTreeBuilder { return this.addParentNode(new SequenceNode(name, keepState)); } /** * Create a parallel node. * * @param {string} name * @param {number} requiredToFail * @param {number} requiredToSucceed * @returns {BehaviorTreeBuilder} */ public parallel(name: string, requiredToFail: number, requiredToSucceed: number): BehaviorTreeBuilder { return this.addParentNode(new ParallelNode(name, requiredToFail, requiredToSucceed)); } /** * Create a selector node. * * @param {string} name * @param {boolean} keepState * @returns {BehaviorTreeBuilder} */ public selector(name: string, keepState: boolean = true): BehaviorTreeBuilder { return this.addParentNode(new SelectorNode(name, keepState)); } /** * Splice a sub tree into the parent tree. * * @param {BehaviorTreeNodeInterface} subTree * @returns {BehaviorTreeBuilder} */ public splice(subTree: BehaviorTreeNodeInterface): BehaviorTreeBuilder { if (this.parentNodeStack.isEmpty()) { throw new BehaviorTreeError(Errors.SPLICE_UNNESTED_TREE); } this.parentNodeStack.peek().addChild(subTree); return this; } /** * Build the actual tree * @returns {BehaviorTreeNodeInterface} */ public build(): BehaviorTreeNodeInterface { if (!this.curNode) { throw new BehaviorTreeError(Errors.NO_NODES); } return this.curNode; } /** * Ends a sequence of children. * * @returns {BehaviorTreeBuilder} */ public end(): BehaviorTreeBuilder { this.curNode = this.parentNodeStack.pop(); return this; } /** * Adds the parent node to the parentNodeStack * * @param {ParentBehaviorTreeNodeInterface} node * @returns {BehaviorTreeBuilder} */ private addParentNode(node: ParentBehaviorTreeNodeInterface): BehaviorTreeBuilder { if (!this.parentNodeStack.isEmpty()) { this.parentNodeStack.peek().addChild(node); } this.parentNodeStack.push(node); return this; } }
aequasi/fluent-behavior-tree
test/Node/InverterNodeTest.ts
<gh_stars>10-100 import test from "ava"; import * as TypeMoq from "typemoq"; import StateData from "../../src/StateData"; import InverterNode from "../../src/Node/InverterNode"; import BehaviorTreeNodeInterface from "../../src/Node/BehaviorTreeNodeInterface"; import BehaviorTreeStatus from "../../src/BehaviorTreeStatus"; import BehaviorTreeError from "../../src/Error/BehaviorTreeError"; import Errors from "../../src/Error/Errors"; let testObject: InverterNode; test.beforeEach(() => { testObject = new InverterNode("some-node"); }); test.afterEach.always(() => { testObject = undefined; }); test("ticking with no child node throws error", async (assert) => { try { await testObject.tick(new StateData()); } catch (e) { assert.throws(() => {throw e}, BehaviorTreeError, "should have thrown"); assert.is(e.message, Errors.INVERTER_NO_CHILDREN); } }); test("inverts success of child node", async (assert) => { const state = new StateData(); const mockChildNode = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChildNode .setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Success)); testObject.addChild(mockChildNode.object); assert.is(BehaviorTreeStatus.Failure, await testObject.tick(state)); mockChildNode.verify((m) => m.tick(state), TypeMoq.Times.once()); }); test("inverts failure of child node", async (assert) => { const state = new StateData(); const mockChildNode = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChildNode .setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Failure)); testObject.addChild(mockChildNode.object); assert.is(BehaviorTreeStatus.Success, await testObject.tick(state)); mockChildNode.verify((m) => m.tick(state), TypeMoq.Times.once()); }); test("pass through running of child node", async (assert) => { const state = new StateData(); const mockChildNode = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChildNode .setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Running)); testObject.addChild(mockChildNode.object); assert.is(BehaviorTreeStatus.Running, await testObject.tick(state)); mockChildNode.verify((m) => m.tick(state), TypeMoq.Times.once()); }); test("adding more than a single child throws exception", async (assert) => { testObject.addChild(TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>() as any); const error = assert.throws( () => testObject.addChild(TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>() as any), BehaviorTreeError, ); assert.is(error.message, Errors.INVERTER_MULTIPLE_CHILDREN); });
aequasi/fluent-behavior-tree
src/index.ts
import BehaviorTreeBuilder from "./BehaviorTreeBuilder"; import BehaviorTreeStatus from "./BehaviorTreeStatus"; import BehaviorTreeErorr from "./Error/BehaviorTreeError"; import Errors from "./Error/Errors"; import ActionNode from "./Node/ActionNode"; import BehaviorTreeNodeInterface from "./Node/BehaviorTreeNodeInterface"; import InverterNode from "./Node/InverterNode"; import ParallelNode from "./Node/ParallelNode"; import ParentBehaviorTreeNodeInterface from "./Node/ParentBehaviorTreeNodeInterface"; import SelectorNode from "./Node/SelectorNode"; import SequenceNode from "./Node/SequenceNode"; import StateData from "./StateData"; export { BehaviorTreeBuilder, BehaviorTreeStatus, StateData, BehaviorTreeNodeInterface, ParentBehaviorTreeNodeInterface, ActionNode, InverterNode, ParallelNode, SelectorNode, SequenceNode, BehaviorTreeErorr, Errors, };
aequasi/fluent-behavior-tree
test/Node/SequenceNodeTest.ts
<filename>test/Node/SequenceNodeTest.ts import test from "ava"; import * as TypeMoq from "typemoq"; import StateData from "../../src/StateData"; import BehaviorTreeNodeInterface from "../../src/Node/BehaviorTreeNodeInterface"; import BehaviorTreeStatus from "../../src/BehaviorTreeStatus"; import SequenceNode from "../../src/Node/SequenceNode"; let testObject: SequenceNode; function init(keepState: boolean = false): void { testObject = new SequenceNode("some-sequence", keepState); } test("can run all children in order", async (assert) => { init(); const state = new StateData(); let callOrder = 0; const mockChild1 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild1.setup(async (m) => await m.tick(state)) .returns(() => { assert.is(1, ++callOrder); return Promise.resolve(BehaviorTreeStatus.Success) }); const mockChild2 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild2.setup(async (m) => await m.tick(state)) .returns(() => { assert.is(2, ++callOrder); return Promise.resolve(BehaviorTreeStatus.Success) }); testObject.addChild(mockChild1.object); testObject.addChild(mockChild2.object); assert.is(BehaviorTreeStatus.Success, await testObject.tick(state)); assert.is(2, callOrder); mockChild1.verify((m) => m.tick(state), TypeMoq.Times.once()); mockChild2.verify((m) => m.tick(state), TypeMoq.Times.once()); }); test("when first child is running, second child is supressed", async (assert) => { init(); const state = new StateData(); const mockChild1 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild1.setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Running)); const mockChild2 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); testObject.addChild(mockChild1.object); testObject.addChild(mockChild2.object); assert.is(BehaviorTreeStatus.Running, await testObject.tick(state)); mockChild1.verify((m) => m.tick(state), TypeMoq.Times.once()); mockChild2.verify((m) => m.tick(state), TypeMoq.Times.never()); }); test("when first child fails, then entire sequence fails", async (assert) => { init(); const state = new StateData(); const mockChild1 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild1.setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Failure)); const mockChild2 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); testObject.addChild(mockChild1.object); testObject.addChild(mockChild2.object); assert.is(BehaviorTreeStatus.Failure, await testObject.tick(state)); mockChild1.verify((m) => m.tick(state), TypeMoq.Times.once()); mockChild2.verify((m) => m.tick(state), TypeMoq.Times.never()); }); test("when second child fails, then entire sequence fails", async (assert) => { init(); const state = new StateData(); const mockChild1 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild1.setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Success)); const mockChild2 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild2.setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Failure)); testObject.addChild(mockChild1.object); testObject.addChild(mockChild2.object); assert.is(BehaviorTreeStatus.Failure, await testObject.tick(state)); mockChild1.verify((m) => m.tick(state), TypeMoq.Times.once()); mockChild2.verify((m) => m.tick(state), TypeMoq.Times.once()); }); test("only evaluates the current node", async (assert) => { init(true); const state = new StateData(); const mockChild1 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild1.setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Success)); const mockChild2 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild2.setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Running)); const mockChild3 = TypeMoq.Mock.ofType<BehaviorTreeNodeInterface>(); mockChild3.setup(async (m) => await m.tick(state)) .returns(() => Promise.resolve(BehaviorTreeStatus.Failure)); testObject.addChild(mockChild1.object); testObject.addChild(mockChild2.object); testObject.addChild(mockChild3.object); assert.is(BehaviorTreeStatus.Running, await testObject.tick(state)); assert.is(BehaviorTreeStatus.Running, await testObject.tick(state)); mockChild1.verify((m) => m.tick(state), TypeMoq.Times.once()); mockChild2.verify((m) => m.tick(state), TypeMoq.Times.exactly(2)); mockChild3.verify((m) => m.tick(state), TypeMoq.Times.never()); });
aequasi/fluent-behavior-tree
src/Node/ActionNode.ts
import BehaviorTreeStatus from "../BehaviorTreeStatus"; import BehaviorTreeError from "../Error/BehaviorTreeError"; import Errors from "../Error/Errors"; import StateData from "../StateData"; import BehaviorTreeNodeInterface from "./BehaviorTreeNodeInterface"; /** * A behavior tree leaf node for running an action * * @property {string} name - The name of the node * @property {(state: StateData) => BehaviorTreeStatus} fn - Function to invoke for the action. */ export default class ActionNode implements BehaviorTreeNodeInterface { public constructor( public readonly name: string, public readonly fn: (state: StateData) => Promise<BehaviorTreeStatus>, ) { } public async tick(state: StateData): Promise<BehaviorTreeStatus> { const result = await this.fn(state); if (!result) { throw new BehaviorTreeError(Errors.NO_RETURN_VALUE); } return result; } }
KidDevelopper/disc-11
src/events/WarnEvent.ts
import { BaseEvent } from "../structures/BaseEvent"; export class WarnEvent extends BaseEvent { public constructor(client: BaseEvent["client"]) { super(client, "warn"); } public execute(warn: string): void { this.client.logger.warn("CLIENT_WARN:", warn); } }
KidDevelopper/disc-11
src/events/DebugEvent.ts
import { BaseEvent } from "../structures/BaseEvent"; export class DebugEvent extends BaseEvent { public constructor(client: BaseEvent["client"]) { super(client, "debug"); } public execute(message: string): void { this.client.logger.debug(message); } }
KidDevelopper/disc-11
src/events/ChannelUpdateEvent.ts
import { BaseEvent } from "../structures/BaseEvent"; import { createEmbed } from "../utils/createEmbed"; import { entersState, VoiceConnectionStatus } from "@discordjs/voice"; import { GuildChannel, VoiceChannel } from "discord.js"; import i18n from "i18n"; export class ChannelUpdateEvent extends BaseEvent { public constructor(client: BaseEvent["client"]) { super(client, "channelUpdate"); } public async execute(oldChannel: GuildChannel, newChannel: GuildChannel): Promise<void> { if (!newChannel.guild.queue || (newChannel.id !== newChannel.guild.queue.connection?.joinConfig.channelId) || (oldChannel.type !== "GUILD_VOICE" && oldChannel.type !== "GUILD_STAGE_VOICE") || (newChannel.type !== "GUILD_VOICE" && newChannel.type !== "GUILD_STAGE_VOICE")) return; if ((oldChannel as VoiceChannel).rtcRegion !== (newChannel as VoiceChannel).rtcRegion) { const queue = newChannel.guild.queue; const msg = await queue.textChannel.send({ embeds: [createEmbed("info", i18n.__("events.channelUpdate.reconfigureConnection"))] }); queue.connection?.configureNetworking(); entersState(queue.connection!, VoiceConnectionStatus.Ready, 20000) .then(() => { void msg.edit({ embeds: [createEmbed("success", i18n.__("events.channelUpdate.connectionReconfigured"), true)] }); }) .catch(() => { queue.destroy(); this.client.logger.info(`${this.client.shard ? `[Shard #${this.client.shard.ids[0]}]` : ""} Unable to re-configure networking on ${newChannel.guild.name} voice channel, the queue was deleted.`); void msg.edit({ embeds: [createEmbed("error", i18n.__("events.channelUpdate.unableReconfigureConnection"), true)] }); }); } } }
KidDevelopper/disc-11
src/commands/music/VolumeCommand.ts
import { inVC, sameVC, validVC } from "../../utils/decorators/MusicUtil"; import { CommandContext } from "../../structures/CommandContext"; import { BaseCommand } from "../../structures/BaseCommand"; import { createEmbed } from "../../utils/createEmbed"; import i18n from "../../config"; import { AudioPlayerPlayingState } from "@discordjs/voice"; import { Message } from "discord.js"; export class VolumeCommand extends BaseCommand { public constructor(client: BaseCommand["client"]) { super(client, { aliases: ["vol"], description: i18n.__("commands.music.volume.description"), name: "volume", slash: { options: [ { description: i18n.__("commands.music.volume.slashDescription"), name: "volume", type: "NUMBER", required: false } ] }, usage: i18n.__("commands.music.volume.usage") }); } public execute(ctx: CommandContext): Promise<Message>|void { if (!inVC(ctx)) return; if (!validVC(ctx)) return; if (!sameVC(ctx)) return; const volume = Number(ctx.args[0] ?? ctx.options?.getNumber("volume", false)); const resVolume = (ctx.guild!.queue!.player!.state as AudioPlayerPlayingState).resource.volume!; if (isNaN(volume)) return ctx.reply({ embeds: [createEmbed("info", `🔊 **|** ${i18n.__mf("commands.music.volume.currentVolume", { volume: `\`${resVolume.volume * 100}\`` })}`).setFooter({ text: i18n.__("commands.music.volume.changeVolume") })] }); if (volume <= 0) return ctx.reply({ embeds: [createEmbed("warn", i18n.__mf("commands.music.volume.plsPause", { volume: `\`${volume}\`` }))] }); if (volume > 100) return ctx.reply({ embeds: [createEmbed("error", i18n.__mf("commands.music.volume.volumeLimit", { maxVol: `\`100\`` }), true)] }); resVolume.setVolume(volume / 100); return ctx.reply({ embeds: [createEmbed("success", `🔊 **|** ${i18n.__mf("commands.music.volume.newVolume", { volume })}`)] }); } }
KidDevelopper/disc-11
src/config.ts
import { IpresenceData } from "./typings"; import { ActivityType, ClientOptions, ClientPresenceStatus, Intents, LimitedCollection, Options, ShardingManagerMode } from "discord.js"; import { join } from "path"; import i18n from "i18n"; export const clientOptions: ClientOptions = { allowedMentions: { parse: ["users"], repliedUser: true }, intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_BANS], makeCache: Options.cacheWithLimits({ MessageManager: { maxSize: Infinity, sweepInterval: 300, sweepFilter: LimitedCollection.filterByLifetime({ lifetime: 10800 }) }, ThreadManager: { maxSize: Infinity, sweepInterval: 300, sweepFilter: LimitedCollection.filterByLifetime({ lifetime: 10800, getComparisonTimestamp: e => e.archiveTimestamp!, excludeFromSweep: e => !e.archived }) } }), retryLimit: 3 }; export const shardsCount: number | "auto" = "auto"; export const shardingMode: ShardingManagerMode = "worker"; export const embedColor = process.env.EMBED_COLOR?.toUpperCase() as string || "3CAAFF"; export const lang = process.env.LOCALE?.toLowerCase() as string || "en"; export const owners: string[] = JSON.parse(process.env.OWNERS ?? "[]"); export const devGuild = JSON.parse(process.env.DEV_GUILD ?? "[]"); export const isDev = process.env.NODE_ENV?.toLowerCase() === "development"; export const isProd = !isDev; export const mainPrefix = isDev ? "d!" : (process.env.MAIN_PREFIX as string || "!"); export const altPrefixes: string[] = (JSON.parse(process.env.ALT_PREFIX as string || "[\"{mention}\"]") as string[]).filter((x, i, a) => (a.indexOf(x) === i) && x !== mainPrefix); export const enableSlashCommand = process.env.ENABLE_SLASH_COMMAND?.toLowerCase() !== "no"; export const musicSelectionType = process.env.MUSIC_SELECTION_TYPE?.toLowerCase() as string || "message"; export const is247Allowed = process.env.ENABLE_24_7_COMMAND?.toLowerCase() === "yes"; export const stayInVCAfterFinished = process.env.STAY_IN_VC_AFTER_FINISHED?.toLowerCase() === "yes"; export const djRoleName = process.env.DJ_ROLE_NAME! || "DJ"; export const muteRoleName = process.env.MUTE_ROLE_NAME! || "Muted"; export const yesEmoji = process.env.YES_EMOJI! || "✅"; export const noEmoji = process.env.NO_EMOJI! || "❌"; export const presenceData: IpresenceData = { activities: (JSON.parse(process.env.ACTIVITIES! || "[]") as string[]).map((x, i) => ({ name: x, type: ((JSON.parse(process.env.ACTIVITY_TYPES! || "[]") as string[])[i]?.toUpperCase() || "PLAYING") as Exclude<ActivityType, "CUSTOM"> })), status: ["online"] as ClientPresenceStatus[], interval: 60000 }; i18n.configure({ defaultLocale: "en", directory: join(process.cwd(), "lang"), locales: [ "en", "es", "id" ], objectNotation: true }); i18n.setLocale(lang); export default i18n;
KidDevelopper/disc-11
src/utils/decorators/MusicUtil.ts
import { CommandContext } from "../../structures/CommandContext"; import { createEmbed } from "../createEmbed"; import i18n from "../../config"; export function haveQueue(ctx: CommandContext): boolean { if (!ctx.guild?.queue) { void ctx.reply({ embeds: [createEmbed("warn", i18n.__("utils.musicDecorator.noQueue"))] }); return false; } return true; } export function inVC(ctx: CommandContext): boolean { if (!ctx.member?.voice.channel) { void ctx.reply({ embeds: [createEmbed("warn", i18n.__("utils.musicDecorator.noInVC"))] }); return false; } return true; } export function validVC(ctx: CommandContext): boolean { const voiceChannel = ctx.member?.voice.channel; if (voiceChannel?.id === ctx.guild?.me?.voice.channel?.id) return true; if (!voiceChannel?.joinable) { void ctx.reply({ embeds: [createEmbed("error", i18n.__("utils.musicDecorator.validVCJoinable"), true)] }); return false; } if (!voiceChannel.permissionsFor(ctx.guild!.me!.id)?.has("SPEAK")) { void ctx.reply({ embeds: [createEmbed("error", i18n.__("utils.musicDecorator.validVCPermission"), true)] }); return false; } return true; } export function sameVC(ctx: CommandContext): boolean { if (!ctx.guild?.me?.voice.channel) return true; const botVC = ctx.guild.queue?.connection?.joinConfig.channelId ?? ctx.guild.me.voice.channel.id; if (ctx.member?.voice.channel?.id !== botVC) { void ctx.reply({ embeds: [createEmbed("warn", i18n.__("utils.musicDecorator.sameVC"))] }); return false; } return true; }
KidDevelopper/disc-11
src/typings/index.d.ts
import { CommandContext } from "../structures/CommandContext"; import { ServerQueue } from "../structures/ServerQueue"; import { Disc } from "../structures/Disc"; import { ActivityType, ApplicationCommandOptionData, ApplicationCommandType, ClientEvents, ClientPresenceStatus, Client as OClient, Collection, GuildMember, MessageEmbed } from "discord.js"; export type MessageInteractionAction = "editReply" | "reply" | "followUp"; export interface QueryData { isURL: boolean; sourceType?: "youtube" | "spotify" | "soundcloud" | "query" | "unknown"; type?: "track" | "playlist" | "unknown"; } export interface SearchTrackResult { type?: "selection"|"results"; items: ISong[]; } export interface PaginationPayload { author: string; content?: string; pages: string[]; embed: MessageEmbed; edit(index: number, embed: MessageEmbed, page: string): unknown; } export interface IDiscLoggerOptions { prod: boolean; } export interface SlashOption { name?: string; description?: string; type?: ApplicationCommandType; options?: ApplicationCommandOptionData[]; defaultPermission?: boolean; } export interface IpresenceData { activities: { name: string; type: Exclude<ActivityType, "CUSTOM"> }[]; status: ClientPresenceStatus[]; interval: number; } export interface IEvent { readonly name: keyof ClientEvents; execute(...args: any): void; } export interface ICommandComponent { meta: { aliases?: string[]; cooldown?: number; disable?: boolean; readonly path?: string; devOnly?: boolean; description?: string; readonly category?: string; name: string; usage?: string; slash?: SlashOption; contextChat?: string; contextUser?: string; }; execute(context: CommandContext): any; } export interface ICategoryMeta { name: string; hide: boolean; cmds: Collection<string, ICommandComponent>; } declare module "discord.js" { // @ts-expect-error Override typings export interface Client extends OClient { config: Disc["config"]; logger: Disc["logger"]; request: Disc["request"]; commands: Disc["commands"]; events: Disc["events"]; build(token: string): Promise<this>; } export interface Guild { client: Disc; queue?: ServerQueue; } } export interface ISong { id: string; title: string; url: string; duration: number; thumbnail: string; } export interface IQueueSong { song: ISong; requester: GuildMember; index: number; key: string; } export type LoopMode = "OFF"|"SONG"|"QUEUE"; export interface ILyricsAPIResult<E extends boolean> { error: E; artist?: E extends true ? null : string; song?: E extends true ? null : string; album_art?: E extends true ? null : string; lyrics?: E extends true ? null : string; url?: E extends true ? null : string; message?: E extends true ? string : never; synced: E extends true ? never : boolean|string; } export interface ISpotifyAccessTokenAPIResult { clientId: string; accessToken?: string; accessTokenExpirationTimestampMs: number; isAnonymous: boolean; } export interface ExternalUrls { spotify: string; } export interface ArtistsEntity { external_urls: ExternalUrls; href: string; id: string; name: string; type: string; uri: string; } export interface SpotifyArtist { name: string; } export interface SpotifyPlaylist { name: string; tracks: { items: { track: SpotifyTrack }[]; next: string | null; previous: string | null; }; } export interface SpotifyTrack { artists: ArtistsEntity[]; duration_ms: number; external_urls: { spotify: string; }; id: string; name: string; } export interface SpotifyArtist { tracks: SpotifyTrack[]; }
KidDevelopper/disc-11
src/events/ErrorEvent.ts
import { BaseEvent } from "../structures/BaseEvent"; export class ErrorEvent extends BaseEvent { public constructor(client: BaseEvent["client"]) { super(client, "error"); } public execute(error: string): void { this.client.logger.error("CLIENT_ERROR:", error); } }