repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
syrflover/iterator-helper
deno/methods/inspect.ts
<filename>deno/methods/inspect.ts import type { ForEachFn } from "../types/functions/mod.ts"; import { _curry } from "../lib/utils/mod.ts"; async function* _inspect_impl_fn<T>( fn: ForEachFn<T>, iter: AsyncIterable<T>, ): AsyncIterable<T> { for await (const elem of iter) { await fn(elem); yield elem; } } export interface Inspect { <T>(fn: ForEachFn<T>, iter: AsyncIterable<T>): AsyncIterable<T>; <T>(fn: ForEachFn<T>): (iter: AsyncIterable<T>) => AsyncIterable<T>; } export const inspect: Inspect = _curry(_inspect_impl_fn);
syrflover/iterator-helper
src/types/guards/isArrayLike_test.ts
<filename>src/types/guards/isArrayLike_test.ts import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { isArrayLike } from './mod.ts'; Deno.test('isArrayLike() array', () => { const actual = isArrayLike([1, 2, 3]); const expected = true; assertEquals(actual, expected); }); Deno.test('isArrayLike() typed array', () => { const actual = isArrayLike(new Int8Array(0)); const expected = true; assertEquals(actual, expected); }); Deno.test('isArrayLike() undefined', () => { const actual = isArrayLike(undefined); const expected = false; assertEquals(actual, expected); });
syrflover/iterator-helper
deno/lib/iterable/next.ts
import { isIterable } from '../../types/guards/isIterable.ts'; export type NextReturn<T> = { done?: boolean; value: T; }; export function next_async<T>(iter: AsyncIterable<T>): Promise<NextReturn<T>> { const it = iter[Symbol.asyncIterator](); return it.next(); } export function next_sync<T>(iter: Iterable<T>): NextReturn<T> { const it = iter[Symbol.iterator](); return it.next(); } export async function next<T>(iter: Iterable<T> | AsyncIterable<T>): Promise<NextReturn<T>> { if (isIterable(iter)) { return next_sync(iter); } return next_async(iter); }
syrflover/iterator-helper
src/methods/cycle_test.ts
<gh_stars>1-10 import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { iterator } from '../mod.ts'; Deno.test('count() [1,2,3,4,5,6,7,8]', async () => { const a = iterator([1, 2, 3, 4, 5, 6, 7, 8]); const actual: number[] = []; const expected = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3]; for await (const _ of a.cycle()) { if (actual.length === expected.length) { break; } actual.push(_); } assertEquals(actual, expected); });
syrflover/iterator-helper
src/types/flatten.ts
import type { EP } from './promise.ts'; export type Flatten<T> = T extends Iterable<infer E> | AsyncIterable<infer E> ? EP<E> : T;
syrflover/iterator-helper
src/types/guards/isAsyncIterable_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { isAsyncIterable } from './mod.ts'; function* iterable() { yield 1; yield 2; yield 3; yield 4; } async function* asyncIterable() { yield 1; yield 2; yield 3; yield 4; } Deno.test('isAsyncIterable() Array == false', () => { const actual = isAsyncIterable([1, 2, 3, 4]); const expected = false; assertEquals(actual, expected); }); Deno.test('isAsyncIterable() Iterable == false', () => { const actual = isAsyncIterable(iterable()); const expected = false; assertEquals(actual, expected); }); Deno.test('isAsyncIterable() AsyncIterable == true', () => { const actual = isAsyncIterable(asyncIterable()); const expected = true; assertEquals(actual, expected); }); Deno.test('isAsyncIterable() undefined == false', () => { const actual = isAsyncIterable(undefined); const expected = false; assertEquals(actual, expected); });
syrflover/iterator-helper
deno/lib/iterable/initLast.ts
import { pair, Pair } from '../../types/pair.ts'; import { fold } from '../../methods/fold.ts'; import { append } from './append.ts'; import { next_async } from './next.ts'; import { sequence } from './toAsyncIterable.ts'; export async function initLast<T>(iter: AsyncIterable<T>): Promise<Pair<AsyncIterable<T>, T | undefined>> { const { done, value } = await next_async(iter); if (done) { return pair(iter, undefined); } return fold(([r, prev], elem) => pair(append(prev, r), elem), pair(sequence<T>([]), value), iter); }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/form-inputs/z-form-input-base.ts
import { AsyncValidatorFn, ValidatorFn, FormControl } from '@angular/forms'; import { Subject } from 'rxjs'; export class ZFormInputBase<X> { value: X; key: string; label: string; hint?: string; required: boolean; order: number; controlType: string; disabled: boolean; validators: ValidatorFn[]; asyncValidators: AsyncValidatorFn[]; layout: { cols: number; colSmall?: number; }; readonly: boolean; icon?: string; public didReceiveControl = new Subject<FormControl>(); public currentControl?: FormControl; constructor(input: ZInput<X>) { this.value = input.value; this.key = input.key || ''; this.icon = input.icon; this.label = input.label || ''; this.required = input.required; this.order = input.order === undefined ? 1 : input.order; this.hint = input.hint; this.disabled = input.disabled; this.validators = input.validators || []; this.asyncValidators = input.asyncValidators || []; this.readonly = input.readonly ? true : false; this.layout = input.layout || {cols: 100}; this.didReceiveControl.subscribe((control) => { this.currentControl = control; }); } } export interface ZInput<X> { value?: X; key?: string; label?: string; icon?: string; hint?: string; required?: boolean; order?: number; sendValueIfDisabled?: boolean; disabled?: boolean; validators?: ValidatorFn[]; asyncValidators?: AsyncValidatorFn[]; layout?: { cols: number; colSmall?: number; }; readonly?: boolean; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/z-modal.component.ts
import { Component, OnInit, Output, EventEmitter, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'z-modal', templateUrl: './z-modal.component.html', styleUrls: ['./z-modal.component.scss'] }) export class ZModalComponent implements OnInit { public showLog = false; @Output() isConfirmed = new EventEmitter<boolean>(); constructor( private dialogRef: MatDialogRef<ZModalComponent>, @Inject(MAT_DIALOG_DATA) public modal: any ) { } ngOnInit(): void {} public close(): void { this.dialogRef.close(); } public closeConfirm(): void { this.isConfirmed.emit(false); this.close(); } public acceptConfirm(): void { this.isConfirmed.emit(true); this.close(); } }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/providers/index.ts
<reponame>LucasZaia/zmaterial-app export * from './z-form-provider';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/index.ts
<filename>projects/zmaterial/src/lib/z-menu/index.ts import { from } from 'rxjs'; export * from './z-menu.module'; export * from './z-menu-material'; export * from './z-menu-bootstrap'; export * from './interfaces';
LucasZaia/zmaterial-app
projects/zmaterial/src/public-api.ts
// ! z-modal export * from './lib/z-modal/index'; // ! z-menu export * from './lib/z-menu/index'; // ! z-form export * from './lib/z-form/index';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/form-inputs/z-form-input-text.ts
<reponame>LucasZaia/zmaterial-app<filename>projects/zmaterial/src/lib/z-form/form-inputs/z-form-input-text.ts import { ZFormInputBase, ZInput } from './z-form-input-base'; export class ZFormInputText extends ZFormInputBase<string> { public controlType = 'inputText'; public type: string; public maxlength?: number; public minlength?: number; public mask: string; public preFix?: string; constructor(input: ZInputText) { super(input); this.type = input.type; this.maxlength = input.maxlength; this.minlength = input.minlength; this.preFix = input.preFix; switch (input.type) { case 'ip': this.mask = 'IP'; break; case 'CPF': this.mask = '000.000.000-00'; break; case 'CNPJ': this.mask = '00.000.000/0000-00'; break; } } } export interface ZInputText extends ZInput<string> { type: 'email' | 'password' | 'text' | 'ip' | 'CPF' | 'CNPJ' | 'CPF/CNPJ' | 'vehiclePlate' ; maxlength?: number; minlength?: number; preFix?: string; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/providers/z-form-provider.ts
<reponame>LucasZaia/zmaterial-app<gh_stars>1-10 import { Observable } from 'rxjs'; import { EventEmitter } from '@angular/core'; import { ZFormInputBase } from '../form-inputs'; export abstract class ZFormProvider { /** * Event Reset Form */ public didResetForm = new EventEmitter(); /** * Event Set Value Form */ public didSetValueForm = new EventEmitter<any>(); /** * Function Set Value Form and Emit Event. * @param value New Value Seto to Form. */ public setValueForm(value: any): void { this.didSetValueForm.emit(value); } /** * Function Reset Form and Emit Event. */ public resetForm(): void { this.didResetForm.emit(); } public abstract getInputs(): Observable<ZFormInputBase<any>[]>; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/z-menu-bootstrap/index.ts
export * from './z-menu-bootstrap.component';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/validators/index.ts
export * from './z-pattern-validator'; export * from './z-custom-validator';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/interfaces/z-modal-manual-log.ts
<gh_stars>1-10 import { ZModalManual } from './z-modal-manual'; export interface ZModalManualLog { base: ZModalManual; btnLogTitle: string; log: string; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/z-menu-material/index.ts
export * from './z-menu-material.component';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/form-inputs/index.ts
export * from './z-form-input-base'; export * from './z-form-input-text';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/z-form.service.ts
import { zCfpValidator, zCnpjPattern, zCnpjValidar, zCpfCnpjPattern, zCpfPattern, zIpPattern, zVehiclePlatePattern } from './validators'; import { AbstractControl, AsyncValidatorFn, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'; import { Injectable } from '@angular/core'; import { ZFormInputBase, ZFormInputText } from './form-inputs'; @Injectable({ providedIn: 'root' }) export class ZFormService { constructor() { } public getFormGroup(formInputs: ZFormInputBase<any>[]): FormGroup { const currentGroup = formInputs.reduce<{ [key: string]: AbstractControl; }>((group, input, idx, arr) => { group[input.key] = this.inputControl(input); return group; }, {}); return new FormGroup(currentGroup); } public inputControl(input: ZFormInputBase<any>): AbstractControl { const validators: ValidatorFn[] = []; const asyncValidators: AsyncValidatorFn[] = []; if (input.required) { validators.push(Validators.required); } if (input.controlType === 'inputText') { if ((input as ZFormInputText).type) { validators.push(Validators.minLength((input as ZFormInputText).minlength)); } switch ((input as ZFormInputText).type) { case 'email': validators.push(Validators.email); break; case 'ip': validators.push(Validators.pattern(zIpPattern)); break; case 'vehiclePlate': validators.push(Validators.pattern(zVehiclePlatePattern)); break; case 'CPF': validators.push(Validators.pattern(zCpfPattern)); validators.push(zCfpValidator); break; case 'CNPJ': validators.push(Validators.pattern(zCnpjPattern)); validators.push(zCnpjValidar); break; case 'CPF/CNPJ': validators.push(Validators.pattern(zCpfCnpjPattern)); break; } } const control = new FormControl({ value: input.value === undefined ? '' : input.value, disabled: input.disabled }, [...validators, ...input.validators], [...asyncValidators, ...input.asyncValidators]); input.didReceiveControl.next(control); return control; } }
LucasZaia/zmaterial-app
src/app/app.component.ts
<reponame>LucasZaia/zmaterial-app<gh_stars>0 import { Component } from '@angular/core'; import { ZMenuProfile, ZModalService, ZMenuItems,ZMenuBootstrapItens, ZMenuProfileBootstrap} from 'zmaterial'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { public currentProfile: ZMenuProfile = { descriptions: [ {icon: 'email', text: '<EMAIL>'}, ] }; public currentProfileBootstrap: ZMenuProfileBootstrap = { img:'https://instagram.fsod8-1.fna.fbcdn.net/v/t51.2885-19/s150x150/155286890_286674549544222_4007179158159824399_n.jpg?tp=1&_nc_ht=instagram.fsod8-1.fna.fbcdn.net&_nc_ohc=IOeJO6hdY8oAX8eMrXt&edm=ABfd0MgAAAAA&ccb=7-4&oh=6e87b0b6245ef13675f09bc7f8273c96&oe=609B0898&_nc_sid=7bff83', descriptions: [ {icon: 'fa-envelope', text: '<EMAIL>'}, {icon: 'fa-phone', text: '<EMAIL>'}, ] }; public currentMenus: ZMenuItems[] = [ { category: 'Cadastro', icon: 'add', itens: [ { label: 'Usuário', link: 'register/user' }, { label: 'Curso', link: 'register/course' } ] } ]; public currentBootstrapMenus: ZMenuBootstrapItens[] = [ { category: 'Cadastro', icon: 'fa-user-plus', itens: [ {label:'User',link:'register/user'}, ] }, { category: 'Curso', icon: 'fa-graduation-cap', itens: [ {label:'Course',link:'register/course'}, ] }, ]; constructor(private zModal: ZModalService) { } public logout(event: boolean): void { console.log(event); } }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/interfaces/z-modal-log.ts
<filename>projects/zmaterial/src/lib/z-modal/interfaces/z-modal-log.ts import { ZModalBase } from './z-modal-base'; export interface ZModalLog { base: ZModalBase; btnLogTitle: string; log: string; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/interfaces/z-modal-manual-confirm.ts
import { ZModalManual } from './z-modal-manual'; export interface ZModalManualConfirm { base: ZModalManual; btnConfirmTitle: string; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/interfaces/index.ts
<gh_stars>1-10 export * from './z-modal-type'; export * from './z-modal-base'; export * from './z-modal-log'; export * from './z-modal-confirm'; export * from './z-modal-manual'; export * from './z-modal-manual-log'; export * from './z-modal-manual-confirm';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/interfaces/z-menu-bootstrap-itens.ts
<gh_stars>0 export interface ZMenuBootstrapItens { category: string; icon: string; itens: { label: string; link: string; icon?: string; disabled?: boolean; }[]; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/interfaces/index.ts
<reponame>LucasZaia/zmaterial-app export * from './z-menu-profile'; export * from './z-menu-items'; export * from './z-menu-bootstrap-itens'; export * from './z-menu-itens-bootstrap-profile';
LucasZaia/zmaterial-app
src/app/app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CourseComponent } from './register/course/course.component'; import { UserComponent } from './register/user/user.component'; const routes: Routes = [ { path: 'register/user', component: UserComponent, }, { path: 'register/course', component: CourseComponent, data: { hideSideBar: true } }, { path: '', component: UserComponent, }, { path: '**', redirectTo: '' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/z-modal.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ZModalComponent } from './z-modal.component'; import { ZModalService } from './z-modal.service'; import { ZModule } from '../z.module'; @NgModule({ declarations: [ ZModalComponent ], imports: [ CommonModule, // Module Global ZModule ], exports: [ ZModalComponent ], providers: [ ZModalService ], entryComponents: [ ZModalComponent ] }) export class ZModalModule { }
LucasZaia/zmaterial-app
src/app/register/user/user.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable, of } from 'rxjs'; import { ZFormInputBase, ZFormInputText, ZFormProvider } from 'zmaterial'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class UserComponent extends ZFormProvider implements OnInit { public currentValue: any = {}; constructor() { super(); } ngOnInit(): void { } getInputs(): Observable<ZFormInputBase<any>[]> { return of([ new ZFormInputText({ label: 'Campo de Texto', key: 'text', type: 'text', required: true, layout: { cols: 50 } }), new ZFormInputText({ label: 'Campo de Senha', key: 'password', type: 'password', required: true, layout: { cols: 50 } }), new ZFormInputText({ label: 'Campo de E-mail', key: 'email', type: 'email', required: true, layout: { cols: 50 } }), new ZFormInputText({ label: 'Campo de IP', key: 'ip', type: 'ip', required: true, layout: { cols: 50 } }), new ZFormInputText({ label: 'Campo de CPF', key: 'CPF', type: 'CPF', required: true, layout: { cols: 50 } }), new ZFormInputText({ label: 'Campo de CNPJ', key: 'CNPJ', type: 'CNPJ', required: true, layout: { cols: 50 } }), new ZFormInputText({ label: 'Campo de CPF/CNPJ', key: '<KEY>', type: 'CPF/CNPJ', required: true, layout: { cols: 50 } }), new ZFormInputText({ label: 'Campo de Placa', key: 'vehiclePlate', type: 'vehiclePlate', required: true, layout: { cols: 50 } }), ]); } public saveData(value: any): void { console.log('Valores: ', value); this.currentValue = value; } }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/z-modal.service.ts
<reponame>LucasZaia/zmaterial-app import { Injectable } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Observable } from 'rxjs'; import { ZModalBase, ZModalConfirm, ZModalLog, ZModalType, ZModalManual, ZModalManualLog, ZModalManualConfirm } from './interfaces'; import { ZModalComponent } from './z-modal.component'; @Injectable({ providedIn: 'root' }) /** * Service That Has Modals Call Functions. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ export class ZModalService { constructor(private dialog: MatDialog) {} /** * Execute the Success Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTSuccess(config: ZModalBase): void { this.dialog.open(ZModalComponent, { width: config.width, height: config.height, disableClose: config.isDisableClose, data: { controlType: ZModalType.T_SUCCESS, title: config.title, description: config.description, btnCloseTitle: config.btnCloseTitle }, }); } /** * Execute the Success Log Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTSuccessLog(config: ZModalLog): void { this.dialog.open(ZModalComponent, { width: config.base.width, height: config.base.height, disableClose: config.base.isDisableClose, data: { controlType: ZModalType.T_SUCCESS_LOG, title: config.base.title, description: config.base.description, btnCloseTitle: config.base.btnCloseTitle, btnLogTitle: config.btnLogTitle, log: config.log } }); } /** * Execute the Success Confirm Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTSuccessConfirm(config: ZModalConfirm): Observable<boolean> { const resp = this.dialog.open(ZModalComponent, { width: config.base.width, height: config.base.height, disableClose: config.base.isDisableClose, data: { controlType: ZModalType.T_SUCCESS_CONFIRM, title: config.base.title, description: config.base.description, btnCloseTitle: config.base.btnCloseTitle, btnConfirmTitle: config.btnConfirmTitle } }); return resp.componentInstance.isConfirmed; } /** * Execute the Warning Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTWarning(config: ZModalBase): void { this.dialog.open(ZModalComponent, { width: config.width, height: config.height, disableClose: config.isDisableClose, data: { controlType: ZModalType.T_WARNING, title: config.title, description: config.description, btnCloseTitle: config.btnCloseTitle }, }); } /** * Execute the Warning Log Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTWarningLog(config: ZModalLog): void { this.dialog.open(ZModalComponent, { width: config.base.width, height: config.base.height, disableClose: config.base.isDisableClose, data: { controlType: ZModalType.T_WARNING_LOG, title: config.base.title, description: config.base.description, btnCloseTitle: config.base.btnCloseTitle, btnLogTitle: config.btnLogTitle, log: config.log } }); } /** * Execute the Warning Confirm Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTWarningConfirm(config: ZModalConfirm): Observable<boolean> { const resp = this.dialog.open(ZModalComponent, { width: config.base.width, height: config.base.height, disableClose: config.base.isDisableClose, data: { controlType: ZModalType.T_WARNING_CONFIRM, title: config.base.title, description: config.base.description, btnCloseTitle: config.base.btnCloseTitle, btnConfirmTitle: config.btnConfirmTitle } }); return resp.componentInstance.isConfirmed; } /** * Execute the Error Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTError(config: ZModalBase): void { this.dialog.open(ZModalComponent, { width: config.width, height: config.height, disableClose: config.isDisableClose, data: { controlType: ZModalType.T_ERROR, title: config.title, description: config.description, btnCloseTitle: config.btnCloseTitle }, }); } /** * Execute the Error Log Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTErrorLog(config: ZModalLog): void { this.dialog.open(ZModalComponent, { width: config.base.width, height: config.base.height, disableClose: config.base.isDisableClose, data: { controlType: ZModalType.T_ERROR_LOG, title: config.base.title, description: config.base.description, btnCloseTitle: config.base.btnCloseTitle, btnLogTitle: config.btnLogTitle, log: config.log } }); } /** * Execute the Error Confirm Modal Template. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalTErrorConfirm(config: ZModalConfirm): Observable<boolean> { const resp = this.dialog.open(ZModalComponent, { width: config.base.width, height: config.base.height, disableClose: config.base.isDisableClose, data: { controlType: ZModalType.T_ERROR_CONFIRM, title: config.base.title, description: config.base.description, btnCloseTitle: config.base.btnCloseTitle, btnConfirmTitle: config.btnConfirmTitle } }); return resp.componentInstance.isConfirmed; } /** * Execute the Manual Modal. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalManual(config: ZModalManual): void { this.dialog.open(ZModalComponent, { width: config.base.width, height: config.base.height, disableClose: config.base.isDisableClose, data: { controlType: ZModalType.M_ALERT, title: config.base.title, description: config.base.description, btnCloseTitle: config.base.btnCloseTitle, icon: config.icon, backgroundColor: config.backgroundColor }, }); } /** * Execute the Manual Log Modal. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalManualLog(config: ZModalManualLog): void { this.dialog.open(ZModalComponent, { width: config.base.base.width, height: config.base.base.height, disableClose: config.base.base.isDisableClose, data: { controlType: ZModalType.M_ALERT_LOG, title: config.base.base.title, description: config.base.base.description, btnCloseTitle: config.base.base.btnCloseTitle, btnLogTitle: config.btnLogTitle, log: config.log, icon: config.base.icon, backgroundColor: config.base.backgroundColor } }); } /** * Execute the Manual Confirm Modal. * * @author <NAME> <<EMAIL>> * @copyright zmaterial */ public zModalManualConfirm(config: ZModalManualConfirm): Observable<boolean> { const resp = this.dialog.open(ZModalComponent, { width: config.base.base.width, height: config.base.base.height, disableClose: config.base.base.isDisableClose, data: { controlType: ZModalType.M_ALERT_CONFIRM, title: config.base.base.title, description: config.base.base.description, btnCloseTitle: config.base.base.btnCloseTitle, btnConfirmTitle: config.btnConfirmTitle, icon: config.base.icon, backgroundColor: config.base.backgroundColor } }); return resp.componentInstance.isConfirmed; } }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/z-menu-material/z-menu-material.component.ts
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; import { Component, Input, OnInit, Output } from '@angular/core'; import { ActivationStart, Router } from '@angular/router'; import { Observable, Subject } from 'rxjs'; import { filter, map } from 'rxjs/operators'; import { ZMenuProfile, ZMenuItems } from '../interfaces'; @Component({ selector: 'z-menu-material', templateUrl: './z-menu-material.component.html', styleUrls: ['./z-menu-material.component.scss'] }) export class ZMenuMaterialComponent implements OnInit { // ? Input - Screen Infos /** * Define title project */ @Input() titleProject: string; /** * Define logo project */ @Input() logoProject: string; /** * Define profile items */ @Input() profile: ZMenuProfile; /** * Define menu items */ @Input() menuItems: ZMenuItems[]; // ? Input - Show Itens /** * If show button logout or not. */ @Input() showLogout: boolean; // ? Output - Event Data /** * Event click logout. */ @Output() logout = new Subject<boolean>(); // ? Global /** * Defines whether it is a mobile device */ public isHandset: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset).pipe( map(result => result.matches) ); /** * Hide sidebar of screen */ public hideSidebar = false; constructor( private breakpointObserver: BreakpointObserver, private router: Router, ) {} ngOnInit(): void { this.router.events.pipe( filter((event) => event instanceof ActivationStart) ).subscribe((event: ActivationStart) => { if (event.snapshot.data.hideSideBar) { this.hideSidebar = event.snapshot.data.hideSideBar; } }); } }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/z-form-material/index.ts
export * from './z-form-material.component';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/index.ts
<gh_stars>1-10 export * from './z-modal.component'; export * from './z-modal.service'; export * from './z-modal.module'; export * from './interfaces';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/z-input-material/index.ts
<filename>projects/zmaterial/src/lib/z-form/z-input-material/index.ts export * from './z-input-material.component';
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/interfaces/z-menu-itens-bootstrap-profile.ts
export interface ZMenuProfileBootstrap{ img?: string; descriptions?: { icon: string; text: string; }[]; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/z-menu-bootstrap/z-menu-bootstrap.component.ts
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; import { ActivationStart, Router } from '@angular/router'; import { Observable, Subject } from 'rxjs'; import { filter, map } from 'rxjs/operators'; import { Component, OnInit, Input, Output } from '@angular/core'; import {ZMenuBootstrapItens} from '../interfaces/z-menu-bootstrap-itens'; import {ZMenuProfileBootstrap} from '../interfaces/z-menu-itens-bootstrap-profile'; @Component({ selector: 'z-menu-bootstrap', templateUrl: './z-menu-bootstrap.component.html', styleUrls: ['./z-menu-bootstrap.component.scss'] }) export class ZMenuBootstrapComponent implements OnInit { @Input() titleProject: string; @Input() itemsMenu: ZMenuBootstrapItens[]; @Input() showLogout: boolean; @Input() profile: ZMenuProfileBootstrap; @Input() logoProject: string; @Output() logout = new Subject<boolean>(); public isHandset: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset).pipe( map(result => result.matches) ); public hideSidebar = false; constructor( private breakpointObserver: BreakpointObserver, private router: Router ) {} ngOnInit(): void { this.router.events.pipe( filter((event) => event instanceof ActivationStart) ).subscribe((event:ActivationStart)=> { if(event.snapshot.data.hideSideBar) { this.hideSidebar = event.snapshot.data.hideSidebar; } }); } }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/interfaces/z-modal-confirm.ts
<filename>projects/zmaterial/src/lib/z-modal/interfaces/z-modal-confirm.ts<gh_stars>1-10 import { ZModalBase } from './z-modal-base'; export interface ZModalConfirm { base: ZModalBase; btnConfirmTitle: string; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/validators/z-pattern-validator.ts
export const zIpPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; export const zVehiclePlatePattern = '[A-Z]{3}[0-9]{1}[A-Z]{1}[0-9]{2}|[A-Z]{3}[0-9]{4}'; export const zCpfPattern = /^\d{3}\.\d{3}\.\d{3}\-\d{2}$/; export const zCnpjPattern = /^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/; export const zCpfCnpjPattern = /(^\d{3}\.\d{3}\.\d{3}\-\d{2}$)|(^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$)/;
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-menu/z-menu.module.ts
<reponame>LucasZaia/zmaterial-app import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ZModule } from '../z.module'; import { ZMenuMaterialComponent } from './z-menu-material'; import { ZMenuBootstrapComponent } from './z-menu-bootstrap'; @NgModule({ declarations: [ ZMenuMaterialComponent, ZMenuBootstrapComponent ], imports: [ CommonModule, // Module Global ZModule ], exports: [ ZMenuMaterialComponent, ZMenuBootstrapComponent ], }) export class ZMenuModule { }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/z-form.module.ts
<reponame>LucasZaia/zmaterial-app import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ZModule } from '../z.module'; import { ZFormMaterialComponent } from './z-form-material'; import { ZInputMaterialComponent } from './z-input-material'; import { ZFormService } from './z-form.service'; import { NgxMaskModule } from 'ngx-mask'; @NgModule({ declarations: [ ZFormMaterialComponent, ZInputMaterialComponent ], imports: [ CommonModule, // Module Global ZModule, // Mask NgxMaskModule.forRoot({ validation: false, }) ], exports: [ ZFormMaterialComponent, ZInputMaterialComponent ], providers: [ ZFormService ] }) export class ZFormModule { }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/interfaces/z-modal-type.ts
<reponame>LucasZaia/zmaterial-app<gh_stars>1-10 export enum ZModalType { // Template Success T_SUCCESS = 'T_SUCCESS', T_SUCCESS_LOG = 'T_SUCCESS_LOG', T_SUCCESS_CONFIRM = 'T_SUCCESS_CONFIRM', // Template Warning T_WARNING = 'T_WARNING', T_WARNING_LOG = 'T_WARNING_LOG', T_WARNING_CONFIRM = 'T_WARNING_CONFIRM', // Template Error T_ERROR = 'T_ERROR', T_ERROR_LOG = 'T_ERROR_LOG', T_ERROR_CONFIRM = 'T_ERROR_CONFIRM', // Template Manual M_ALERT = 'M_ALERT', M_ALERT_LOG = 'M_ALERT_LOG', M_ALERT_CONFIRM = 'M_ALERT_CONFIRM' }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-modal/interfaces/z-modal-base.ts
export interface ZModalBase { title: string; description: string; btnCloseTitle: string; isDisableClose?: boolean | true; width?: string | 'auto'; height?: string | 'auto'; }
LucasZaia/zmaterial-app
projects/zmaterial/src/lib/z-form/z-input-material/z-input-material.component.ts
<reponame>LucasZaia/zmaterial-app import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl, FormGroup } from '@angular/forms'; import { ZFormInputBase, ZFormInputText } from '../form-inputs'; import { ZFormService } from '../z-form.service'; @Component({ selector: 'z-input-material', templateUrl: './z-input-material.component.html', styleUrls: ['./z-input-material.component.scss'] }) export class ZInputMaterialComponent implements OnInit { @Input() input: ZFormInputBase<any>; @Input() form: FormGroup; public errorKeys: string[] = []; constructor(private formService: ZFormService) { } ngOnInit(): void { if (this.currentControl) { this.formSetup(this.currentControl); } else { this.input.didReceiveControl.subscribe((control) => { this.formSetup(control); }); } } get currentControl(): AbstractControl { return this.input.currentControl; } get asInputText(): ZFormInputText { return this.input as ZFormInputText; } public getErrors(control: AbstractControl): string[] { return Object.keys(control.errors); } public formSetup(control: AbstractControl): void { switch (this.input.controlType) { } } }
NatSokneng/blog-post
src/users/users.service.ts
<reponame>NatSokneng/blog-post import { Injectable, NotFoundException } from "@nestjs/common"; import { UserRepository } from "./repositories/user.repository"; import { UserEntity } from "./entities/user.entity"; import { CreateUserDto } from "./dto/create-user.dto"; import { RegistrationRespModel } from "./egistration.resp.model"; @Injectable() export class UsersService { constructor(private userRepository: UserRepository) {} async findOneByEmail(email: string) { return await this.userRepository.findOneUserByEmail(email); } private async registrationValidation(createUserDto: CreateUserDto) { if (!createUserDto.firstName) { return "First name can't be empty"; } if (!createUserDto.lastName) { return "Last name can't be empty"; } if (!createUserDto.email) { return "Email can't be empty"; } if (!createUserDto.password) { return "Password can't be empty"; } const emailRule = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; if (!emailRule.test(createUserDto.email.toLowerCase())) { return "Invalid email"; } const user = await this.userRepository.findOne({ email: createUserDto.email, }); if (user != null && user.email) { return "Email already exist"; } } public async registerUser(createUserDto: CreateUserDto) { let register = new RegistrationRespModel(); const errorMessage = await this.registrationValidation(createUserDto); if (errorMessage) { register.message = errorMessage; register.successStatus = false; return register; } const userEntity = new UserEntity(); userEntity.firstName = createUserDto.firstName; userEntity.lastName = createUserDto.lastName; userEntity.email = createUserDto.email; userEntity.password = <PASSWORD>; await this.userRepository.save(userEntity); register.successStatus = true; register.message = "Register is successfully"; return register; } async findById(id: number) { return await this.userRepository.findOne(id); } async deleteUser(id: number) { const deleteUser = await this.userRepository.delete({ id }); if (!deleteUser.affected) { throw new NotFoundException(`ID ${id} is not found`); } } }
NatSokneng/blog-post
src/post/post.controller.ts
<gh_stars>0 import { Controller, Get, Post, Body, HttpStatus, Param, Delete, Patch, UseGuards, } from "@nestjs/common"; import { PostService } from "./post.service"; import { CreatePostDto } from "./dto/create-post.dto"; import { UpdatePostDto } from "./dto/update-post.dto"; import { JwtAuthGuard } from "src/auth/jwt-auth.guard"; @Controller("post") export class PostController { constructor(private readonly postService: PostService) {} @UseGuards(JwtAuthGuard) @Post() async create(@Body() createPostDto: CreatePostDto) { const post = await this.postService.create(createPostDto); return { statusCode: HttpStatus.OK, message: "Created is successfully", post, }; } @UseGuards(JwtAuthGuard) @Get() async findAll() { const allPosts = await this.postService.findAll(); return { statusCode: HttpStatus.OK, message: "All post ", allPosts, }; } @UseGuards(JwtAuthGuard) @Get(":id") async findById(@Param("id") id: string) { const userId = await this.postService.DetailPost(+id); return { statusCode: HttpStatus.OK, message: "User ID", userId, }; } @UseGuards(JwtAuthGuard) @Delete(":id") async deletePost(@Param("id") id: string) { const deletePost = await this.postService.deletePost(+id); return { statusCode: HttpStatus.OK, message: "Deleted is successfully", deletePost, }; } @UseGuards(JwtAuthGuard) @Patch(":id") async updatePost( @Param("id") id: string, @Body() updatePostDto: UpdatePostDto ) { const updatePost = await this.postService.updatePost(+id, updatePostDto); return { statusCode: HttpStatus.OK, message: "Updated is successfully", updatePost, }; } }
NatSokneng/blog-post
src/post/entities/post.entity.ts
<filename>src/post/entities/post.entity.ts import { type } from "os"; import { CategoryEntity } from "src/categories/entities/category.entity"; import { TagEntity } from "src/tag/entities/tag.entity"; import { Entity, Column, ManyToMany, JoinTable } from "typeorm"; import { BaseEntity } from "../../generic/BaseEntity"; @Entity("Post") export class PostEntity extends BaseEntity { @Column() public title: string; @ManyToMany((type) => CategoryEntity, (category) => category.posts) @JoinTable({ name: "CategoryPost", joinColumn: { name: "postId", }, inverseJoinColumn: { name: "categoryId", }, }) categories: CategoryEntity[]; @ManyToMany(() => TagEntity, (tag) => tag.posts) tags: TagEntity[]; }
NatSokneng/blog-post
src/migrations/1646793604734-AddCocumnUser.ts
import { MigrationInterface, QueryRunner, Table } from "typeorm"; export class AddCocumnUser1646793604734 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.createTable( new Table({ name: "Test", columns: [ { name: "name", type: "varchar(200)", isNullable: false }, { name: "createdAt", type: "timestamp", default: "now()", }, ], }), true ); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.dropTable("Test"); } }
NatSokneng/blog-post
src/users/users.controller.ts
import { Controller, UseGuards, Get, Request, } from "@nestjs/common"; import { UsersService } from "./users.service"; import { JwtAuthGuard } from "../auth/jwt-auth.guard"; @Controller("users") export class UsersController { constructor(private readonly usersService: UsersService) {} @UseGuards(JwtAuthGuard) @Get("v1/profile") async getProfile(@Request() req) { return await this.usersService.findById(req.userId); } }
NatSokneng/blog-post
src/new-user/new-user.module.ts
import { Module } from '@nestjs/common'; import { NewUserService } from './new-user.service'; import { NewUserController } from './new-user.controller'; import { TypeOrmModule } from '@nestjs/typeorm'; import { NewUserRepository } from './repository/newuser.repository'; @Module({ imports: [TypeOrmModule.forFeature([NewUserRepository])], controllers: [NewUserController], providers: [NewUserService] }) export class NewUserModule {}
NatSokneng/blog-post
src/new-user/new-user.service.ts
<filename>src/new-user/new-user.service.ts import { Injectable, NotFoundException } from "@nestjs/common"; import { CreateNewUserDto } from "./dto/create-new-user.dto"; import { UpdateNewUserDto } from "./dto/update-new-user.dto"; import { NewUserEntity } from "./entities/new-user.entity"; import { NewUserRepository } from "./repository/newuser.repository"; @Injectable() export class NewUserService { constructor(private newUserRepository: NewUserRepository) { console.log(newUserRepository); } async create(createNewUserDto: CreateNewUserDto) { try { const newUser = new NewUserEntity(); newUser.email = createNewUserDto.email; newUser.password = <PASSWORD>; const user = await this.newUserRepository.save(newUser); return user; } catch (error) { console.log(error); } } async findAllNewUser() { const findAllNewUser = await this.newUserRepository.find(); if (!findAllNewUser) { throw new NotFoundException(`Not found`); } return findAllNewUser; } async findNewUserById(id: number) { const userDetail = await this.newUserRepository.findOne({ id }); if (!userDetail) { throw new NotFoundException(`ID ${id} is not found`); } return userDetail; } update(id: number, updateNewUserDto: UpdateNewUserDto) { return `This action updates a #${id} newUser`; } async deleteNewUser(id: number) { const deleteNewUser = await this.newUserRepository.delete({ id }); if (!deleteNewUser.affected) { throw new NotFoundException(`Id ${id} is not found`); } } }
NatSokneng/blog-post
src/categories/entities/category.entity.ts
<reponame>NatSokneng/blog-post<filename>src/categories/entities/category.entity.ts import { type } from "os"; import { PostEntity } from "src/post/entities/post.entity"; import { Entity, Column, ManyToMany } from "typeorm"; import { BaseEntity } from "../../generic/BaseEntity"; @Entity("Category") export class CategoryEntity extends BaseEntity { @Column() public name: string; @Column() public description: string; @ManyToMany(type => PostEntity, post => post.categories) posts: PostEntity[]; }
NatSokneng/blog-post
src/migrations/1645589701241-Category_Post.ts
import { MigrationInterface, QueryRunner, Table } from "typeorm"; export class CategoryPost1645589701241 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.createTable( new Table({ name: "CategoryPost", columns: [ { name: "categoryId", type: "int", }, { name: "postId", type: "int", }, ], }), true ); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.dropTable("CategoryPost"); } }
NatSokneng/blog-post
src/auth/auth.contoller.ts
import { Controller, Get, Post, Body, HttpStatus, Param, Delete, } from "@nestjs/common"; import { AuthService } from "./auth.service"; import { CreateUserDto } from "src/users/dto/create-user.dto"; import { UsersService } from "src/users/users.service"; import { AuthLoginDto } from "./dto/auth.login.dto"; //import { AuthExceptionFilter } from './auth-exceptions.filter'; @Controller("auth") export class AuthController { constructor( private readonly authService: AuthService, private readonly userService: UsersService ) {} @Post("v1/register") async createLogin(@Body() createUserDto: CreateUserDto) { return await this.userService.registerUser(createUserDto); } @Post("v1/login") async login(@Body() loginDto: AuthLoginDto) { const login = await this.authService.login(loginDto); return { statusCode: HttpStatus.OK, message: "Login is successfully", login, }; } @Get(":id") async show(@Param("id") id: string) { const user = await this.userService.findById(+id); return { statusCode: HttpStatus.OK, message: "Fine user by Id", user, }; } @Delete(":id") async deleteUser(@Param("id") id: string) { const deleteUser = await this.userService.deleteUser(+id); return { StatusCode: HttpStatus.OK, Message: "Delete is successfully", deleteUser, }; } }
NatSokneng/blog-post
src/tag/entities/tag.entity.ts
import { PostEntity } from "src/post/entities/post.entity"; import { Entity, Column, ManyToMany, JoinTable } from "typeorm"; import { BaseEntity } from "../../generic/BaseEntity"; @Entity("Tag") export class TagEntity extends BaseEntity { @Column() public content: string; @ManyToMany(() => PostEntity, (post) => post.tags) @JoinTable({ name: "PostTag", joinColumn: { name: "TagId", }, inverseJoinColumn: { name: "PostId", }, }) posts: PostEntity[]; }
NatSokneng/blog-post
src/users/repositories/user.repository.ts
<reponame>NatSokneng/blog-post import { EntityRepository, Repository } from 'typeorm'; import { UserEntity } from '../entities/user.entity'; @EntityRepository(UserEntity) export class UserRepository extends Repository<UserEntity> { findOneUserByEmail(email: string) { const query = this.createQueryBuilder("User"); query.where("User.email = :email", { email }); return query.getOne(); } }
NatSokneng/blog-post
src/migrations/1645585569621-Post.ts
<reponame>NatSokneng/blog-post<gh_stars>0 import { MigrationInterface, QueryRunner, Table } from "typeorm"; export class Post1645585569621 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.createTable( new Table({ name: "Post", columns: [ { name: "id", type: "int", isPrimary: true, isGenerated: true, generationStrategy: "increment", }, { name: "title", type: "varchar(200)" }, { name: "createdAt", type: "timestamp", default: "now()", }, { name: "updatedAt", type: "timestamp", default: "now()", }, ], }), true ); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.dropTable("Post"); } }
NatSokneng/blog-post
src/tag/tag.module.ts
import { Module } from "@nestjs/common"; import { TagService } from "./tag.service"; import { TagController } from "./tag.controller"; import { TypeOrmModule } from "@nestjs/typeorm"; import { TagRepository } from "./repository/tag.repository"; import { PostRepository } from "src/post/repositories/post.repository"; @Module({ imports: [TypeOrmModule.forFeature([TagRepository, PostRepository])], controllers: [TagController], providers: [TagService], }) export class TagModule {}
NatSokneng/blog-post
src/configurations/database.configuration.ts
<filename>src/configurations/database.configuration.ts import { Injectable } from "@nestjs/common"; import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from "@nestjs/typeorm"; import { ConfigurationService } from "./enviroment.configuration"; @Injectable() export class TypeOrmConfigService implements TypeOrmOptionsFactory { createTypeOrmOptions(): TypeOrmModuleOptions { const configService = new ConfigurationService(); return { type: configService.get('DB_DRIVER'), host: configService.get('DB_HOST'), port: +configService.get('DB_PORT'), username: configService.get('DB_USER'), password: config<PASSWORD>('DB_PASSWORD'), database: configService.get('DB_NAME'), logging: configService.get('DB_LOGGING'), synchronize: false, entities: [ __dirname + '/**/*.entity{.ts,.js}', 'dist/**/*.entity.js' ] }; } }
NatSokneng/blog-post
src/tag/dto/create-tag.dto.ts
<gh_stars>0 import { IsNotEmpty } from "class-validator"; export class CreateTagDto { @IsNotEmpty() content: string; @IsNotEmpty() postId: number[] }
NatSokneng/blog-post
src/new-user/dto/update-new-user.dto.ts
<filename>src/new-user/dto/update-new-user.dto.ts import { PartialType } from '@nestjs/mapped-types'; import { CreateNewUserDto } from './create-new-user.dto'; export class UpdateNewUserDto extends PartialType(CreateNewUserDto) {}
NatSokneng/blog-post
src/users/entities/user.entity.ts
<gh_stars>0 import { Entity, Column, BeforeInsert } from "typeorm"; import { BaseEntity } from "../../generic/BaseEntity"; import * as bcrypt from "bcrypt"; @Entity("User") export class UserEntity extends BaseEntity { @Column() public firstName: string; @Column() public lastName: string; @Column({ unique: true }) public email: string; @Column() password: string; @BeforeInsert() async hashPassword() { this.password = await bcrypt.hash(this.password, 8); } async validatePassword(password: string): Promise<boolean> { return bcrypt.compare(password, this.password); } /* @Column({ nullable: true, name: "refreshtoken" }) refreshToken: string; @Column({ type: "date", nullable: true, name: "refreshtokenexp" }) refreshTokenExp: string; */ }
NatSokneng/blog-post
src/new-user/repository/newuser.repository.ts
<filename>src/new-user/repository/newuser.repository.ts import { EntityRepository, Repository } from "typeorm"; import { NewUserEntity } from "../entities/new-user.entity"; @EntityRepository(NewUserEntity) export class NewUserRepository extends Repository<NewUserEntity> { async deleteNew(){ const query = await this.createQueryBuilder('NewUser'); query.select("NewUser.updatedAt", "updatedAt"); query.withDeleted(); query.getMany(); } }
NatSokneng/blog-post
src/new-user/entities/new-user.entity.ts
import { Column, BeforeInsert, Entity } from "typeorm"; import { BaseEntity } from "src/generic/BaseEntity"; import * as bcrypt from "bcrypt"; @Entity('NewUser') export class NewUserEntity extends BaseEntity { @Column({ unique: true, length: 200, }) email: string; @Column({ length: 25, }) password: string; @BeforeInsert() async hashPassword() { this.password = await bcrypt.hash(this.password, 8); } async validatePassword(password: string): Promise<boolean> { return bcrypt.compare(password, this.password); } }
NatSokneng/blog-post
src/categories/categories.service.ts
<gh_stars>0 import { Injectable, NotFoundException } from "@nestjs/common"; import { CreateCategoryDto } from "./dto/create-category.dto"; import { UpdateCategoryDto } from "./dto/update-category.dto"; import { CategoryRepository } from "./reposities/category.reposity"; @Injectable() export class CategoriesService { constructor(private readonly categoryRepository: CategoryRepository) {} async create(createCategoryDto: CreateCategoryDto) { const category = await this.categoryRepository.save(createCategoryDto); return category; } async allCategories() { const categories = await this.categoryRepository.find(); if(!categories) { throw new NotFoundException(`Not found`); } return categories; } async categoriesDetail(id: number) { const categoriesDetail = await this.categoryRepository.findOne({ where: { id: id }, }); if (!categoriesDetail) { throw new NotFoundException(`ID ${id} not exist`); } // return this.categoryRepository.save(categoriesDetail); return await categoriesDetail; } async updateCategory(id: number, updateCategoryDto: UpdateCategoryDto) { const updateCategory = await this.categoryRepository.update( { id }, updateCategoryDto ); await this.categoryRepository.findOne({ id }); if (!updateCategory.affected) { throw new NotFoundException(`ID ${id} not exist`); } } async deleteCategory(id: number) { const deleteCategory = await this.categoryRepository.delete({ id }); if (!deleteCategory.affected) { throw new NotFoundException(`ID ${id} not exist`); } } /* async restoreDeletedCategory(id: number) { const restoreResponse = await this.categoryRepository.restore(id); if (!restoreResponse.affected) { throw new NotFoundException(`Category ID ${id} not restore`); } } */ }
NatSokneng/blog-post
src/new-user/dto/create-new-user.dto.ts
<filename>src/new-user/dto/create-new-user.dto.ts import { IsEmail, IsNotEmpty, Length } from 'class-validator'; export class CreateNewUserDto { @IsEmail() @Length(200) email: string; @IsNotEmpty() @Length(8, 25) password: string; }
NatSokneng/blog-post
src/categories/categories.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete, HttpStatus, UseGuards, } from "@nestjs/common"; import { CategoriesService } from "./categories.service"; import { CreateCategoryDto } from "./dto/create-category.dto"; import { UpdateCategoryDto } from "./dto/update-category.dto"; import { JwtAuthGuard } from "src/auth/jwt-auth.guard"; @Controller("categories") export class CategoriesController { constructor(private readonly categoriesService: CategoriesService) {} @UseGuards(JwtAuthGuard) @Post() async create(@Body() createCategoryDto: CreateCategoryDto) { const categories = await this.categoriesService.create(createCategoryDto); return { statusCode: HttpStatus.OK, message: "Created is successfully", categories, }; } @UseGuards(JwtAuthGuard) @Get() async findAll() { const allCategories = await this.categoriesService.allCategories() return { statusCode: HttpStatus.OK, message: "All categories is ...", allCategories } } @UseGuards(JwtAuthGuard) @Get(":id") async findOne(@Param("id") id: string) { const categoryId = await this.categoriesService.categoriesDetail(+id); return { statusCode: HttpStatus.OK, message: "Category ID is...", categoryId } } @UseGuards(JwtAuthGuard) @Patch(":id") async update(@Param("id") id: string, @Body() updateCategoryDto: UpdateCategoryDto){ const update = await this.categoriesService.updateCategory(+id, updateCategoryDto); return { statusCode: HttpStatus.OK, message: "Updated is successfully", update }; } @UseGuards(JwtAuthGuard) @Delete(":id") async deleteCategory(@Param("id") id: string) { const deleteCategory = await this.categoriesService.deleteCategory(+id); return { statusCode: HttpStatus.OK, message: "Deleted is successfully", deleteCategory, }; } }
NatSokneng/blog-post
src/post/post.service.ts
import { Injectable, NotFoundException } from "@nestjs/common"; import { CategoryRepository } from "src/categories/reposities/category.reposity"; import { CreatePostDto } from "./dto/create-post.dto"; import { PostRepository } from "./repositories/post.repository"; import { PostEntity } from "./entities/post.entity"; import { UpdatePostDto } from "./dto/update-post.dto"; @Injectable() export class PostService { constructor( private postRepository: PostRepository, private categoryRepository: CategoryRepository ) {} async create(createPostDto: CreatePostDto) { const postEntity = new PostEntity(); postEntity.title = createPostDto.title; const categories = await this.categoryRepository.findByIds( createPostDto.categoryIds ); postEntity.categories = categories; const post = await this.postRepository.save(postEntity); return post; } async findAll() { const posts = await this.postRepository.getAllPost(); if (!posts) { throw new NotFoundException(`Not found`); } return posts; } async DetailPost(id: number) { const detailPost = await this.postRepository.getOneDetailByPostId(id); if (!detailPost) { throw new NotFoundException(`ID ${id} is not exist`); } return await detailPost; } async deletePost(id: number) { const deletePost = await this.postRepository.delete({ id }); if (!deletePost.affected) { throw new NotFoundException(`ID ${id} not exist`); } } async updatePost(id: number, updatePostDto: UpdatePostDto) { const updatePost = await this.postRepository.update({ id }, updatePostDto); await this.postRepository.findOne({ id }); if (!updatePost.affected) { throw new NotFoundException(`ID ${id} not exist`); } } }
NatSokneng/blog-post
src/tag/tag.service.ts
import { Injectable, NotFoundException } from "@nestjs/common"; import { CreateTagDto } from "./dto/create-tag.dto"; import { UpdateTagDto } from "./dto/update-tag.dto"; import { TagEntity } from "./entities/tag.entity"; import { TagRepository } from "./repository/tag.repository"; import { PostRepository } from "src/post/repositories/post.repository"; @Injectable() export class TagService { constructor( private tagRepository: TagRepository, private postRepository: PostRepository ) {} async create(createTagDto: CreateTagDto) { const tagEntity = new TagEntity(); tagEntity.content = createTagDto.content; const post = await this.postRepository.findByIds(createTagDto.postId); tagEntity.posts = post; const tag = await this.tagRepository.save(tagEntity); return tag; } async findAll() { const tags = await this.tagRepository.findAllTag(); if(!tags) { throw new NotFoundException(`Not Found`); } return tags; } async findOne(id: number) { const tagId = await this.tagRepository.findTagBYId(id); if (!tagId) { throw new NotFoundException(`ID ${id} is not found`); } return tagId; } async update(id: number, updateTagDto: UpdateTagDto) { const updateTag = await this.tagRepository.update({ id }, updateTagDto); await this.tagRepository.findOne({ id }); if (!updateTag.affected) { throw new NotFoundException(`ID ${id} not found`); } } async remove(id: number) { const deleteTagById = await this.tagRepository.delete({ id }); if (!deleteTagById.affected) { throw new NotFoundException(`Tag ID ${id} is not found`); } } }
NatSokneng/blog-post
src/tag/repository/tag.repository.ts
<reponame>NatSokneng/blog-post import { EntityRepository, Repository } from "typeorm"; import { TagEntity } from "../entities/tag.entity"; @EntityRepository(TagEntity) export class TagRepository extends Repository<TagEntity> { findAllTag() { const query = this.createQueryBuilder("TagEntity"); query.leftJoinAndSelect("TagEntity.posts", "Post"); return query.getMany(); } findTagBYId(id: number) { const query = this.createQueryBuilder("TagEntity"); query.leftJoinAndSelect("TagEntity.posts", "Post"); query.where("TagEntity.id = :tagId", { tagId: id }); return query.getOne(); } }
NatSokneng/blog-post
src/configurations/enviroment.configuration.ts
export class ConfigurationService { private readonly envConfig: { [key: string]: any } = null; constructor() { this.envConfig = { PORT: process.env.PORT, DB_DRIVER: process.env.DB_DRIVER, DB_HOST: process.env.DB_HOST, DB_PORT: process.env.DB_PORT, DB_USER: process.env.DB_USER, DB_PASSWORD: <PASSWORD>, DB_NAME: process.env.DB_NAME, DB_LOGGING: process.env.DB_LOGGING, NODE_ENV: process.env.NODE_ENV }; } get(key: string): any { return this.envConfig[key]; } }
NatSokneng/blog-post
src/new-user/new-user.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete, HttpStatus, UseGuards, } from "@nestjs/common"; import { NewUserService } from "./new-user.service"; import { CreateNewUserDto } from "./dto/create-new-user.dto"; import { UpdateNewUserDto } from "./dto/update-new-user.dto"; import { JwtAuthGuard } from "src/auth/jwt-auth.guard"; @Controller("new-user") export class NewUserController { constructor(private newUserService: NewUserService) {} @UseGuards(JwtAuthGuard) @Post("/") async createLogin(@Body() createNewUserDto: CreateNewUserDto) { const newUser = await this.newUserService.create(createNewUserDto); return { StatusCode: HttpStatus.OK, Message: "Create new user is successfully", newUser, }; } @UseGuards(JwtAuthGuard) @Get() async findAllNewUser() { const allNewUser = await this.newUserService.findAllNewUser(); return { StatusCode: HttpStatus.OK, Message: "All New User", allNewUser, }; } @UseGuards(JwtAuthGuard) @Get(":id") async findNewUser(@Param("id") id: string) { const userDetail = await this.newUserService.findNewUserById(+id); return { StatusCode: HttpStatus.OK, Message: "New user is ", userDetail, }; } @Patch(":id") update(@Param("id") id: string, @Body() updateNewUserDto: UpdateNewUserDto) { return this.newUserService.update(+id, updateNewUserDto); } @UseGuards(JwtAuthGuard) @Delete(":id") async deleteNewUser(@Param("id") id: string) { const newUser = await this.newUserService.deleteNewUser(+id); return { StatusCode: HttpStatus.OK, Message: "Deleted is successfully", newUser, }; } }
NatSokneng/blog-post
src/app.module.ts
import { Module } from "@nestjs/common"; import { AuthModule } from "./auth/auth.module"; import { UsersModule } from "./users/users.module"; import { TypeOrmModule } from "@nestjs/typeorm"; import { ConfigModule } from "@nestjs/config"; import { TypeOrmConfigService } from "./configurations/database.configuration"; import { AuthController } from "./auth/auth.contoller"; import { UsersController } from "./users/users.controller"; import { UsersService } from "./users/users.service"; import { CategoriesModule } from "./categories/categories.module"; import { PostModule } from "./post/post.module"; import { TagModule } from "./tag/tag.module"; import { NewUserModule } from './new-user/new-user.module'; @Module({ imports: [ TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService, }), ConfigModule.forRoot(), AuthModule, UsersModule, CategoriesModule, PostModule, TagModule, NewUserModule, ], controllers: [AuthController, UsersController], providers: [UsersService], }) export class AppModule {}
NatSokneng/blog-post
src/tag/tag.controller.ts
<reponame>NatSokneng/blog-post import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, HttpStatus, } from "@nestjs/common"; import { TagService } from "./tag.service"; import { CreateTagDto } from "./dto/create-tag.dto"; import { UpdateTagDto } from "./dto/update-tag.dto"; import { JwtAuthGuard } from "src/auth/jwt-auth.guard"; @Controller("tag") export class TagController { constructor(private readonly tagService: TagService) {} @UseGuards(JwtAuthGuard) @Post() async create(@Body() createTagDto: CreateTagDto) { const tag = await this.tagService.create(createTagDto); return { StatusCode: HttpStatus.OK, message: " Created is successfully", tag, }; } @UseGuards(JwtAuthGuard) @Get() async findAll() { const getAllTag = await this.tagService.findAll(); return { StatusCode: HttpStatus.OK, Message: "All tag is... ", getAllTag, }; } @UseGuards(JwtAuthGuard) @Get(":id") async findOne(@Param("id") id: string) { const tagId = await this.tagService.findOne(+id); return { StatusCode: HttpStatus.OK, Message: "Detail is ID: ", tagId, }; } @UseGuards(JwtAuthGuard) @Patch(":id") async update(@Param("id") id: string, @Body() updateTagDto: UpdateTagDto) { const updateTag = await this.tagService.update(+id, updateTagDto); return { StatusCode: HttpStatus.OK, Message: "Update is Successfully", updateTag, }; } @Delete(":id") async remove(@Param("id") id: string) { const deleteTag = await this.tagService.remove(+id); return { StatusCode: HttpStatus.OK, Message: "Delete is successfully", deleteTag, }; } }
NatSokneng/blog-post
src/users/users.module.ts
import { Module } from '@nestjs/common'; import { UsersService } from './users.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { UserRepository } from './repositories/user.repository'; import { JwtModule } from '@nestjs/jwt'; @Module({ imports: [TypeOrmModule.forFeature([UserRepository]), JwtModule.register({ secret: 'My random secret key never let others', signOptions: { expiresIn: '1h', }, }) ], providers: [UsersService], exports: [TypeOrmModule] }) export class UsersModule {}
NatSokneng/blog-post
src/post/repositories/post.repository.ts
import { EntityRepository, Repository } from "typeorm"; import { PostEntity } from "../entities/post.entity"; @EntityRepository(PostEntity) export class PostRepository extends Repository<PostEntity> { getOneDetailByPostId(id: number) { const query = this.createQueryBuilder("PostEntity"); query.leftJoinAndSelect("PostEntity.categories", "Category"); query.where("PostEntity.id = :postId", { postId: id }); return query.getOne(); } getAllPost() { const query = this.createQueryBuilder("PostEntity"); query.leftJoinAndSelect("PostEntity.categories", "Category"); return query.getMany(); } }
FlashHand/rig-test-1
index.d.ts
<reponame>FlashHand/rig-test-1<filename>index.d.ts declare module 'rig-test-1' { export const hello: () => void }
jkogut/simple-python-rest-api-v1
deployment/pulumi/index.ts
import * as pulumi from "@pulumi/pulumi"; import * as k8s from "@pulumi/kubernetes"; // lets take image from pulumi config let config = new pulumi.Config(); let appImage = config.require("appImage"); // testapp container, replicated 1 time. const appName = "pyapi"; const appLabels = { app: appName }; const testapp = new k8s.apps.v1beta1.Deployment(appName, { spec: { selector: { matchLabels: appLabels }, replicas: 1, template: { metadata: { labels: appLabels }, spec: { containers: [ { name: appName, image: appImage, resources: { requests: { cpu: "50m", memory: "100Mi" } }, ports: [{ containerPort: 5002 }] }] } } } }); // allocate an IP to the testapp Deployment. const frontend = new k8s.core.v1.Service(appName, { metadata: { labels: testapp.spec.apply(spec => spec.template.metadata.labels) }, spec: { type: "LoadBalancer", ports: [{ port: 80, targetPort: 5002, protocol: "TCP" }], selector: appLabels } }); // when "done", this will print the public IP. export let frontendIp = frontend.status.apply(status => status.loadBalancer.ingress[0].ip);
anakreon/awCrypt
src/cipher/morse.ts
export const encode = (plaintext: string): string => { return plaintext.trim() .toLowerCase() .split(textSeparator.word) .map(encodeTextWord) .join(morseSeparator.word); }; export const decode = (ciphertext: string): string => { return ciphertext.trim() .toLowerCase() .split(morseSeparator.word) .map(decodeMorseWord) .join(textSeparator.word); }; const encodeTextWord = (plaintextWord: string): string => { return plaintextWord .split(textSeparator.character) .map(encodeTextCharacter) .join(morseSeparator.character); }; const decodeMorseWord = (morseWord: string): string => { return morseWord .split(morseSeparator.character) .map(decodeMorseCharacter) .join(textSeparator.character); }; const decodeMorseCharacter = (morseCharacter: string): string => { return MORSE_CODE_DECODE[morseCharacter]; }; const encodeTextCharacter = (plaintextCharacter: string): string => { return MORSE_CODE_ENCODE[plaintextCharacter]; }; interface Separator { word: string; character: string; } const morseSeparator: Separator = { word: ' / ', character: ' ' }; const textSeparator: Separator = { word: ' ', character: '' }; const MORSE_CODE_ENCODE: { [plaintextCharacter: string]: string } = { "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-", "w": ".--", "x": "-..-", "y": "-.--", "z": "--..", ".": ".-.-.-", ",": "--..--", "?": "..--..", "!": "-.-.--", "-": "-....-", "/": "-..-.", "@": ".--.-.", "(": "-.--.", ")": "-.--.-" }; const MORSE_CODE_DECODE: { [plaintextCharacter: string]: string } = Object.keys(MORSE_CODE_ENCODE) .reduce((reverseMap: { [plaintextCharacter: string]: string }, textCharacter: string) => { const morseCharacter = MORSE_CODE_ENCODE[textCharacter]; reverseMap[morseCharacter] = textCharacter; return reverseMap; }, {});
anakreon/awCrypt
src/cipher/substitution.ts
<filename>src/cipher/substitution.ts export const encode = (plaintext: string, keyword: string): string => { return new CharcodeShiftEncoder(keyword).convert(plaintext); }; export const decode = (ciphertext: string, keyword: string): string => { return new CharcodeShiftDecoder(keyword).convert(ciphertext); }; abstract class CharcodeShiftConverter { protected alphabet: string[] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.toUpperCase().split(''); protected cipherAlphabet: string[]; constructor (keyword: string) { this.cipherAlphabet = this.buildCipherAlphabet(keyword); } private buildCipherAlphabet (keyword: string): string[] { const cipherAlphabet = Array.from(new Set(keyword.split(''))); const lastLetter = cipherAlphabet[cipherAlphabet.length - 1]; const lastLetterIndex = this.alphabet.indexOf(lastLetter); for (var i = 0, len = this.alphabet.length; i < len; ++i) { const index = (lastLetterIndex + i + 1) % 26; if (!cipherAlphabet.includes(this.alphabet[index])) { cipherAlphabet.push(this.alphabet[index]); } } return cipherAlphabet; }; public convert (originalCharacters: string): string { const formattedOriginalCharacters = this.formatCharactersForConversion(originalCharacters); let targetCharacters = ''; for (var i = 0, len = formattedOriginalCharacters.length; i < len; ++i) { const characterToConvert = formattedOriginalCharacters[i]; targetCharacters += this.convertCharacter(characterToConvert); } return targetCharacters; } private formatCharactersForConversion (originalCharacters: string): string { const originalCharactersUpperCase = originalCharacters.toUpperCase(); if (this.hasNonAlphabeticalCharacters(originalCharactersUpperCase)) { throw 'invalid input - alphabetical characters only'; } return originalCharactersUpperCase; } protected hasNonAlphabeticalCharacters (testString: string): boolean { return !/^[A-Z ]*$/.test(testString) } protected abstract convertCharacter (originalCharacter: string): string; } class CharcodeShiftEncoder extends CharcodeShiftConverter { private startFromCharacterCode: number = 'A'.charCodeAt(0); protected convertCharacter (originalCharacter: string): string { const originalCharacterNumberInAlphabet = originalCharacter.charCodeAt(0) - this.startFromCharacterCode; return this.cipherAlphabet[originalCharacterNumberInAlphabet] || originalCharacter; } } class CharcodeShiftDecoder extends CharcodeShiftConverter { protected convertCharacter (originalCharacter: string): string { const indexInAlphabet = this.cipherAlphabet.indexOf(originalCharacter); return this.alphabet[indexInAlphabet]; } }
anakreon/awCrypt
src/cipher/charcodeShift.ts
<reponame>anakreon/awCrypt export const encode = (plaintext: string, key: number): string => { return new CharcodeShiftEncoder().convert(plaintext, key); }; export const decode = (ciphertext: string, key: number): string => { return new CharcodeShiftDecoder().convert(ciphertext, key); }; abstract class CharcodeShiftConverter { public convert (originalCharacters: string, key: number): string { let targetCharacters = ''; for (var i = 0, len = originalCharacters.length; i < len; ++i) { const characterToConvert = originalCharacters[i]; targetCharacters += this.convertCharacter(characterToConvert, key); } return targetCharacters; } private convertCharacter (originalCharacter: string, key: number): string { const originalCharacterCode = originalCharacter.charCodeAt(0); const targetCharacterCode = this.getTargetCharacterCode(originalCharacterCode, key); return String.fromCharCode(targetCharacterCode); } protected abstract getTargetCharacterCode (originalCharacterCode: number, key: number): number; } class CharcodeShiftEncoder extends CharcodeShiftConverter { protected getTargetCharacterCode (originalCharacterCode: number, key: number): number { return originalCharacterCode + key; } } class CharcodeShiftDecoder extends CharcodeShiftConverter { protected getTargetCharacterCode (originalCharacterCode: number, key: number): number { return originalCharacterCode - key; } }
anakreon/awCrypt
src/cipher/base64.ts
<filename>src/cipher/base64.ts export const encode = (plaintext: string) => { return new Base64Encoder().convert(plaintext); }; export const decode = (ciphertext: string) => { return new Base64Decoder().convert(ciphertext); }; abstract class Base64Converter { protected abstract originalCharacterBatchSize: number; protected abstract targetCharacterBatchSize: number; protected abstract specialCharacters: string[]; protected abstract originalBitsPerByte: number; protected abstract targetBitsPerByte: number; protected indexTable = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' ]; public convert (originalCharacters: string): string { let targetCharacters = ''; for (var i = 0, len = originalCharacters.length; i < len; i += this.originalCharacterBatchSize) { const originalCharactersBatch = originalCharacters.substr(i, this.originalCharacterBatchSize); targetCharacters += this.convertCharactersBatch(originalCharactersBatch); } return targetCharacters; } private convertCharactersBatch (originalCharacters: string): string { const originalCharacterBytes = this.convertOriginalCharactersToBytes(originalCharacters) + this.getSupplementDigits(originalCharacters); const targetCharacters = this.convertCharacterBytesToTargetCharacters(originalCharacterBytes); const paddingCharacters = this.generatePaddingCharacters(originalCharacters); return targetCharacters + paddingCharacters; } private convertOriginalCharactersToBytes (characters: string): string { return characters.split('') .filter((character: string) => !this.specialCharacters.includes(character)) .map((character: string) => this.convertOriginalCharacterToByte(character)) .join(''); } private convertCharacterBytesToTargetCharacters (originalCharacterBytes: string): string { const characterCountToConvert = Math.floor(originalCharacterBytes.length / this.targetBitsPerByte); let targetCharacters = ''; for (var i = 0; i < characterCountToConvert; ++i) { const byte = originalCharacterBytes.substr(i * this.targetBitsPerByte, this.targetBitsPerByte); targetCharacters += this.convertCharacterByteToTargetCharacter(byte); } return targetCharacters; } protected abstract getSupplementDigits (originalCharacters: string): string; protected abstract generatePaddingCharacters (originalCharacters: string): string; protected abstract convertOriginalCharacterToByte (character: string): string; protected abstract convertCharacterByteToTargetCharacter (byte: string): string; } class Base64Encoder extends Base64Converter { protected originalCharacterBatchSize: number = 3; protected targetCharacterBatchSize: number = 4; protected specialCharacters: string[] = []; protected originalBitsPerByte: number = 8; protected targetBitsPerByte: number = 6; protected getSupplementDigits (originalCharacters: string): string { return '00'.repeat(this.originalCharacterBatchSize - originalCharacters.length); } protected generatePaddingCharacters (originalCharacters: string): string { return '='.repeat(this.originalCharacterBatchSize - originalCharacters.length); } protected convertOriginalCharacterToByte (character: string): string { const binaryCharCode = character.charCodeAt(0).toString(2); return binaryCharCode.padStart(this.originalBitsPerByte, '0'); } protected convertCharacterByteToTargetCharacter (byte: string): string { const index = parseInt(byte, 2); return this.indexTable[index]; } } class Base64Decoder extends Base64Converter { protected originalCharacterBatchSize: number = 4; protected targetCharacterBatchSize: number = 3; protected specialCharacters: string[] = ['=']; protected originalBitsPerByte: number = 6; protected targetBitsPerByte: number = 8; protected getSupplementDigits (originalCharacters: string): string { return ''; } protected generatePaddingCharacters (originalCharacters: string): string { return ''; } protected convertOriginalCharacterToByte (character: string): string { const indexCode = this.getIndexOfBase64Character(character); const binaryIndexCode = indexCode.toString(2); return binaryIndexCode.padStart(this.originalBitsPerByte, '0'); } private getIndexOfBase64Character (character: string): number { return this.indexTable.findIndex((value: string) => value === character); } protected convertCharacterByteToTargetCharacter (byte: string): string { const charCode = parseInt(byte, 2); return String.fromCharCode(charCode); } }
anakreon/awCrypt
src/index.ts
import { Ascii85, Base64, Caesar, CharcodeShift, Morse, RailFence, Substitution } from './types'; import * as _ascii85 from './cipher/ascii85'; import * as _base64 from './cipher/base64'; import * as _caesar from './cipher/caesar'; import * as _charcodeShift from './cipher/charcodeShift'; import * as _morse from './cipher/morse'; import * as _railFence from './cipher/railFence'; import * as _substitution from './cipher/substitution'; export const ascii85: Ascii85 = _ascii85; export const base64: Base64 = _base64; export const caesar: Caesar = _caesar; export const charcodeShift: CharcodeShift = _charcodeShift; export const morse: Morse = _morse; export const railFence: RailFence = _railFence; export const substitution: Substitution = _substitution;
anakreon/awCrypt
src/types.ts
export interface Ascii85 { encode: (inputText: string) => string; decode: (inputText: string) => string; } export interface Base64 { encode: (inputText: string) => string; decode: (inputText: string) => string; } export interface Caesar { encode: (plaintext: string, key: number) => string; decode: (ciphertext: string, key: number) => string; } export interface CharcodeShift { encode: (plaintext: string, key: number) => string; decode: (ciphertext: string, key: number) => string; } export interface Morse { encode: (plaintext: string) => string; decode: (ciphertext: string) => string; } export interface RailFence { encode: (plaintext: string, numberOfRails: number) => string; decode: (ciphertext: string, numberOfRails: number) => string; } export interface Substitution { encode: (plaintext: string, keyword: string) => string; decode: (ciphertext: string, keyword: string) => string; }
anakreon/awCrypt
src/cipher/ascii85.ts
export const encode = (plaintext: string) => { return new Ascii85Encoder().convert(plaintext); }; export const decode = (ciphertext: string) => { return new Ascii85Decoder().convert(ciphertext); }; class Ascii85Encoder { private originalBitsPerByte: number = 8; private originalCharacterBatchSize: number = 4; private targetCharacterBatchSize: number = 5; public convert (originalCharacters: string): string { let targetCharacters = ''; for (var i = 0, len = originalCharacters.length; i < len; i += this.originalCharacterBatchSize) { const originalCharactersBatch = originalCharacters.substr(i, this.originalCharacterBatchSize); targetCharacters += this.convertCharactersBatch(originalCharactersBatch, i, originalCharacters); } return '<~' + targetCharacters + '~>'; } private convertCharactersBatch (originalCharactersBatch: string, index: number, originalCharacters: string): string { const originalCharacterBytes = this.convertOriginalCharactersToBytes(originalCharactersBatch) + this.getSupplementDigits(originalCharactersBatch); const targetCharacters = this.convertCharacterBytesToTargetCharacters(originalCharacterBytes, originalCharactersBatch); return targetCharacters; } private convertCharacterBytesToTargetCharacters (originalCharacterBytes: string, originalCharactersBatch: string): string { if (this.isFullBatch(originalCharactersBatch)) { return this.convertFullBatchCharacterBytesToTargetCharacters(originalCharacterBytes); } else { return this.convertLastBatchCharacterBytesToTargetCharacters(originalCharacterBytes, originalCharactersBatch); } } private convertFullBatchCharacterBytesToTargetCharacters (originalCharacterBytes: string): string { const decimalValue = parseInt(originalCharacterBytes, 2); if (decimalValue) { let ascii85Characters = this.getAscii85Characters(decimalValue); return Array(this.targetCharacterBatchSize - ascii85Characters.length + 1).join('!') + ascii85Characters; } else { return 'z'; } } private convertLastBatchCharacterBytesToTargetCharacters (originalCharacterBytes: string, originalCharactersBatch: string): string { const decimalValue = parseInt(originalCharacterBytes, 2); if (decimalValue) { let ascii85Characters = this.getAscii85Characters(decimalValue); return ascii85Characters.substring(0, ascii85Characters.length - (this.originalCharacterBatchSize - originalCharactersBatch.length)); } else { return Array(originalCharactersBatch.length + 2).join('!'); } } private isFullBatch (originalCharactersBatch: string): boolean { return originalCharactersBatch.length === this.originalCharacterBatchSize; } private convertOriginalCharactersToBytes (characters: string): string { return characters.split('') .map((character: string) => this.convertOriginalCharacterToByte(character)) .join(''); } private getSupplementDigits (originalCharactersBatch: string): string { return '0'.repeat((this.originalCharacterBatchSize - originalCharactersBatch.length) * this.originalBitsPerByte); } private convertOriginalCharacterToByte (character: string): string { const binaryCharCode = character.charCodeAt(0).toString(2); return binaryCharCode.padStart(this.originalBitsPerByte, '0'); } private getAscii85Characters (decimalValue: number): string { let ascii85 = ''; for (var index = decimalValue; index > 1; index /= 85) { const ascii85Character = this.getAscii85Character(index % 85); ascii85 = ascii85Character + ascii85; } return ascii85; } private getAscii85Character (divisionRemainder: number): string { const ascii85StartIndex = 33; return String.fromCharCode(divisionRemainder + ascii85StartIndex); } } class Ascii85Decoder { private originalCharacterBatchSize: number = 5; public convert (originalCharacters: string): string { const originalCharactersClean = this.stripEncodedTagsAndWhitespaces(originalCharacters); let targetCharacters = ''; let index = 0; while (index < originalCharactersClean.length) { if (originalCharactersClean[index] === 'z') { targetCharacters += '\u0000\u0000\u0000\u0000'; index++; } else { const originalCharactersBatch = originalCharactersClean.substr(index, this.originalCharacterBatchSize); targetCharacters += this.convertCharactersBatch(originalCharactersBatch); index += this.originalCharacterBatchSize; } } return targetCharacters; } private convertCharactersBatch (originalCharactersBatch: string): string { const originalCharactersBatchPadded = originalCharactersBatch.padEnd(this.originalCharacterBatchSize, 'u'); const decimalValue = this.convertAscii85CharsToDecimal(originalCharactersBatchPadded); const originalCharacterBytes = decimalValue.toString(2).padStart(32, '0'); let targetCharacters = this.convertCharacterBytesToTargetCharacters(originalCharacterBytes); return targetCharacters.substring(0, targetCharacters.length - (this.originalCharacterBatchSize - originalCharactersBatch.length)); } private stripEncodedTagsAndWhitespaces (inputString: string): string { return inputString .substring(2, inputString.length - 2) .replace(/\s/g, ''); } private convertAscii85CharsToDecimal (ascii85Value: string): number { let decimalValue = 0; for (var i = 0; i < ascii85Value.length; ++i) { decimalValue += (ascii85Value.charCodeAt(i) - 33) * Math.pow(85, ascii85Value.length - 1 - i); } return decimalValue; } private convertCharacterBytesToTargetCharacters (originalCharacterBytes: string): string { let decodedChars = ''; for (var i = 0; i < originalCharacterBytes.length; i += 8) { const charCode = parseInt(originalCharacterBytes.substring(i, i + 8), 2); decodedChars += String.fromCharCode(charCode); } return decodedChars; } }
anakreon/awCrypt
src/cipher/railFence.ts
<reponame>anakreon/awCrypt export const encode = (plaintext: string, numberOfRails: number): string => { let ciphertext = ''; const loopLength = 2 * (numberOfRails - 1); const totalLoops = plaintext.length / loopLength; for (var railNo = 0; railNo < numberOfRails; ++railNo) { for (var loopNo = 0; loopNo < totalLoops; ++loopNo) { const letterIndexOne = 2 * (numberOfRails - 1) * loopNo + railNo; if (plaintext[letterIndexOne]) { ciphertext += plaintext[letterIndexOne]; } const letterIndexTwo = 2 * (numberOfRails - 1) * loopNo + 2 * (numberOfRails - 1) - railNo; const isIndexInRange = letterIndexTwo > 2 * (numberOfRails - 1) * loopNo && letterIndexTwo < 2 * (numberOfRails - 1) * (loopNo + 1); if (plaintext[letterIndexTwo] && letterIndexOne !== letterIndexTwo && isIndexInRange) { ciphertext += plaintext[letterIndexTwo]; } } } return ciphertext; }; export const decode = (ciphertext: string, numberOfRails: number): string => { const loopLength = 2 * (numberOfRails - 1); const baseLineLength = Math.floor(ciphertext.length / loopLength); const remainingLength = ciphertext.length % loopLength; const rails = []; let totalRailLength = 0; for (var railNo = 0; railNo < numberOfRails; ++railNo) { const currentRailLength = getCurrentRailLength(railNo, numberOfRails, baseLineLength, remainingLength); rails[railNo] = ciphertext.substr(totalRailLength, currentRailLength); totalRailLength += currentRailLength; } let plaintext = ''; for (var loop = 0, len = rails[0].length * 2; loop < len; ++loop) { if (loop % 2 === 0) { plaintext += loopAcrossRailsInOrder(rails); } else { plaintext += loopAcrossRailsInReversedOrder(rails); } } return plaintext; }; const getCurrentRailLength = (railNo: number, numberOfRails: number, baseLineLength: number, remainingLength: number) => { let currentRailLength = baseLineLength; if (railNo < remainingLength) { currentRailLength++; } const secCount = remainingLength - numberOfRails; const isInInterval = railNo < numberOfRails - 1 && railNo > numberOfRails - 2 - secCount; if (secCount && isInInterval) { currentRailLength++; } if (railNo !== 0 && railNo !== (numberOfRails - 1)) { currentRailLength += baseLineLength; } return currentRailLength; }; const loopAcrossRailsInOrder = (rails: string[]) => { let plaintextPart = ''; for (var railNo = 0; railNo < rails.length - 1; ++railNo) { plaintextPart += pullNextRailValue(railNo, rails); } return plaintextPart; }; const loopAcrossRailsInReversedOrder = (rails: string[]) => { let plaintextPart = ''; for (var railNo = rails.length - 1; railNo > 0; --railNo) { plaintextPart += pullNextRailValue(railNo, rails); } return plaintextPart; }; const pullNextRailValue = (railNo: number, rails: string[]) => { let railValue = ''; if (typeof rails[railNo][0] !== 'undefined') { railValue += rails[railNo][0]; rails[railNo] = rails[railNo].substr(1); } return railValue; };
anakreon/awCrypt
src/cipher/caesar.ts
export const encode = (plaintext: string, key: number): string => { return new CaesarEncoder().convert(plaintext, key); }; export const decode = (ciphertext: string, key: number): string => { return new CaesarDecoder().convert(ciphertext, key); }; abstract class CaesarConverter { private charactersToIgnore: string[] = [' ']; private startFromCharacterCode: number = 'A'.charCodeAt(0); protected alphabetLength: number = 26; public convert (originalCharacters: string, key: number): string { const formattedOriginalCharacters = this.formatCharactersForConversion(originalCharacters); let targetCharacters = ''; for (var i = 0, len = formattedOriginalCharacters.length; i < len; ++i) { const characterToConvert = formattedOriginalCharacters[i]; targetCharacters += this.convertCharacter(characterToConvert, key); } return this.formatCharactersAfterConversion(targetCharacters); } private formatCharactersForConversion (originalCharacters: string): string { const originalCharactersUpperCase = originalCharacters.toUpperCase(); if (this.hasNonAlphabeticalCharacters(originalCharactersUpperCase)) { throw 'invalid input - alphabetical characters only'; } return originalCharactersUpperCase; } protected hasNonAlphabeticalCharacters (testString: string): boolean { return !/^[A-Z ]*$/.test(testString) } private convertCharacter (originalCharacter: string, key: number): string { if (this.charactersToIgnore.includes(originalCharacter)) { return originalCharacter; } const originalCharacterNumberInAlphabet = this.getOriginalCharacterNumberInAlphabet(originalCharacter); const targetCharacterNumberInAlphabet = this.getTargetCharacterNumberInAlphabet(originalCharacterNumberInAlphabet, key); const targetCharacterCode = this.startFromCharacterCode + targetCharacterNumberInAlphabet; return String.fromCharCode(targetCharacterCode); } private getOriginalCharacterNumberInAlphabet (originalCharacter: string): number { return originalCharacter.charCodeAt(0) - this.startFromCharacterCode; } protected abstract getTargetCharacterNumberInAlphabet (originalCharacterNumberInAlphabet: number, key: number): number; protected abstract formatCharactersAfterConversion (targetCharacters: string): string; } class CaesarEncoder extends CaesarConverter { protected getTargetCharacterNumberInAlphabet (originalCharacterNumberInAlphabet: number, key: number): number { return (this.alphabetLength + originalCharacterNumberInAlphabet + key) % 26; } protected formatCharactersAfterConversion (targetCharacters: string): string { return targetCharacters; } } class CaesarDecoder extends CaesarConverter { protected getTargetCharacterNumberInAlphabet (originalCharacterNumberInAlphabet: number, key: number): number { return (this.alphabetLength + originalCharacterNumberInAlphabet - key) % 26; } protected formatCharactersAfterConversion (targetCharacters: string): string { return targetCharacters.toLowerCase(); } }
gpunalkar/quickstart
src/app/config/app.routes.ts
<gh_stars>0 import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { UserComponent } from '../components/user.component/user.component'; import { AboutComponent } from '../components/about.component/about.component'; const appRoutes:Routes = [ { path: "", component: UserComponent }, { path: "about", component: AboutComponent } ]; export const Routing:ModuleWithProviders = RouterModule.forRoot(appRoutes);
gpunalkar/quickstart
src/app/components/user.component/user.component.ts
<filename>src/app/components/user.component/user.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { PostServices } from '../../services/post.services/post.services'; @Component({ selector: 'user', templateUrl: `./user.component.html`, providers:[PostServices] }) export class UserComponent { name: string; address: address; myPost: myPost[]; constructor(private router: Router, private postServices:PostServices) { this.name = "This is contructor text"; // this.address.street = 'Nagar Road'; // this.address.city = 'Pune'; this.postServices.getPost().subscribe( post => {this.myPost = post}) } testFunction() { this.router.navigateByUrl('about'); } } interface address { street: string, city: string } interface myPost{ id :number, title: string, body: string }
miguelcjalmeida/vagante-dsmod
src/tools/create-lottery-picker.ts
<reponame>miguelcjalmeida/vagante-dsmod import { INextOf, nextItemFactory } from '../manipulators/next-item-factory' import { shuffleArray } from './shuffle-array' export interface ILotteryStack<T> { proportion: number possibilities: T[] } export interface ILottery<T> { [key: string]: ILotteryStack<T> } export function createLotteryPicker<T>( lotteryConfig: ILottery<T>, resetLotteryAction?: (list: T[]) => void, ) : ILotteryNextOf<T> { const lottery : T[] = [] for (const stackName in lotteryConfig) { const stack = lotteryConfig[stackName] stack.possibilities.forEach((p) => { for (let i = 0; i < stack.proportion; i += 1) { lottery.push(p) } }) } shuffleArray(lottery) shuffleArray(lottery) shuffleArray(lottery) const reset = resetLotteryAction ? resetLotteryAction : shuffleArray const factory = nextItemFactory(lottery, reset) as ILotteryNextOf<T> factory.lottery = lotteryConfig return factory } export interface ILotteryNextConfig<T> { lottery: ILottery<T> } export type ILotteryNextOf<T> = INextOf<T> & ILotteryNextConfig<T>
miguelcjalmeida/vagante-dsmod
src/transformators/merchant-intermission/replace-orbeck-items.ts
<filename>src/transformators/merchant-intermission/replace-orbeck-items.ts import { IRoomBlock } from '../../rooms/context' import { IItemEntity } from '../../rooms/entities' import { findRoomEntities } from '../../finders/find-room-entities' import { createLotteryPicker } from '../../tools/create-lottery-picker' import { EntityTypes, ItemTypes } from '../../rooms/types' import { shuffleArray } from '../../tools/shuffle-array' const nextScroll = createLotteryPicker<[ItemTypes, number]>( { common: { proportion: 3 * (8 - 2), possibilities: [ [ItemTypes.ChaosScroll, 5], [ItemTypes.RechargeScroll, 1], ], }, uncommon: { proportion: 2 * (8 - 2), possibilities: [ [ItemTypes.EnchantScroll, 1], [ItemTypes.IdentifyScroll, 2], ], }, rare: { proportion: 1 * (8 - 4), possibilities: [ [ItemTypes.MagicMappingScroll, 1], [ItemTypes.UncurseScroll, 1], [ItemTypes.TeleportScroll, 3], [ItemTypes.JumpScroll, 3], ], }, }, shuffleArray, ) export function replaceOrbeckItems(placeholders: IItemEntity[]) { placeholders.forEach((x) => { const next = nextScroll() x.itemType = next[0] x.count = next[1] }) }
miguelcjalmeida/vagante-dsmod
src/modder/get-all-transformators.ts
<filename>src/modder/get-all-transformators.ts import { characterSelection } from '../transformators/character-selection' import { itemsCreator } from '../transformators/items-creator' import { merchantIntermission } from '../transformators/merchant-intermission' import { cloneDsMod } from '../transformators/clone-dsmod' import { removeDoors } from '../transformators/remove-doors' import { fairyReplace } from '../transformators/fairy-replace' import { versioning } from '../transformators/versioning' import { roomInstances } from '../transformators/room-instances' import { labelFirekeepr } from '../transformators/label-firekeeper' export const getAllTransformators = () => { return [ cloneDsMod, roomInstances, itemsCreator, merchantIntermission, characterSelection, removeDoors, labelFirekeepr, fairyReplace, versioning, // recalcCharSelection, // partyUpMod, // saveIntoTemplate, // scarceland, ] }
miguelcjalmeida/vagante-dsmod
src/item-builder/next-equipment-picker.ts
import { createLotteryPicker } from '../tools/create-lottery-picker' import { equipmentProfiles, EquipmentSubType, EquipmentType } from './equipment-profile' import { ItemTypes } from '../rooms/types' import { shuffleArray } from '../tools/shuffle-array' export const nextEquipmentPicker = createLotteryPicker( { weapons: { proportion: 1, possibilities: equipmentProfiles.filter(x => x.type === EquipmentType.PrimaryWeapon), }, bows: { proportion: 9, possibilities: equipmentProfiles.filter(x => x.subType === EquipmentSubType.Bow), }, armor: { proportion: 1, possibilities: equipmentProfiles.filter( x => x.type !== EquipmentType.PrimaryWeapon && x.type !== EquipmentType.SecondaryWeapon), }, rings: { proportion: 1, possibilities: equipmentProfiles.filter( x => x.type === EquipmentType.Ring || x.type === EquipmentType.Amulet, ), }, boomerang: { proportion: 3, possibilities: [equipmentProfiles[ItemTypes.Boomerang]], }, }, shuffleArray, )
miguelcjalmeida/vagante-dsmod
src/transformators/merchant-intermission/replace-cornyx-items.ts
<reponame>miguelcjalmeida/vagante-dsmod<filename>src/transformators/merchant-intermission/replace-cornyx-items.ts import { IItemEntity, IBookEntity } from '../../rooms/entities' import { createLotteryPicker } from '../../tools/create-lottery-picker' import { BookTypes, AttributeTypes, ItemTypes } from '../../rooms/types' import { shuffleArray } from '../../tools/shuffle-array' import { priceUp } from '../../item-builder/price-up' import { equipmentProfiles, EquipmentSubType, EquipmentType } from '../../item-builder/equipment-profile' import { improveEquipAttr } from '../../item-builder/improve-equipment-attr' import { improveEquipment } from '../../item-builder/improve-equipment' const nextBook = createLotteryPicker( { book: { proportion: 1, possibilities: [ { skill: BookTypes.FireShield, cost: 1 }, { skill: BookTypes.Fireball, cost: 3 }, { skill: BookTypes.FlamePillar, cost: 2 }, ], }, }, ) const nextEquip = createLotteryPicker({ melee: { proportion: 1, possibilities: equipmentProfiles .filter(x => x.type === EquipmentType.PrimaryWeapon) .map(x => improveEquipAttr({ ...x }, AttributeTypes.AllWeaponBurn, 0)), }, bow: { proportion: 9, possibilities: equipmentProfiles .filter(x => x.subType === EquipmentSubType.Bow) .map(x => improveEquipAttr({ ...x }, AttributeTypes.AllWeaponBurn, 1)), }, armor: { proportion: 1, possibilities: equipmentProfiles .filter(x => x.subType === EquipmentSubType.Armor) .map(x => improveEquipAttr({ ...x }, AttributeTypes.ResistFire, 1)), }, accessory: { proportion: 1, possibilities: equipmentProfiles .filter(x => x.subType === EquipmentSubType.Accessory) .map(x => improveEquipAttr({ ...x }, AttributeTypes.FireWalk, 1)), }, }) export function replaceCornyxItems(placeholders: IItemEntity[], lvl: number) { placeholders.forEach((x : IBookEntity, i) => { if (i >= 2) return const equip = nextEquip() x.itemType = equip.itemType x.attributes = equip.attributes improveEquipment(x, lvl) }) placeholders.forEach((x : IBookEntity, i) => { if (i < 2) return const book = nextBook() x.itemType = ItemTypes.Book x.skill = book.skill priceUp(x, book.cost) }) }
miguelcjalmeida/vagante-dsmod
src/build.ts
<gh_stars>1-10 import { applyMod } from './modder/apply-mod' applyMod()
miguelcjalmeida/vagante-dsmod
src/transformators/remove-doors.ts
<gh_stars>1-10 import { IRoomContext, IRoomBlock, IActSpecification, IRoomAct } from '../rooms/context' import { RoomNames } from '../rooms/names'; export const removeDoors = (ctx: IRoomContext) => { console.log('removing doors') ctx.acts.forEach((act) => { if (act._comment === RoomNames.Tutorial) return for (const i in act.rooms) { const room = act.rooms[i] room.forEach((block) => { removeDoorFromBlock(act, block) }) } }) } function removeDoorFromBlock(act: IRoomAct, block: IRoomBlock) { const tilesIndex = -1 block.tiles.forEach((rowTiles) => { for (let i = 0; i < rowTiles.length; i += 6) { const midTileIndex = i + 3 const midTile = rowTiles[midTileIndex] if (midTile !== 0 && midTile !== 1) continue rowTiles[midTileIndex] = -1 } }) }
miguelcjalmeida/vagante-dsmod
src/transformators/clone-dsmod.ts
import { IRoomContext } from '../rooms/context' import { findAct } from '../finders/find-act' import { RoomNames } from '../rooms/names' import { dsmod } from '../manipulators/get-template' export const cloneDsMod = (context: IRoomContext) => { cloneDsModRoomIntoRoom(context, RoomNames.ACT_ONE) cloneDsModRoomIntoRoom(context, RoomNames.ACT_TWO) cloneDsModRoomIntoRoom(context, RoomNames.ACT_THREE) cloneDsModRoomIntoRoom(context, RoomNames.ACT_FOUR) cloneDsModRoomIntoRoom(context, RoomNames.BRANCH_ONE) cloneDsModRoomIntoRoom(context, RoomNames.BRANCH_TWO) cloneDsModRoomIntoRoom(context, RoomNames.BRANCH_THREE) cloneDsModRoomIntoRoom(context, RoomNames.BRANCH_FOUR) cloneDsModRoomIntoRoom(context, RoomNames.FinalFight) cloneDsModRoomIntoRoom(context, RoomNames.Intermission) } function cloneDsModRoomIntoRoom(context: IRoomContext, roomName: RoomNames) { cloneSpecs(context, roomName) const room = findAct(context, roomName) if (!room) return const dsModRoom = findAct(dsmod, roomName) if (!dsModRoom) return room.rooms = dsModRoom.rooms } function cloneSpecs(context: IRoomContext, roomName: RoomNames) { const specs = context.act_specifications.find(x => x._comment === roomName) const dsmodSpecs = dsmod.act_specifications.find(x => x._comment === roomName) if (!specs || !dsmodSpecs) return specs.width = dsmodSpecs.width specs.height = dsmodSpecs.height }
miguelcjalmeida/vagante-dsmod
src/transformators/merchant-intermission/replace-anri-items.ts
import { IBookEntity, IItemEntity } from '../../rooms/entities' import { AttributeTypes, ItemTypes } from '../../rooms/types' import { improveEquipment } from '../../item-builder/improve-equipment' import { createLotteryPicker } from '../../tools/create-lottery-picker' import { IEquipmentProfile, EquipmentSubType, EquipmentType } from '../../item-builder/equipment-profile' const sword : IEquipmentProfile = { itemType: ItemTypes.SteelSword, attributes: [ [AttributeTypes.CoinHeal, 0], [AttributeTypes.Luk, 1], ], subType: EquipmentSubType.Sword, type: EquipmentType.PrimaryWeapon, } const ring : IEquipmentProfile = { itemType: ItemTypes.EyeRing, attributes: [ [AttributeTypes.CoinHeal, 0], ], subType: EquipmentSubType.Accessory, type: EquipmentType.Ring, } const nextItem = createLotteryPicker({ equips: { proportion: 1, possibilities: [sword, ring], }, }) export function replaceAnriItems(placeholders: IItemEntity[], level: number) { placeholders.forEach((x : IBookEntity) => { const item = nextItem() x.itemType = item.itemType x.attributes = item.attributes improveEquipment(x, level) const foundLuk = x.attributes.find(x => x[0] === AttributeTypes.Luk) if (foundLuk) foundLuk[1] = foundLuk[1] * 2 }) }
miguelcjalmeida/vagante-dsmod
src/transformators/merchant-intermission/replace-andre-items.ts
import { equipmentProfiles, EquipmentType } from '../../item-builder/equipment-profile' import { EntityTypes } from '../../rooms/types' import { IItemEntity } from '../../rooms/entities' import { createLotteryPicker } from '../../tools/create-lottery-picker' import { shuffleArray } from '../../tools/shuffle-array' import { improveEquipment } from '../../item-builder/improve-equipment' const armor = equipmentProfiles.filter(x => x.type === EquipmentType.Armor) const boots = equipmentProfiles.filter(x => x.type === EquipmentType.Boots) const gloves = equipmentProfiles.filter(x => x.type === EquipmentType.Glove) const caps = equipmentProfiles.filter(x => x.type === EquipmentType.Cap) const nextArmor = createLotteryPicker({ armor: { proportion: 3, possibilities: armor } }) const nextBoot = createLotteryPicker({ boots: { proportion: 3, possibilities: boots } }) const nextGlove = createLotteryPicker({ gloves: { proportion: 3, possibilities: gloves } }) const nextCap = createLotteryPicker({ caps: { proportion: 3, possibilities: caps } }) export const nextAndreEquipPicker = createLotteryPicker( { all: { proportion: 1, possibilities: [ nextArmor, nextBoot, nextGlove, nextCap, ], }, }, shuffleArray, ) export function replaceAndreItems(placeholders: IItemEntity[], level: number) { placeholders.forEach((x) => { const equip = nextAndreEquipPicker()() x.itemType = equip.itemType x.cursed = false x.count = 1 x.attributes = equip.attributes x.type = EntityTypes.Item improveEquipment(x, level) }) }
miguelcjalmeida/vagante-dsmod
src/transformators/merchant-intermission/replace-gavlan-items.ts
<gh_stars>1-10 import { IItemEntity } from '../../rooms/entities' import { createLotteryPicker } from '../../tools/create-lottery-picker' import { AttributeTypes, ItemTypes } from '../../rooms/types' import { priceUp } from '../../item-builder/price-up' import { equipmentProfiles, EquipmentSubType, EquipmentType } from '../../item-builder/equipment-profile' import { improveEquipAttr } from '../../item-builder/improve-equipment-attr' import { improveEquipment } from '../../item-builder/improve-equipment' import { createUniqueLotteryPicker } from '../../tools/create-unique-lottery-picker' const nextEffect = createLotteryPicker( { effects: { proportion: 1, possibilities: [ AttributeTypes.PoisonReflect, AttributeTypes.ResistPoison, AttributeTypes.WeaponPoisonCoat, ], }, }, ) const nextEquip = createLotteryPicker({ melee: { proportion: 1, possibilities: equipmentProfiles.filter(x => x.type === EquipmentType.PrimaryWeapon), }, }) const nextRing = createLotteryPicker({ ring: { proportion: 1, possibilities: equipmentProfiles .filter(x => x.subType === EquipmentSubType.Accessory) .map(x => improveEquipAttr({ ...x }, AttributeTypes.Sta, 5)), }, }) const nextPotion = createLotteryPicker({ common: { proportion: 3, possibilities: [ { count: 3, potion: ItemTypes.PoisonPotion, cost: 1 }, ], }, rare: { proportion: 1, possibilities: [ { count: 1, potion: ItemTypes.PoisonResistPotion, cost: 3 }, ], }, }) export function replaceGavlanItems(placeholders: IItemEntity[], lvl: number) { placeholders.forEach((x, i) => { if (i <= 0) replaceRing(x, lvl) else if (i <= 2) replaceWeapon(x, lvl) else replacePotions(x, lvl) }) } function replaceWeapon(placeholder: IItemEntity, level: number) { const equip = { ...nextEquip() } improveEquipAttr(equip, nextEffect(), 1) improveEquipAttr(equip, AttributeTypes.WeaponStrongPoison, 1) placeholder.itemType = equip.itemType placeholder.attributes = equip.attributes improveEquipment(placeholder, level - 1) } function replaceRing(placeholder: IItemEntity, level: number) { const ring = nextRing() placeholder.itemType = ring.itemType placeholder.attributes = ring.attributes improveEquipment(placeholder, level, { enhanceCurrentStats: false, minCost: level, addStackable: false, addEffect: true, }) } function replacePotions(placeholder: IItemEntity, level: number) { const pot = nextPotion() placeholder.itemType = pot.potion placeholder.count = pot.count priceUp(placeholder, pot.cost) }
miguelcjalmeida/vagante-dsmod
src/item-builder/attributes-by-type.ts
import { AttributeTypes } from '../rooms/types' import { attributeProfiles, AttributeRestrictions, IAttributeProfile } from './attribute-profile' import { nextItemFactory, INextOf } from '../manipulators/next-item-factory' import { createLotteryPicker } from '../tools/create-lottery-picker' export interface AttributesByRestrictTo { [index: string]: IAttributeProfile[] } export interface NextAttributeByRestrictTo { [index: string]: INextOf<IAttributeProfile> } export const stackableAttributes = attributeProfiles .filter(x => x.stackable && x.restrictTo === AttributeRestrictions.None) export const basicAttributes = attributeProfiles .filter(x => x.basic) export const valueOneStackableAttribute = attributeProfiles .filter(x => x.stackable && x.cost === 1) export const effectAttributes = attributeProfiles .filter(x => !x.stackable && !x.basic) export const nonRestrictToEffectAttributes = effectAttributes .filter(x => x.restrictTo === AttributeRestrictions.None) export const weaponEffectAttributes = effectAttributes .filter( x => x.restrictTo === AttributeRestrictions.AllWeapon || x.restrictTo === AttributeRestrictions.Weapon) export const bowEffectAttributes = effectAttributes .filter( x => x.restrictTo === AttributeRestrictions.Bow || x.restrictTo === AttributeRestrictions.AllWeapon) export const otherRangedEffectAttributes = effectAttributes .filter(x => x.restrictTo === AttributeRestrictions.AllWeapon) export const nextStackableAttribute = lottery(stackableAttributes) export const nextBasicAttribute = lottery(basicAttributes) export const nextValueOneStackableAttribute = lottery(valueOneStackableAttribute) export const nextNonRestrictToEffectAttribute = lottery(nonRestrictToEffectAttributes) export const nextWeaponEffectAttributes = createLotteryPicker<IAttributeProfile>({ weapon: { proportion: 15, possibilities: weaponEffectAttributes.filter( x => x.type !== AttributeTypes.WeaponBlink), }, blink: { proportion: 1, possibilities: weaponEffectAttributes.filter( x => x.type === AttributeTypes.WeaponBlink), }, others: { proportion: 1, possibilities: nonRestrictToEffectAttributes, }, }) export const nextBowEffectAttribute = createLotteryPicker({ weapon: { proportion: 15, possibilities: bowEffectAttributes, }, others: { proportion: 1, possibilities: nonRestrictToEffectAttributes, }, }) export const nextOtherRangedEffectAttribute = createLotteryPicker({ weapon: { proportion: 10, possibilities: otherRangedEffectAttributes, }, others: { proportion: 1, possibilities: nonRestrictToEffectAttributes, }, }) // generics export const restrictAttributesByType : AttributesByRestrictTo = {} export const nextAttributeByRestrictTo : NextAttributeByRestrictTo = {} for (const index in AttributeRestrictions) { const restriction = <any>AttributeRestrictions[index] as AttributeRestrictions restrictAttributesByType[index] = effectAttributes.filter( x => x.restrictTo === restriction, ) nextAttributeByRestrictTo[index] = lottery([ ...restrictAttributesByType[index], ...nonRestrictToEffectAttributes, ]) } function lottery<T>(items: T[]) { return createLotteryPicker({ restrict: { possibilities: items, proportion: 4, }, }) }