repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
janCstoffregen/raeber-mit-generischer-suche
src/client/app/register/titelregister/register-titelregister.component.ts
/** * Created by <NAME> (rfbaumgartner) on 07.07.17. */ import { Component, Input, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { ActivatedRoute, Params, Router } from '@angular/router'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import { FulltextSearch } from '../../shared/utilities/knora-api-params'; import { AlphabeticalSortingService } from '../../shared/utilities/alphabetical-sorting.service'; @Component({ moduleId: module.id, selector: 'rae-register-titelregister', templateUrl: 'register-titelregister.component.html', styleUrls: [ 'register-titelregister.component.css' ], providers: [ AlphabeticalSortingService ] }) export class RegisterTitelregisterComponent implements OnInit { rsEntry: Array<any>; nHits: number; @Input() selectedTab: string; constructor(private http: Http, private route: ActivatedRoute, private router: Router, private sortingService: AlphabeticalSortingService) { } ngOnInit() { let searchParams = new FulltextSearch; searchParams.searchstring = 'e'; this.route.params .switchMap((params: Params) => this.http.get(searchParams.toString())) .map(response => response.json()) .subscribe((res: any) => { this.rsEntry = res.subjects; this.nHits = res.nhits; this.sortAlphabetically(); }); } // TODO: Sort alphabetically after init. How? sortAlphabetically() { this.rsEntry = this.rsEntry.sort((n1, n2) => { const k1 = this.sortingService.germanAlphabeticalSortKey(n1.value[ 0 ]); const k2 = this.sortingService.germanAlphabeticalSortKey(n2.value[ 0 ]); if (k1 > k2) { return 1; } if (k1 < k2) { return -1; } return 0; }); } sortChronologically() { // Sortiere nach obj_id bis eine interne Nummerierung da ist this.rsEntry = this.rsEntry.sort((n1, n2) => { const k1 = n1.obj_id; const k2 = n2.obj_id; if (k1 > k2) { return 1; } if (k1 < k2) { return -1; } return 0; }); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/fassung/fassung-diplomatisch/fassung-diplomatisch.component.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche /** * Created by <NAME> (rfbaumgartner) on 24.07.17. */ import { Component, Input } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-fassung-diplomatisch', templateUrl: 'fassung-diplomatisch.component.html' }) export class FassungDiplomatischComponent { @Input() pages: any; gewaehlteSchicht: string = 'schicht0'; }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/synopse/synopse.component.ts
/** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { ActivatedRoute, Params } from '@angular/router'; import { ExtendedSearch, KnoraProperty } from '../shared/utilities/knora-api-params'; @Component({ moduleId: module.id, selector: 'rae-synopse', templateUrl: 'synopse.component.html' }) export class SynopseComponent implements OnInit { poemsInSynopse: Array<any>; nHits: number; synopseTag: string; showText: boolean; viewMode: string; private sub: any; constructor(private http: Http, private route: ActivatedRoute) { this.showText = true; this.viewMode = 'grid'; } ngOnInit() { this.sub = this.route.params.subscribe(params => { this.synopseTag = params[ 'synopse' ]; }); // TODO Parameter anpassen let searchParams = new ExtendedSearch(); searchParams.filterByRestype = 'http://www.knora.org/ontology/text#Convolute'; searchParams.property = new KnoraProperty('http://www.knora.org/ontology/text#hasTitle', 'MATCH', this.synopseTag); searchParams.property = new KnoraProperty('http://www.knora.org/ontology/text#hasDescription', '!EQ', ' '); searchParams.showNRows = 500; this.route.params .switchMap((params: Params) => this.http.get(searchParams.toString())) .map(response => response.json()) .subscribe((res: any) => { this.poemsInSynopse = res.subjects; this.nHits = res.nhits; }); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/textgrid/textgrid.module.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche /** * Created by <NAME> (<EMAIL>) on 7/21/17. */ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MdButtonToggleModule, MdCardModule } from '@angular/material'; import { RouterModule } from '@angular/router'; import { DynamicPaging } from './paging.service'; import { TextgridComponent } from './textgrid.component'; @NgModule({ imports: [ CommonModule, MdButtonToggleModule, MdCardModule, RouterModule ], declarations: [ TextgridComponent ], providers: [ DynamicPaging ], exports: [ TextgridComponent ] }) export class TextgridModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/statisch/pdf-notizbuecher.component.ts
/** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-pdf-notizbuecher', templateUrl: 'pdf-notizbuecher.component.html' }) export class PdfNotizbuecherComponent { title = 'pdf-Dateien (Notizbuecher)'; creationDate = 'Donnerstag, 16 Februar 2017'; }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/fassung/fassung-routing.module.ts
<gh_stars>0 /** * Created by <NAME> (rfbaumgartner) on 05.07.17. */ import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { FassungComponent } from './fassung.component'; @NgModule({ imports: [ RouterModule.forChild([ { path: 'drucke/abgewandt-zugewandt/:konvolut/:fassung', component: FassungComponent }, { path: 'drucke/:konvolut/:fassung', component: FassungComponent }, { path: 'manuskripte/:konvolut/:fassung', component: FassungComponent }, { path: 'notizbuecher/notizbuch-divers/:konvolut/:fassung', component: FassungComponent }, { path: 'notizbuecher/:konvolut/:fassung', component: FassungComponent }, { path: 'typoskripte/typoskripte-sammlungen/:konvolut/:fassung', component: FassungComponent }, { path: 'typoskripte/:konvolut/:fassung', component: FassungComponent }, { path: 'material/:konvolut/:fassung', component: FassungComponent } ]) ], exports: [ RouterModule ] }) export class FassungRoutingModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/statisch/signaturen.component.ts
<filename>src/client/app/statisch/signaturen.component.ts /** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-signaturen', templateUrl: 'signaturen.component.html' }) export class SignaturenComponent { title = 'Der Lyrik-Nachlass (Übersicht)'; }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/register/register.component.ts
/** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { ActivatedRoute, Router } from '@angular/router'; import '../operators'; @Component({ moduleId: module.id, selector: 'rae-register', templateUrl: 'register.component.html' }) export class RegisterComponent implements OnInit { title = 'Titelregister'; selectedTab: string; private sub: any; constructor(private http: Http, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.sub = this.route.params.subscribe(params => { this.selectedTab = params[ 'zeitraum' ]; }); console.log('search/schlaf?searchtype=fulltext'); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/core/fusszeile.component.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche<gh_stars>0 /** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-fusszeile', templateUrl: './fusszeile.component.html' }) export class FusszeileComponent { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/konvolut/konvolut-routing.module.ts
/** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { KonvolutComponent } from './konvolut.component'; import { SuperKonvolutComponent } from './super-konvolut.component'; @NgModule({ imports: [ RouterModule.forChild([ { path: 'drucke/abgewandt-zugewandt', component: SuperKonvolutComponent }, { path: 'drucke/abgewandt-zugewandt/:konvolut', component: KonvolutComponent }, { path: 'drucke/:konvolut', component: KonvolutComponent }, { path: 'manuskripte/:konvolut', component: KonvolutComponent }, { path: 'notizbuecher/notizbuch-divers/:konvolut', component: KonvolutComponent }, { path: 'notizbuecher/:konvolut', component: KonvolutComponent }, { path: 'typoskripte/typoskripte-sammlungen/:konvolut', component: KonvolutComponent }, { path: 'typoskripte/:konvolut', component: KonvolutComponent }, { path: 'material/:konvolut', component: KonvolutComponent } ]) ], exports: [ RouterModule ] }) export class KonvolutRoutingModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/konvolut/konvolut.module.ts
/** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdToolbarModule } from '@angular/material'; import { BrowserModule } from '@angular/platform-browser'; import { KonvolutComponent } from './konvolut.component'; import { KonvolutRoutingModule } from './konvolut-routing.module'; import { KonvolutSteckbriefComponent } from './konvolut-steckbrief/konvolut-steckbrief.component'; import { RegisterspalteModule } from '../shared/registerspalte/registerspalte.module'; import { SuperKonvolutComponent } from './super-konvolut.component'; import { TextgridModule } from '../shared/textgrid/textgrid.module'; import { KonvolutWerkzeugleisteComponent } from './konvolut-werkzeugleiste/konvolut-werkzeugleiste.component'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdToolbarModule, RegisterspalteModule, TextgridModule, KonvolutRoutingModule ], declarations: [ KonvolutComponent, KonvolutSteckbriefComponent, KonvolutWerkzeugleisteComponent, SuperKonvolutComponent ], exports: [ KonvolutComponent ] }) export class KonvolutModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/core/core-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { HomepageComponent } from '../statisch/homepage.component'; import { ImpressumComponent } from '../statisch/impressum.component'; import { SignaturenComponent } from '../statisch/signaturen.component'; import { WerklisteComponent } from '../statisch/werkliste.component'; import { LebensdatenComponent } from '../statisch/lebensdaten.component'; import { AnleitungComponent } from '../statisch/anleitung.component'; import { WerkausgabeComponent } from '../statisch/werkausgabe.component'; import { SucheModule } from '../suche/suche.module'; import { PdfNotizbuecherComponent } from '../statisch/pdf-notizbuecher.component'; import { PdfSynopsenComponent } from '../statisch/pdf-synopsen.component'; import { PageNotFoundComponent } from './404.component'; @NgModule({ imports: [ SucheModule, RouterModule.forRoot([ { path: 'werkausgabe', component: WerkausgabeComponent }, { path: 'material/pdf-dateien/notizbuecher', component: PdfNotizbuecherComponent }, { path: 'anleitung', component: AnleitungComponent }, { path: 'lebensdaten', component: LebensdatenComponent }, { path: 'werkliste', component: WerklisteComponent }, { path: 'signaturen', component: SignaturenComponent }, { path: 'impressum', component: ImpressumComponent }, { path: 'material/pdf-dateien/synopsen', component: PdfSynopsenComponent }, { path: 'start', component: HomepageComponent }, { path: '', redirectTo: '/start', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]) ], exports: [ RouterModule ] }) export class CoreRoutingModule { } export const routingComponents = [ AnleitungComponent, HomepageComponent, ImpressumComponent, LebensdatenComponent, PageNotFoundComponent, PdfNotizbuecherComponent, PdfSynopsenComponent, SignaturenComponent, WerkausgabeComponent, WerklisteComponent ];
janCstoffregen/raeber-mit-generischer-suche
src/client/app/shared/image-frame/image-frame.component.ts
<gh_stars>0 import { Component, OnInit, Input } from '@angular/core'; import { Http, Headers, Response } from '@angular/http'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import 'rxjs/Rx'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switchMap'; @Component({ moduleId: module.id, selector: 'rae-image-frame', templateUrl: 'image-frame.component.html', styleUrls: [ 'image-frame.component.css' ] }) export class ImageFrameComponent implements OnInit { @Input() images_in_grid: Array<any>; myImages: Array<any>; zoomfactor = 5; heightAndWidth = 100; height = 200; width = 200; overflow = 'auto'; resize = 'both'; px = 'px'; ausgeklappt: boolean = true; // for testings searchQuery: string; konvolut_id: string; konvolut_type: string; private sub: any; constructor(private http: Http, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.konvolut_type = this.route.snapshot.url[0].path; } searchForDoctor() { return this.http.get('http://test-02.salsah.org/api/search/?searchtype=extended&property_id%5B%5D=439&compop%5B%5D=!EQ&searchval%5B%5D=&show_nrows=25&start_at=0&progvalfile=prog_63047.salsah&filter_by_restype=100') .map( (lambda: Response) => { const data = lambda.json(); console.log(data); //console.log(JSON.stringify(data.subjects, null, 4)); return data.subjects; } ) .subscribe(response => this.myImages = response); } increaseSize() { if (this.zoomfactor > 2) { this.zoomfactor -= 1; } else { window.alert('Picture reached maximum quality'); } } reduceSize() { if (this.zoomfactor < 5) { this.zoomfactor += 1; } else { window.alert('Picture reached minimum quality'); } } increaseFrameSize() { this.height += 200; this.width += 200; } reduceFrameSize() { this.height -= 200; this.width -= 200; } resetSize() { this.height = 200; this.width = 200; this.zoomfactor = 5; } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/core/navigationsleiste.component.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche /** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-navigationsleiste', templateUrl: './navigationsleiste.component.html' }) export class NavigationsleisteComponent { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/fassung/fassung-steckbrief/fassung-steckbrief.component.ts
<filename>src/client/app/fassung/fassung-steckbrief/fassung-steckbrief.component.ts /** * Created by <NAME> (rfbaumgartner) on 05.07.17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-fassung-steckbrief', templateUrl: 'fassung-steckbrief.component.html' }) export class FassungSteckbriefComponent { // TODO: dynamisieren }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/konvolut/konvolut.component.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche<filename>src/client/app/konvolut/konvolut.component.ts /** * Created by retobaumgartner on 06.06.17. */ import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { ActivatedRoute } from '@angular/router'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switchMap'; import { DynamicPaging } from '../shared/textgrid/paging.service'; import { ExtendedSearch, FulltextSearch, KnoraProperty } from '../shared/utilities/knora-api-params'; @Component({ moduleId: module.id, selector: 'rae-konvolut', templateUrl: 'konvolut.component.html' }) export class KonvolutComponent implements OnInit { poems: Array<any>; viewMode: string; konvolut_id: string; konvolut_type: string; private sub: any; private _esearch = new ExtendedSearch(); constructor(private http: Http, private route: ActivatedRoute, private dp: DynamicPaging) { this.viewMode = 'grid'; window.onscroll = () => { let windowHeight = 'innerHeight' in window ? window.innerHeight : document.documentElement.offsetHeight; let body = document.body, html = document.documentElement; let docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); let windowBottom = windowHeight + window.pageYOffset; if (windowBottom >= docHeight) { this.loadMore(); } }; } ngOnInit() { this._esearch.filterByRestype = 'http://www.knora.org/ontology/text#Convolute'; this._esearch.property = new KnoraProperty('http://www.knora.org/ontology/text#hasTitle', '!EQ', ' '); this._esearch.property = new KnoraProperty('http://www.knora.org/ontology/text#hasDescription', '!EQ', ' '); this.dp.size = 10; this.dp.loadText(this._esearch).subscribe( konstText => this.poems = konstText ); this.konvolut_type = this.route.snapshot.url[ 0 ].path; this.sub = this.route.params.subscribe(params => { this.konvolut_id = params[ 'konvolut' ]; }); } loadMore() { this.dp.loadText(this._esearch).subscribe( konstText => this.poems = this.poems.concat(konstText) ); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/statisch/homepage.component.ts
<filename>src/client/app/statisch/homepage.component.ts /** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-homepage', templateUrl: 'homepage.component.html' }) export class HomepageComponent { title = 'Historisch-kritische Online-Edition'; }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/fassung/fassung.component.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche /** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { ActivatedRoute, Params, Router } from '@angular/router'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switchMap'; import { FulltextSearch } from '../shared/utilities/knora-api-params'; @Component({ moduleId: module.id, selector: 'rae-fassung', templateUrl: 'fassung.component.html', styleUrls: [ 'fassung.component.css' ] }) export class FassungComponent implements OnInit { creationDate = 'Freitag, 01 Juni 1979'; modificationDate = 'Samstag, 13 Mai 2017'; zeigeKonstituiert: boolean = true; zeigeDiplomatisch: boolean = false; fassung_tag: Array<string> = [ 'Sonne', 'Wind', 'Wasser' ]; // TODO dynamisieren pages: Array<any> = ['page1', 'page2']; // TODO dynamisieren // for testings searchQuery: string; poem_id: string; konvolut_id: string; konvolut_type: string; nextPoem: string = '219-brunnen'; // TODO prevPoem: string = '221-baum'; // TODO poem_resizable: boolean; show_register: boolean; private sub: any; constructor(private http: Http, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.poem_resizable = true; this.show_register = true; this.konvolut_type = this.route.snapshot.url[ 0 ].path; let searchParams = new FulltextSearch; searchParams.searchstring = 'e'; this.konvolut_type = this.route.snapshot.url[ 0 ].path; this.sub = this.route.params.subscribe(params => { this.konvolut_id = params[ 'konvolut' ]; this.poem_id = params[ 'fassung' ]; }); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/suche.component.ts
<gh_stars>0 /** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component, OnInit } from '@angular/core'; import { Http, Response } from '@angular/http'; import { globalSearchVariableService } from './globalSearchVariablesService'; import {isUndefined} from "util"; import {forEach} from "@angular/router/src/utils/collection"; @Component({ moduleId: module.id, selector: 'rae-suche', templateUrl: 'suche.component.html' }) export class SucheComponent implements OnInit { vocabulary: 'http%3A%2F%2Fwww.knora.org%2Fontology%2Ftext'; numberOfComponents = 1; myResources: Array<any>; myProperties: Array<any>; searchResult: Array<any>; selectedResource: string; selectedProperty: string; boolOperator: string; encodedURL: string; searchForVal: string; query: string; availableboolOperators = [ {name: 'equal to', operator: 'EQ'}, {name: 'not equal to', operator: '!EQ'}, {name: 'greater than', operator: 'GT'}, {name: 'greater or equal', operator: 'GT_EQ'}, {name: 'lower than', operator: 'LT'}, {name: 'lower or equal than', operator: 'LT_EQ'}, {name: 'exists', operator: 'EXISTS'}, {name: 'match', operator: 'MATCH'}, {name: 'like', operator: 'LIKE'}, {name: '!like', operator: '!LIKE'}, {name: 'match_boolean', operator: 'MATCH_BOOLEAN'} ]; arraySize: number; array = [ 1 ]; i: number; j: number; k: number; isAlreadyInArray = 0; //setOfAllQueries: Array<any>; //{numberOfSearchBox: '', numberOfProperty: '', propertyIRI: '', logicalOperator: '', searchVal: ''} helperMap = new Map(); mapOfAllQueries = new Map(); count = 0; numberOfPropertiesInSearchBox = ''; str: string; value: string; keys: Array<any>; finalQueryArray= ['']; currentSearchBox = '1'; allSearchResults: Array<any>; constructor(private http: Http) { } ngOnInit() { //console.log(this.vocabulary); this.initialQuery(this.vocabulary, this.resourceTypesPath); } initialQuery() { return this.http.get ( globalSearchVariableService.API_URL + globalSearchVariableService.resourceTypesPath + globalSearchVariableService.initialVocabulary ) .map( (lambda: Response) => { const data = lambda.json(); console.log(data); return data.resourcetypes; } ) .subscribe(response => this.myResources = response); } propertyQuery() { if (this.selectedResource !== undefined) { //console.log('Path to request property:' + globalSearchVariableService.propertyListsQuery); this.encodedURL = encodeURIComponent(this.selectedResource); //console.log('Selected resource:' + this.encodedURL); return this.http.get(globalSearchVariableService.API_URL + globalSearchVariableService.propertyListsQuery + this.encodedURL) .map( (lambda: Response) => { const data = lambda.json(); console.log(data); return data.properties; } ) .subscribe(response => this.myProperties = response); } } finalQuery() { this.query = globalSearchVariableService.API_URL + globalSearchVariableService.extendedSearch + encodeURIComponent(this.selectedResource) + globalSearchVariableService.extendedProperty + encodeURIComponent(this.selectedProperty) + globalSearchVariableService.compareOperator + this.boolOperator + globalSearchVariableService.searchval + this.searchForVal; //console.log( //'Final extended search URl: ' + this.query); return this.http.get(this.query) .map( (lambda: Response) => { const data = lambda.json(); console.log(data); return data.subjects; } ) .subscribe(response => this.searchResult = response); } increaseNumberOfComponents() { this.numberOfComponents += 1; console.log(this.numberOfComponents); console.log(typeof this.arraySize); } increaseArrayElement() { this.arraySize = this.array[this.array.length - 1 ]; this.arraySize += 1; this.array.push(this.arraySize); console.log(this.arraySize); } updateQuerySet(propertyTriple: Array<any>) { this.k = 0; // Case: setOfAllQueries it totally empty: console.log('PropertyTriple: ' + propertyTriple); console.log('Resource: ' + this.selectedResource); this.mapOfAllQueries.set( propertyTriple[0].toString() + propertyTriple[1].toString(), [ propertyTriple[2], [ propertyTriple[3], propertyTriple[4] ] ] ); this.str = JSON.stringify(this.mapOfAllQueries, null, 4); console.log(this.str); //Final list of Queries: this.keys = Array.from(this.mapOfAllQueries.keys()); console.log(this.keys); this.mapOfAllQueries.forEach( value => { if(this.keys[this.k][1] === '1') { console.log('Add first property'); this.finalQueryArray[this.keys[this.k][0] - 1] = globalSearchVariableService.API_URL + globalSearchVariableService.extendedSearch + encodeURIComponent(propertyTriple[5]) + globalSearchVariableService.extendedProperty + encodeURIComponent(value[0]) + globalSearchVariableService.compareOperator + value[1][0] + globalSearchVariableService.searchval + value[1][1]; } else { console.log('Add additional property'); this.finalQueryArray[this.keys[this.k][0] - 1] += globalSearchVariableService.extendedProperty + encodeURIComponent(value[0]) + globalSearchVariableService.compareOperator + value[1][0] + globalSearchVariableService.searchval + value[1][1]; } this.k++; console.log(value[0]); for(this.i = 0; this.i < value[1].length; this.i++) { console.log(value[1][this.i]); } } ); } executeFinalQueries() { console.log(this.finalQueryArray); for(this.i = 0; this.i < this.finalQueryArray.length; this.i ++) { this.performQuery(this.finalQueryArray[this.i]); } } performQuery(query: string) { return this.http.get(query) .map( (lambda: Response) => { const data = lambda.json(); //console.log(data); this.k = 0; if(data.subjects !== undefined) { if(this.allSearchResults === undefined) { this.allSearchResults = []; } this.allSearchResults.push.apply(this.allSearchResults,data.subjects); } console.log(this.allSearchResults); return data.subjects; } ) .subscribe(response => this.searchResult = response); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/statisch/statisch-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { HomepageComponent } from './homepage.component'; import { ImpressumComponent } from './impressum.component'; import { SignaturenComponent } from './signaturen.component'; import { WerklisteComponent } from './werkliste.component'; import { LebensdatenComponent } from './lebensdaten.component'; import { AnleitungComponent } from './anleitung.component'; import { WerkausgabeComponent } from './werkausgabe.component'; import { PdfNotizbuecherComponent } from './pdf-notizbuecher.component'; import { PdfSynopsenComponent } from './pdf-synopsen.component'; @NgModule({ imports: [ RouterModule.forChild([ { path: 'werkausgabe', component: WerkausgabeComponent }, { path: 'material/pdf-dateien/notizbuecher', component: PdfNotizbuecherComponent }, { path: 'anleitung', component: AnleitungComponent }, { path: 'lebensdaten', component: LebensdatenComponent }, { path: 'werkliste', component: WerklisteComponent }, { path: 'signaturen', component: SignaturenComponent }, { path: 'impressum', component: ImpressumComponent }, { path: 'material/pdf-dateien/synopsen', component: PdfSynopsenComponent }, { path: 'start', component: HomepageComponent } ]) ], exports: [ RouterModule ] }) export class StatischRoutingModule { } export const routingComponents = [ AnleitungComponent, HomepageComponent, ImpressumComponent, LebensdatenComponent, PdfNotizbuecherComponent, PdfSynopsenComponent, SignaturenComponent, WerkausgabeComponent, WerklisteComponent ];
McAngelo/pangaea-product-cart
src/App.tsx
import React, { useReducer, useCallback, useState, useEffect } from 'react'; import logo from './logo.svg'; import './App.css'; //import Home from "./Home"; //import AnotherScreen from "./AnotherScreen"; import Greeting from "./GreetingFunctional"; import ListCreator, { ListItem } from './ListCreator'; //import { Switch, Route} from "react-router"; const reducer = (state: any, action: any) => { console.log("enteredNameReducer"); switch(action.type){ case "enteredName": if(state.enteredName === action.payload){ return state; } return { ...state, enteredName: action.payload } case "message": return { ...state, message: `Hello, ${action.payload}`} default: throw new Error(`Invalid action type ${action.type}`); } } const initialState = { enteredName: "", message: "" } function App() { const [{ message, enteredName }, dispatch] = useReducer(reducer, initialState); const [startCount, setStartCount] = useState(0); const [count, setCount] = useState(0); const setCountCallback = useCallback(() => { const inc = count + 1 > startCount ? count + 1 : Number( count + 1 ) + startCount; setCount(inc); }, [count, startCount]); const [listItems, setListItems] = useState<Array<ListItem>>(); useEffect(() => { const li = []; for(let i = 0; i < count; i++){ li.push({id: i}); } setListItems(li); }, [count]); const onWelcomeBtnClick = () => { setCountCallback(); } const onChangeStartCount = (e: React.ChangeEvent<HTMLInputElement>) => { setStartCount(Number(e.target.value)); } console.log("App.tsx render"); return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <Greeting message ={message} enteredName={enteredName} greetingDispatcher={dispatch} /> <div style={{marginTop: '10px'}}> <label>Enter a number and we'll increment it</label> <br/> <input value={startCount} onChange={onChangeStartCount} style={{width: '.75rem'}} /> &nbsp; <label>{count}</label> <br /> <button onClick={onWelcomeBtnClick}>Increment count</button> </div> <div> <ListCreator listItems={listItems} /> </div> </header> </div> ); } export default App;
McAngelo/pangaea-product-cart
src/Home.tsx
<filename>src/Home.tsx import React, { FC } from "react"; // eslint-disable-next-line @typescript-eslint/no-unused-vars const Home : FC = () =>{ return <div>Hello World! Home </div>; }; export default Home;
McAngelo/pangaea-product-cart
src/ListCreator.tsx
import React, { FC, useEffect, useRef } from 'react'; export interface ListItem{ id: number; } export interface ListItems { listItems?: Array<ListItem>; } const ListCreator: FC<ListItems> = React.memo(({listItems}: ListItems) => { let renderItems = useRef<Array<JSX.Element> | undefined>(); useEffect(() => { console.log("listItems updated"); renderItems.current = listItems?.map((item, index) => { return ( <div key={item.id}>{item.id}</div> ); }); }, [listItems]); console.log("ListCreator render"); return ( <React.Fragment> {renderItems.current} </React.Fragment> ); }); export default ListCreator;
McAngelo/pangaea-product-cart
src/GreetingFunctional.tsx
<reponame>McAngelo/pangaea-product-cart import React from "react"; interface GreetingProps { enteredName: string; message: string; greetingDispatcher: React.Dispatch<{ type: string, payload: string}>; } export default function Greeting(props: GreetingProps) { const onChangeName = (e: React.ChangeEvent<HTMLInputElement>) => { props.greetingDispatcher({type: "enteredName", payload: e.target.value}); props.greetingDispatcher({type: "message", payload: e.target.value}); } return ( <div> <input value={props.enteredName} onChange={ onChangeName } /> <div>{ props.message }</div> </div> ); }
McAngelo/pangaea-product-cart
src/AnotherScreen.tsx
<gh_stars>0 import React, { FC } from "react"; const AnotherScreen: FC = () => { return <div>Hello World! Another Screen</div>; }; export default AnotherScreen;
Fgerthoffert/jira-clone-issues
src/utils/jira/utils/batchUpdateIssues/index.ts
<reponame>Fgerthoffert/jira-clone-issues<gh_stars>0 import { JiraMap } from '../../../../global'; import getIssueTransitions from '../getIssueTransitions'; import updateIssue from '../updateIssue'; import { Config, JiraTransition } from '../../../../global'; const batchUpdateIssues = async (userConfig: Config, issuesToPush: any[], logger: any) => { const availableTransitions: any = []; for (const sourceIssue of issuesToPush) { const dstIssueKey = `${userConfig.destination.projectKey}-${sourceIssue.key.replace(`${userConfig.source.projectKey}-`, '')}` if (availableTransitions.length === 0) { // If there are no transitions in availableTransitions, we get it from the first issue const transitions = await getIssueTransitions(userConfig.destination, dstIssueKey) for (const t of transitions) { if (!availableTransitions.find((at: JiraTransition) => at.name === t.name)) { availableTransitions.push({id: t.id, name: t.name}) } } } const fieldsObj: any = {}; // Handle issue type field const issueTypeMap = userConfig.issueTypes.find((t: JiraMap) => t.source === sourceIssue.fields.issuetype.name) if (issueTypeMap !== undefined) { fieldsObj['issuetype'] = {name: issueTypeMap.destination} } else { fieldsObj['issuetype'] = {name: sourceIssue.fields.issuetype.name} } // Handle all default fields for (const field of userConfig.fields) { if (sourceIssue.fields[field.source] !== null) { fieldsObj[field.destination] = sourceIssue.fields[field.source] } } // Handle updatedAt if (userConfig.destination.fields !== undefined) { fieldsObj[userConfig.destination.fields.syncSourceUpdatedAt] = sourceIssue.fields.updated } // Generate description, which is being updated every time an update is detected let descriptionField = `Source Project: ${sourceIssue.fields.project.name} \n` descriptionField += `Last Updated: ${new Date(sourceIssue.fields.updated)} (Imported: ${new Date()}) \n` descriptionField += `Link: ${userConfig.source.host}/browse/${sourceIssue.key} \n` if (sourceIssue.fields.parent !== undefined && sourceIssue.fields.parent !== null) { descriptionField += `Type: ${sourceIssue.fields.issuetype.name} \n` descriptionField += `Parent: ${userConfig.source.host}/browse/${sourceIssue.fields.parent.key} (${sourceIssue.fields.parent.fields.summary}) \n` } descriptionField += `Reporter: ${sourceIssue.fields.reporter === null ? 'EMPTY' : sourceIssue.fields.reporter.displayName} \n` descriptionField += `Assignee: ${sourceIssue.fields.assignee === null ? 'EMPTY' : sourceIssue.fields.assignee.displayName} \n` descriptionField += `---- \n\n\n` descriptionField += `*+Source issue description:+*\n` if (sourceIssue.fields.description === null) { descriptionField += `=== NO DESCRIPTION IN SOURCE PROJECT === \n` } else { descriptionField += sourceIssue.fields.description.slice(0, 20000) if (sourceIssue.fields.description.length > 20000) { descriptionField += `=== DESCRIPTION EXCEED MAX LENGTH - See source ticket for full content === \n` } } // Add comments to the body of the issue if (sourceIssue.fields.comment.total > 0) { descriptionField += `\n ---- \n` descriptionField += `*+Source issue comments:+*\n` for (const comment of sourceIssue.fields.comment.comments) { descriptionField += `${comment.author.displayName} at ${new Date(comment.created)}\n` descriptionField += `${comment.body} \n` descriptionField += `------ \n\n\n` } } fieldsObj['description'] = descriptionField logger(`${dstIssueKey} - Submitting update to Destination: ${JSON.stringify(fieldsObj)}`); await updateIssue(userConfig.destination, {key: dstIssueKey, fields: fieldsObj}) } }; export default batchUpdateIssues;
Fgerthoffert/jira-clone-issues
src/utils/jira/utils/updateIssue/index.ts
import axios from 'axios'; import { JiraInstance, JiraIssue } from '../../../../global'; import { sleep } from '../../../utils'; const updateIssue = async (jiraServer: JiraInstance, issue: JiraIssue) => { if (jiraServer !== undefined) { let response: any = {} try { response = await axios({ method: 'put', url: `${jiraServer.host}/rest/api/2/issue/${issue.key}`, auth: { username: jiraServer.username, password: <PASSWORD>, }, data: issue }); } catch (error: any) { console.log(issue) console.log(error.response.data.errors) console.log('There has been an error') } if (response.data.length > 0) { return response.data; } // Sleep for 50ms between create requests to avoid flooding the server await sleep(50) } return []; }; export default updateIssue;
Fgerthoffert/jira-clone-issues
src/utils/jira/utils/fetchJql/index.ts
import axios from 'axios'; import { performance } from 'perf_hooks'; import { JiraIssue, JiraInstance } from '../../../../global'; export const fetchJql = async ( jiraServer: JiraInstance, jqlQuey: string, fields: string, startAt: number, maxResults: number, ) => { if (jiraServer !== undefined) { const response = await axios({ method: 'get', url: jiraServer.host + '/rest/api/2/search', auth: { username: jiraServer.username, password: <PASSWORD>, }, validateStatus: function(status) { return status >= 200 && status < 500; }, params: { jql: jqlQuey, startAt: startAt, maxResults: maxResults, fields: fields, }, }); // console.log(jqlQuey); // console.log(response.data); if (response.data !== undefined) { return response.data; } } return {}; }; const fetchJqlPagination = async ( jiraServer: JiraInstance, jqlQuey: string, fields: string, issue: JiraIssue | null, startAt: number, maxResults: number, issues: Array<JiraIssue>, ) => { console.log( ' Start: startAt: ' + startAt + ' - maxResults: ' + maxResults + ' - issues in current cache: ' + issues.length, ); const t0 = performance.now(); const response = await fetchJql( jiraServer, jqlQuey, fields, startAt, maxResults, ); const t1 = performance.now(); const callDuration = t1 - t0; let addedToCache = 0; if (response.errorMessages !== undefined) { console.log(response); return []; } if (issue === null) { for (const newIssue of response.issues) { issues.push(newIssue); } addedToCache = response.issues.length; } else { addedToCache = 0; for (const newIssue of response.issues) { if ( new Date(newIssue.fields.updated) < new Date(issue.fields.updated) || (new Date(newIssue.fields.updated).toISOString() === new Date(issue.fields.updated).toISOString() && newIssue.key === issue.key)) { break; } else { issues.push(newIssue); addedToCache++; } } } const apiPerf = Math.round(response.issues.length / (callDuration / 1000)); console.log( ' Fetched: ' + response.issues.length + ' issues - Total: ' + response.total + ' - issues in current cache: ' + issues.length + ', download rate: ' + apiPerf + ' nodes/s', ); if ( addedToCache !== response.issues.length || issues.length === response.total ) { console.log(' Issue already in cache and/or dataset up to date, stopping'); } else { await fetchJqlPagination( jiraServer, jqlQuey, fields, issue, issues.length, maxResults, issues, ); } return issues; }; export default fetchJqlPagination;
Fgerthoffert/jira-clone-issues
src/utils/utils.ts
export const sleep = (ms: number) => { //https://github.com/Microsoft/tslint-microsoft-contrib/issues/355 // tslint:disable-next-line no-string-based-set-timeout return new Promise(resolve => setTimeout(resolve, ms)); };
Fgerthoffert/jira-clone-issues
types/load-yaml-file.d.ts
<filename>types/load-yaml-file.d.ts declare module 'load-yaml-file';
Fgerthoffert/jira-clone-issues
src/commands/prepare.ts
import { flags } from '@oclif/command'; import * as fs from 'fs'; import * as path from 'path'; import cli from 'cli-ux'; import Command from '../base'; import { JiraIssue, JiraInstance, } from '../global'; import fetchJqlPagination from '../utils/jira/utils/fetchJql'; import getProject from '../utils/jira/utils/getProject'; import getProjectStatuses from '../utils/jira/utils/getProjectStatuses'; interface IssueAction { action: string; data: JiraIssue; } const getAllIssues = async (cache: boolean, jiraInstance: JiraInstance, configDir: string) => { let projectIssues: any = []; if (cache === true && fs.existsSync(path.join(configDir, 'cache', 'source-issues.json'))) { const file: any = await fs.readFileSync(path.join(configDir, 'cache', 'source-issues.json')); projectIssues = JSON.parse(file); } else { projectIssues = await fetchJqlPagination( jiraInstance, 'project = "' + jiraInstance.projectKey + '" ORDER BY updated DESC', '*navigable,comment', null, 0, jiraInstance.fetch.maxNodes, [], ); fs.writeFileSync( path.join(configDir, 'cache', 'source-issues.json'), JSON.stringify(projectIssues), ); } return projectIssues; } export default class Issues extends Command { static description = 'Help prepare the configuration by comparing source and destination Jira projects'; static flags = { help: flags.help({ char: 'h' }), envUserConf: flags.string({ required: false, env: 'USER_CONFIG', description: 'User Configuration passed as an environment variable, takes precedence over config file', }), cache: flags.boolean({ char: 'c', default: false, description: 'Use cache data, do not fetch from the source Jira instance (useful for dev)', }), }; async run() { const { flags } = this.parse(Issues); const userConfig = this.userConfig; this.log('---') this.log('Step 1: Verifying presence of a destination project') cli.action.start(`Step 1: Searching for destination project with key: ${userConfig.destination.projectKey}`); const destinationProject = await getProject(userConfig.destination) if (destinationProject === null) { this.log(`ERROR: Unable to find project with key: ${userConfig.destination.projectKey}`) this.exit(1) } cli.action.stop(`project found: ${destinationProject.name} - description: ${destinationProject.description}`) this.log('---') this.log('Step 2: Polling all the source issues to get the list of issues statuses and types') cli.action.start(`Step 2: Polling issues from source Jira instance`); const projectSourceIssues: JiraIssue[] = await getAllIssues(flags.cache, userConfig.source, this.config.configDir); const sourceStatuses: string[] = projectSourceIssues.reduce((acc: string[], i) => { if (!acc.includes(i.fields.status.name)) { acc.push(i.fields.status.name) } return acc }, []) const sourceIssuesTypes: string[] = projectSourceIssues.reduce((acc: string[], i) => { if (!acc.includes(i.fields.issuetype.name)) { acc.push(i.fields.issuetype.name) } return acc }, []) cli.action.stop(`data fetch complete, the following status and types were found:`) this.log(`Step 2: Statuses: ${JSON.stringify(sourceStatuses)}`) this.log(`Step 2: Types: ${JSON.stringify(sourceIssuesTypes)}`) this.log('---') this.log('Step 3: Checking the destination server contains the necessary issue types') this.log(`Step 3: Source Project: ${JSON.stringify(sourceIssuesTypes)}`) const destinationTypes: string[] = destinationProject.issueTypes.reduce((acc: string[], t: any) => { if (!acc.includes(t.name)) { acc.push(t.name) } return acc }, []) this.log(`Step 3: Destination Project: ${JSON.stringify(destinationTypes)}`) this.log(`Step 3: The following mapping are present in configuration:`) for (const issueType of userConfig.issueTypes) { this.log(` ${issueType.source} => ${issueType.destination}`) } const incorrectTypes = userConfig.issueTypes.filter((configType) => { return !destinationTypes.includes(configType.destination) }) if (incorrectTypes.length > 0) { this.log('ERROR: The following destination types IN YOUR configuration do not exist on the destination project') this.log('ERROR: Please create them first or update your configuration') this.log(`ERROR: ${JSON.stringify(incorrectTypes)}`) this.exit(1) } const unmappedTypes: string[] = sourceIssuesTypes.filter((sourceType: string) => { if (destinationTypes.includes(sourceType)) { return false; } else if (userConfig.issueTypes.find((configType) => configType.source === sourceType)) { return false } return true }) if (unmappedTypes.length > 0) { this.log('ERROR: The following issue types are present in the source Jira Project') this.log('ERROR: They do not exist on the destination Jira Project NOR are available through a mapping') this.log('ERROR: Please create them first or update your configuration') this.log(`ERROR: ${JSON.stringify(unmappedTypes)}`) this.exit(1) } this.log('---') this.log('Step 4: Checking the destination server contains the necessary statuses') cli.action.start(`Step 4: Polling issues statuses from destination Jira instance`); const destinationProjectStatuses = await getProjectStatuses(userConfig.destination) cli.action.stop(`done`) const destinationStatuses: string[] = destinationProjectStatuses.reduce((acc: string[], t: any) => { for (const status of t.statuses) { if (!acc.includes(status.name)) { acc.push(status.name) } } return acc }, []) this.log(`Step 4: Source Project: ${JSON.stringify(sourceStatuses)}`) this.log(`Step 4: Destination Project: ${JSON.stringify(destinationStatuses)}`) this.log(`Step 4: The following mapping are present in configuration:`) for (const issueStatus of userConfig.status) { this.log(` ${issueStatus.source} => ${issueStatus.destination}`) } const incorrectStatus = userConfig.status.filter((configStatus) => { return !destinationStatuses.includes(configStatus.destination) }) if (incorrectStatus.length > 0) { this.log('ERROR: The following destination status IN YOUR configuration do not exist on the destination project') this.log('ERROR: Please create them first or update your configuration') this.log(`ERROR: ${JSON.stringify(incorrectStatus)}`) this.exit(1) } const unmappedStatuses: string[] = sourceStatuses.filter((sourceStatus: string) => { if (destinationStatuses.includes(sourceStatus)) { return false; } else if (userConfig.status.find((configStatus) => configStatus.source === sourceStatus)) { return false } return true }) if (unmappedStatuses.length > 0) { this.log('ERROR: The following issue types are present in the source Jira Project') this.log('ERROR: They do not exist on the destination Jira Project NOR are available through a mapping') this.log('ERROR: Please create them first or update your configuration') this.log(`ERROR: ${JSON.stringify(unmappedStatuses)}`) this.exit(1) } this.log('=== Prepare step successful, your project should be ready for import ===') } }
Fgerthoffert/jira-clone-issues
src/base.ts
import Command from '@oclif/command'; import * as fs from 'fs'; import * as fse from 'fs-extra'; import * as jsYaml from 'js-yaml'; import loadYamlFile from 'load-yaml-file'; import * as path from 'path'; import { Config } from './global'; import { defaultConfig } from './components/config/index'; export default abstract class extends Command { userConfig = defaultConfig; setUserConfig(userConfig: Config) { this.userConfig = userConfig; } async init() { if (process.env.CONFIG_DIR !== undefined) { this.config.configDir = process.env.CONFIG_DIR; } // If config file does not exists, initialize it: fse.ensureDirSync(this.config.configDir); fse.ensureDirSync(this.config.configDir + '/cache/'); if (!fs.existsSync(path.join(this.config.configDir, 'config.yml'))) { fs.writeFileSync( path.join(this.config.configDir, 'config.yml'), jsYaml.safeDump(this.userConfig), ); this.log( 'Initialized configuration file with defaults in: ' + path.join(this.config.configDir, 'config.yml'), ); this.log('Please EDIT the configuration file first'); this.exit(); } else { this.log( 'Configuration file exists: ' + path.join(this.config.configDir, 'config.yml'), ); const userConfig = await loadYamlFile( path.join(this.config.configDir, 'config.yml'), ); this.setUserConfig(userConfig); } } }
Fgerthoffert/jira-clone-issues
src/utils/jira/utils/createEmptyIssue/index.ts
import axios from 'axios'; import { JiraInstance, JiraInstanceDestination } from '../../../../global'; import { sleep } from '../../../utils'; const createEmptyIssue = async (jiraServer: JiraInstance & JiraInstanceDestination, sourceKey: string) => { const issueDataFields: any = { project: { key: jiraServer.projectKey }, summary: `[${sourceKey}] - Empty issue (for sync purposes)`, issuetype: { name: jiraServer.defaultIssueType }, } if (jiraServer !== undefined) { let response: any = {} try { response = await axios({ method: 'post', url: jiraServer.host + '/rest/api/2/issue', auth: { username: jiraServer.username, password: <PASSWORD>, }, data: { fields: issueDataFields, } }); } catch (error: any) { console.log(error.response.data.errors) console.log('There has been an error') } if (response.data.length > 0) { return response.data; } // Sleep between create requests to avoid flooding the server await sleep(50) } return []; }; export default createEmptyIssue;
Fgerthoffert/jira-clone-issues
src/components/config/index.ts
export { default as zencrepesConfig } from './defaultConfig.type'; export { default as defaultConfig } from './defaultConfig';
Fgerthoffert/jira-clone-issues
src/utils/jira/utils/batchUpdateStatus/index.ts
<gh_stars>0 import { JiraIssue } from '../../../../global'; import getIssueTransitions from '../getIssueTransitions'; import transitionIssue from '../transitionIssue'; import { Config, JiraTransition } from '../../../../global'; const batchUpdateStatus = async (userConfig: Config, issuesToPush: any[], destinationIssues: any[], logger: any) => { const availableTransitions: any = []; for (const sourceIssue of issuesToPush) { const destinationIssue = destinationIssues.find((i: JiraIssue) => i.key.replace(userConfig.destination.projectKey, '') === sourceIssue.key.replace(userConfig.source.projectKey, '')) // Handle issue status change //https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#api/2/issue-getTransitions if (destinationIssue.fields.status.name !== sourceIssue.fields.status.name) { logger(`Issue status needs to be updated for ${sourceIssue.key}, source: ${sourceIssue.fields.status.name} - destination: ${destinationIssue.fields.status.name}`) let srcTransition = availableTransitions.find((t: JiraTransition) => t.name === sourceIssue.fields.status.name); let dstTransition: JiraTransition | null = srcTransition !== undefined ? srcTransition : {}; if (dstTransition !== null) { // If the transition couldn't be found in the list of available transition from the array initially fetched // It's possible it's coming from another transition not available then, so we're fetching the list again const transitions = await getIssueTransitions(userConfig.destination, destinationIssue.key) for (const t of transitions) { if (!availableTransitions.find((at: JiraTransition) => at.name === t.name)) { availableTransitions.push({id: t.id, name: t.name}) } } srcTransition = availableTransitions.find((t: JiraTransition) => t.name === sourceIssue.fields.status.name); if (srcTransition !== undefined) { dstTransition = srcTransition } } if (dstTransition !== null) { logger(`Submitting transition for update: ${JSON.stringify(dstTransition)}`) await transitionIssue(userConfig.destination, destinationIssue.key, dstTransition) } else { logger(`ERROR: Unable to find transition: ${sourceIssue.fields.status.name}`) logger(availableTransitions) } } else { logger(`Issue update not needed for ${destinationIssue.key}, source: ${sourceIssue.fields.status.name} - destination: ${destinationIssue.fields.status.name}`) } } }; export default batchUpdateStatus;
Fgerthoffert/jira-clone-issues
src/components/config/defaultConfig.ts
const defaultConfig = { source: { host: 'https://jira.domain.com/', username: 'USERNAME', password: 'PASSWORD', projectKey: 'DMF', fetch: { maxNodes: 30, }, }, destination: { host: 'https://jira.domain.com/', username: 'USERNAME', password: 'PASSWORD', projectKey: 'DMF', fetch: { maxNodes: 30, }, defaultIssueType: 'Task', fields: { syncSourceUpdatedAt: 'customfield_10314' } }, issueTypes: [{ source: 'Bug', destination: 'Task', }], status: [{ source: 'OPEN', destination: 'OPEN', }], fields: [{ source: 'Custom-field-source', destination: 'Custom-field-destination' }], }; export default defaultConfig;
Fgerthoffert/jira-clone-issues
src/components/config/defaultConfig.type.ts
export interface JiraInstance { host: string; username: string; password: <PASSWORD>; projectKey: string; fetch: { maxNodes: number; } } export interface JiraInstanceDestination { defaultIssueType: string; fields: { syncSourceUpdatedAt: string; } } export interface JiraMap { source: string; destination: string; } export interface Config { source: JiraInstance; destination: JiraInstance & JiraInstanceDestination; status: JiraMap[]; fields: JiraMap[]; issueTypes: JiraMap[]; } export default Config;
Fgerthoffert/jira-clone-issues
src/commands/update.ts
import { flags } from '@oclif/command'; import cli from 'cli-ux'; import Command from '../base'; import { JiraInstance, JiraInstanceDestination } from '../global'; import { fetchJql } from '../utils/jira/utils/fetchJql'; import fetchJqlPagination from '../utils/jira/utils/fetchJql'; import createEmptyIssue from '../utils/jira/utils/createEmptyIssue'; import batchUpdateIssues from '../utils/jira/utils/batchUpdateIssues'; import batchUpdateStatus from '../utils/jira/utils/batchUpdateStatus'; const getLastissuesToUpdate = async (jiraInstance: JiraInstance & JiraInstanceDestination) => { let dateField = 'updated'; if (jiraInstance.fields !== undefined && jiraInstance.fields.syncSourceUpdatedAt !== undefined) { dateField = `${jiraInstance.fields.syncSourceUpdatedAt.replace('customfield_', 'cf[')}]` } const projectIssues = await fetchJql( jiraInstance, `project = "${jiraInstance.projectKey}" AND ${dateField} is not EMPTY ORDER BY ${dateField} DESC`, '*navigable,comment', 0, 1 ); if (projectIssues.maxResults === 1) { return projectIssues.issues[0] } return null; } const getLastIssueByKey = async (jiraInstance: JiraInstance) => { const projectIssues = await fetchJql( jiraInstance, `project = "${jiraInstance.projectKey}" ORDER BY key DESC`, '*navigable,comment', 0, 1 ); if (projectIssues.maxResults === 1) { return projectIssues.issues[0] } return null; } export default class Issues extends Command { static description = 'Update issues based on recent changes in the source'; static flags = { help: flags.help({ char: 'h' }), envUserConf: flags.string({ required: false, env: 'USER_CONFIG', description: 'User Configuration passed as an environment variable, takes precedence over config file', }), }; async run() { const userConfig = this.userConfig; cli.action.start(`Fetch the latest updated issue on source`); let lastIssue = await getLastissuesToUpdate(userConfig.destination) cli.action.stop(`done`) // lastIssue could be null if the project is empty, in that case all issues will end-up being fetched from // the source instance if (lastIssue !== null) { this.log(`The last updated issue was: ${lastIssue.key}, updated on: ${lastIssue.fields[userConfig.destination.fields.syncSourceUpdatedAt]}`) // Modify lastIssue date lastIssue = { ...lastIssue, fields: { ...lastIssue.fields, updated: lastIssue.fields[userConfig.destination.fields.syncSourceUpdatedAt] } } } cli.action.start(`Get all issues updated since ${lastIssue.fields[userConfig.destination.fields.syncSourceUpdatedAt]} from the source Jira`); const issuesToUpdate = await fetchJqlPagination( userConfig.source, 'project = "' + userConfig.source.projectKey + '" ORDER BY updated DESC', '*navigable,comment', lastIssue, 0, userConfig.source.fetch.maxNodes, [], ); cli.action.stop(`done`) this.log(`The following Jira issues will be pushed to the destination instance:`) for (const i of issuesToUpdate) { this.log(`Needs update - Key: ${i.key} - Updated on: ${i.fields.updated} - Created on: ${i.fields.created}`) } // Before pushing an update we need to make sure all issues on the source are also present on the destination // Including any potential gaps in numbering // The last issue by Key might very well be different than last updated issue, thus using a different query const lastSourceIssueByKey = await getLastIssueByKey(userConfig.source) const lastDesintationIssueByKey = await getLastIssueByKey(userConfig.destination) let dstKeyId = 0; if (lastDesintationIssueByKey === null) { this.log(`The destination server does not contain any issue yet`) } else { this.log(`The latest issue created on the destination was: ${lastDesintationIssueByKey.key}, created on: ${lastDesintationIssueByKey.fields.created}`) dstKeyId = parseInt(lastDesintationIssueByKey.key.replace(`${userConfig.destination.projectKey}-`, '')) } this.log(`The latest issue created on the source was: ${lastSourceIssueByKey.key}, created on: ${lastSourceIssueByKey.fields.created}`) cli.action.start(`Checking if empty issues needs to be created`); const srcKeyId = parseInt(lastSourceIssueByKey.key.replace(`${userConfig.source.projectKey}-`, '')) while(dstKeyId < srcKeyId) { dstKeyId++; this.log(`Creating issue for: ${userConfig.source.projectKey}-${srcKeyId}`) await createEmptyIssue(userConfig.destination, `${userConfig.source.projectKey}-${srcKeyId}`) } cli.action.stop(`done`) if (issuesToUpdate.length === 0) { this.log(`No issues require an update, exiting`) this.exit() } // Check if all issues exist on the destination instance before grabbing status // We will then filter these to make sure we don't try to push data for an issue that does not exist cli.action.start(`Grab all issues located in the destination instance`); const destinationIssuesKeysRaw = await fetchJqlPagination( userConfig.destination, 'project = "' + userConfig.source.projectKey + '" ORDER BY updated DESC', 'key', null, 0, userConfig.source.fetch.maxNodes, [], ); cli.action.stop(`done`) const destinationIssuesKeys = destinationIssuesKeysRaw.map(i => i.key) cli.action.start(`Grab issues status from the recently updated issues`); const destinationIssues = await fetchJqlPagination( userConfig.destination, `key in(${issuesToUpdate.filter((i) => destinationIssuesKeys.includes(i.key)).map((i) => i.key).toString()})`, '*navigable,comment', null, 0, userConfig.source.fetch.maxNodes, [], ); cli.action.stop(`done`) this.log(`Issues to update: ${JSON.stringify(issuesToUpdate.map((i) => i.key))}`) this.log(`Destination issues: ${JSON.stringify(destinationIssues.map((i) => i.key))}`) cli.action.start(`Updating issues status when necessary`); await batchUpdateStatus(userConfig, issuesToUpdate.filter((i) => destinationIssuesKeys.includes(i.key)), destinationIssues, this.log) cli.action.stop(`done`) cli.action.start(`Bulk updating issues content`); await batchUpdateIssues(userConfig, issuesToUpdate.filter((i) => destinationIssuesKeys.includes(i.key)), this.log) cli.action.stop(`done`) } }
Fgerthoffert/jira-clone-issues
src/global.ts
<reponame>Fgerthoffert/jira-clone-issues export { Config, JiraInstance, JiraInstanceDestination, JiraMap, } from './components/config/defaultConfig.type'; export interface JiraTransition { id: string; name: string; } export interface JiraIssueFields { status: { name: string; }; issuetype: { name: string }; summary: string; updated: string; created: string; } export interface JiraIssue { id?: string; key: string; fields: JiraIssueFields; }
sonlinux/shopu
src/index.tsx
<gh_stars>1-10 import { defaultDataIdFromObject, InMemoryCache } from "apollo-cache-inmemory"; import { persistCache } from "apollo-cache-persist"; import { ApolloClient } from "apollo-client"; import { ApolloLink } from "apollo-link"; import { BatchHttpLink } from "apollo-link-batch-http"; import { RetryLink } from "apollo-link-retry"; import * as React from "react"; import { positions, Provider as AlertProvider, useAlert } from "react-alert"; import { ApolloProvider } from "react-apollo"; import { render } from "react-dom"; import { Route, Router, Switch } from "react-router-dom"; import urljoin from "url-join"; import { createBrowserHistory } from "history"; import { App } from "./app"; import CheckoutApp from "./checkout"; import { CheckoutContext } from "./checkout/context"; import CheckoutProvider from "./checkout/provider"; import { baseUrl as checkoutBaseUrl } from "./checkout/routes"; import { NotificationTemplate, OverlayProvider, UserProvider } from "./components"; import CartProvider from "./components/CartProvider"; import ShopProvider from "./components/ShopProvider"; import { UserContext } from "./components/User/context"; import { authLink, invalidTokenLinkWithTokenHandlerComponent } from "./core/auth"; const API_URL = urljoin(process.env.BACKEND_URL || "", "/graphql/"); const { component: UserProviderWithTokenHandler, link: invalidTokenLink } = invalidTokenLinkWithTokenHandlerComponent(UserProvider); const link = ApolloLink.from([ invalidTokenLink, authLink, new RetryLink(), new BatchHttpLink({ uri: API_URL }) ]); const cache = new InMemoryCache({ dataIdFromObject: obj => { if (obj.__typename === "Shop") { return "shop"; } return defaultDataIdFromObject(obj); } }); const history = createBrowserHistory(); history.listen((location, action) => { if (["PUSH"].includes(action)) { window.scroll({ behavior: "smooth", top: 0 }); } }); const startApp = async () => { await persistCache({ cache, storage: window.localStorage }); const apolloClient = new ApolloClient({ cache, link }); const notificationOptions = { position: positions.BOTTOM_RIGHT, timeout: 2500 }; const Root = () => { const alert = useAlert(); return ( <Router history={history}> <ApolloProvider client={apolloClient}> <ShopProvider> <OverlayProvider> <UserProviderWithTokenHandler apolloClient={apolloClient} onUserLogin={() => alert.show( { title: "You are now logged in" }, { type: "success" } ) } onUserLogout={() => alert.show( { title: "You are now logged out" }, { type: "success" } ) } refreshUser > <UserContext.Consumer> {user => ( <CheckoutProvider user={user}> <CheckoutContext.Consumer> {checkout => ( <CartProvider checkout={checkout} apolloClient={apolloClient} > <Switch> <Route path={checkoutBaseUrl} component={CheckoutApp} /> <Route component={App} /> </Switch> </CartProvider> )} </CheckoutContext.Consumer> </CheckoutProvider> )} </UserContext.Consumer> </UserProviderWithTokenHandler> </OverlayProvider> </ShopProvider> </ApolloProvider> </Router> ); }; render( <AlertProvider template={NotificationTemplate} {...notificationOptions}> <Root /> </AlertProvider>, document.getElementById("root") ); }; if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/service-worker.js"); } startApp();
sonlinux/shopu
src/components/MainMenu/MainMenu.tsx
<reponame>sonlinux/shopu import { mediumScreen, smallScreen } from "../../globalStyles/scss/variables.scss"; import "./scss/index.scss"; import * as React from "react"; import Media from "react-media"; import { Link } from "react-router-dom"; import ReactSVG from "react-svg"; import { MenuDropdown, Offline, Online, OverlayContext, OverlayTheme, OverlayType } from ".."; import { maybe } from "../../core/utils"; import { baseUrl } from "../../routes"; import { CartContext } from "../CartProvider/context"; import { UserContext } from "../User/context"; import NavDropdown from "./NavDropdown"; import { TypedMainMenuQuery } from "./queries"; import cartImg from "../../images/cart.svg"; import hamburgerHoverImg from "../../images/hamburger-hover.svg"; import hamburgerImg from "../../images/hamburger.svg"; import logoImg from "../../images/logo.svg"; import searchImg from "../../images/search.svg"; import userImg from "../../images/user.svg"; const MainMenu: React.FC = () => ( <OverlayContext.Consumer> {overlayContext => ( <nav className="main-menu" id="header"> <div className="main-menu__left"> <TypedMainMenuQuery renderOnError displayLoader={false}> {({ data }) => { const items = maybe(() => data.shop.navigation.main.items, []); return ( <ul> <Media query={{ maxWidth: mediumScreen }} render={() => ( <li className="main-menu__hamburger" onClick={() => overlayContext.show( OverlayType.sideNav, OverlayTheme.left, { data: items } ) } > <ReactSVG path={hamburgerImg} className={"main-menu__hamburger--icon"} /> <ReactSVG path={hamburgerHoverImg} className={"main-menu__hamburger--hover"} /> </li> )} /> <Media query={{ minWidth: mediumScreen }} render={() => items.map(item => ( <li className="main-menu__item" key={item.id}> <NavDropdown overlay={overlayContext} {...item} /> </li> )) } /> </ul> ); }} </TypedMainMenuQuery> </div> <div className="main-menu__center"> <Link to={baseUrl}> <ReactSVG path={logoImg} /> </Link> </div> <div className="main-menu__right"> <ul> <Online> <Media query={{ minWidth: smallScreen }} render={() => ( <UserContext.Consumer> {({ logout, user }) => user ? ( <MenuDropdown head={ <li className="main-menu__icon main-menu__user--active"> <ReactSVG path={userImg} /> </li> } content={ <ul className="main-menu__dropdown"> <li onClick={logout}>Log Out</li> </ul> } /> ) : ( <li className="main-menu__icon" onClick={() => overlayContext.show( OverlayType.login, OverlayTheme.right ) } > <ReactSVG path={userImg} /> </li> ) } </UserContext.Consumer> )} /> <CartContext.Consumer> {cart => ( <li className="main-menu__icon main-menu__cart" onClick={() => { overlayContext.show(OverlayType.cart, OverlayTheme.right); }} > <ReactSVG path={cartImg} /> {cart.getQuantity() > 0 ? ( <span className="main-menu__cart__quantity"> {cart.getQuantity()} </span> ) : null} </li> )} </CartContext.Consumer> </Online> <Offline> <li className="main-menu__offline"> <Media query={{ minWidth: mediumScreen }} render={() => <span>Offline</span>} /> </li> </Offline> <li className="main-menu__search" onClick={() => overlayContext.show(OverlayType.search, OverlayTheme.right) } > <Media query={{ minWidth: mediumScreen }} render={() => <span>Search</span>} /> <ReactSVG path={searchImg} /> </li> </ul> </div> </nav> )} </OverlayContext.Consumer> ); export default MainMenu;
splitinfinities/lottie-wc
src/components/lottie-animation/lottie-animation.tsx
<gh_stars>100-1000 import { Component, Prop, State, Method, Element } from '@stencil/core'; import lottie from 'lottie-web'; @Component({ tag: 'lottie-animation', styleUrl: 'lottie-animation.css' }) export class LottieAnimation { @Element() element: HTMLElement; @Element() progress: HTMLElement; /** * input the lottie data directly to the component */ @Prop() animationData: string; /** * Get the animation via src attribute */ @Prop() src: string; @Prop() loop: boolean; @Prop() count: number; @Prop() autoplay: boolean; @Prop() controls: boolean; @Prop() renderer: string = "svg"; @Prop() speed: number = 1; @Prop() direction: number = 1; @State() __paused: boolean = false; @State() settings: Object = {}; @State() io: IntersectionObserver; @State() status: string; @State() lottie: any; @State() duration: any; @State() currentTime: any; @State() mouseDown: any; componentDidLoad() { this.update({ container: this.element.querySelector('.animation') }) this.load(); this.setSpeed(this.speed); this.setDirection(this.direction); if (this.autoplay) { this.addIntersectionObserver(); } } load () { this.lottie = lottie.loadAnimation(this.settings); if (this.controls) { this.lottie.addEventListener("data_ready", () => { this.handleDataReady() }); this.lottie.addEventListener("enterFrame", () => { this.handleNewFrame() }); } } handleDataReady () { this.duration = this.lottie.totalFrames / this.lottie.frameRate; } handleNewFrame () { this.currentTime = this.lottie.currentFrame / this.lottie.frameRate; } addIntersectionObserver() { if ('IntersectionObserver' in window) { this.io = new IntersectionObserver((data: any) => { // because there will only ever be one instance // of the element we are observing // we can just use data[0] if (data[0].isIntersecting) { this.play(); } else { this.pause(); } }) this.io.observe(this.element.querySelector('.animation')); } else { // fall back to setTimeout for Safari and IE setTimeout(() => { this.handleVisible(); }, 300); } } handleVisible() { this.pause(); } removeIntersectionObserver() { if (this.io) { this.io.disconnect(); this.io = null; } } @Method() play() { this.status = "play"; this.lottie.play() } @Method() pause() { this.__paused = true; this.status = "pause"; this.lottie.pause() } @Method() stop() { this.status = "stop"; this.lottie.stop() } @Method() setSpeed(value: number = 1) { this.lottie.setSpeed(value); } @Method() setDirection(value: number = 1) { this.lottie.setDirection(value); } @Method() rendererSettings(settings) { this.settings = settings; this.lottie = this.settings } @Method() instance() { return this.lottie; } /** Renders the settings object and checks if the data is added via src or animationData element */ @Method() update(settings) { const settingsObj: any = { renderer: this.renderer, loop: this.count ? this.count : this.loop, autoplay: this.autoplay, rendererSettings: { scaleMode: 'noScale', clearCanvas: false, progressiveLoad: true, hideOnTransparent: true }, ...settings }; if(this.animationData) { settingsObj.animationData = this.animationData; } else { settingsObj.path = this.src; } this.settings = settingsObj; } handleProgressClick(e) { var x = e.offsetX; let clickedValue = (x / this.progress.offsetWidth) * 1000; clickedValue = this.duration * clickedValue; if (this.lottie.isPaused && this.__paused) { this.lottie.goToAndStop(clickedValue, false) } else { this.lottie.goToAndPlay(clickedValue, false) } } round (number) { var factor = Math.pow(10, 4); return Math.round(number * factor) / factor; } renderControls() { return ( <div class="controls"> <button onClick={() => { this.lottie.isPaused ? this.play() : this.pause() }}>{this.lottie.isPaused ? "Play" : "Pause"}</button> <button onClick={() => { this.stop() }}>Stop</button> <div class="seek"> <progress max="100" value={(this.currentTime / this.duration) * 100} onMouseDown={() => { this.mouseDown = true; this.pause(); this.__paused = true; }} onMouseMove={(e) => { if (this.mouseDown) { this.handleProgressClick(e); } }} onMouseUp={() => { this.mouseDown = false; this.play(); }} onBlur={() => {this.mouseDown = false;}}> <div class="progress-bar"> <p class="duration">{this.round(this.duration)}</p> <span style={{"width": `${(this.currentTime / this.duration) * 100}%`}}> <p class="currentTime">{this.round(this.currentTime)}</p> </span> </div> </progress> </div> </div> ); } render() { return ( <div> <div class="animation" data-status={this.status}></div> {this.lottie && this.controls && this.renderControls()} </div> ); } }
splitinfinities/lottie-wc
src/components.d.ts
/** * This is an autogenerated file created by the Stencil build process. * It contains typing information for all components that exist in this project * and imports for stencil collections that might be configured in your stencil.config.js file */ declare global { namespace JSX { interface Element {} export interface IntrinsicElements {} } namespace JSXElements {} interface HTMLStencilElement extends HTMLElement { componentOnReady(): Promise<this>; componentOnReady(done: (ele?: this) => void): void; forceUpdate(): void; } interface HTMLAttributes {} } import { LottieAnimation as LottieAnimation } from './components/lottie-animation/lottie-animation'; declare global { interface HTMLLottieAnimationElement extends LottieAnimation, HTMLStencilElement { } var HTMLLottieAnimationElement: { prototype: HTMLLottieAnimationElement; new (): HTMLLottieAnimationElement; }; interface HTMLElementTagNameMap { 'lottie-animation': HTMLLottieAnimationElement; } interface ElementTagNameMap { 'lottie-animation': HTMLLottieAnimationElement; } namespace JSX { interface IntrinsicElements { 'lottie-animation': JSXElements.LottieAnimationAttributes; } } namespace JSXElements { export interface LottieAnimationAttributes extends HTMLAttributes { /** * input the lottie data directly to the component */ 'animationData'?: string; 'autoplay'?: boolean; 'controls'?: boolean; 'count'?: number; 'direction'?: number; 'loop'?: boolean; 'renderer'?: string; 'speed'?: number; /** * Get the animation via src attribute */ 'src'?: string; } } } declare global { namespace JSX { interface StencilJSX {} } }
nw55/es-logging
src/filter.ts
import { ArgumentError, LogLevelKeys } from '@nw55/common'; import { LogMessage } from './common'; import { LogLevel } from './log-level'; export interface LogFilter { shouldLog: (level: LogLevel, source?: string) => boolean; shouldLogMessage: (message: LogMessage) => boolean; } type LogFilterFunction = (level: LogLevel, source?: string) => boolean; const logNothingFilter: LogFilter = { shouldLog: () => false, shouldLogMessage: () => false }; export function defaultLogFilter(filter: LogFilterFunction | LogFilter | boolean): LogFilter { if (filter === true) return LogLevel.All; if (filter === false) return logNothingFilter; if (typeof filter !== 'function') return filter; return { shouldLog: filter, shouldLogMessage: message => filter(message.level, message.source) }; } interface LogFilterMap { [sourcePrefix: string]: LogLevel | LogLevelKeys; } export class SourcePrefixLogFilter implements LogFilter { private _defaultLevelValue: number; private _separator: string; private _prefixMap = new Map<string, number>(); private _minLevelValue: number; constructor(defaultLevel: LogLevel | LogLevelKeys, map: LogFilterMap, separator = '/') { if (separator === '') throw new ArgumentError(); this._defaultLevelValue = LogLevel.get(defaultLevel).value; this._separator = separator; this._minLevelValue = this._defaultLevelValue; for (const [prefix, levelOrLevelKey] of Object.entries(map)) { const levelValue = LogLevel.get(levelOrLevelKey).value; this._minLevelValue = Math.min(this._minLevelValue, levelValue); this._prefixMap.set(prefix, levelValue); } } shouldLog(level: LogLevel, source?: string) { if (level.value < this._minLevelValue) return false; if (source !== undefined) { let prefix = source; while (true) { const prefixLevelValue = this._prefixMap.get(prefix); if (prefixLevelValue !== undefined) { if (prefix !== source) this._prefixMap.set(source, prefixLevelValue); return level.value >= prefixLevelValue; } const lastSeparatorIndex = prefix.lastIndexOf(this._separator); if (lastSeparatorIndex < 0) break; prefix = prefix.slice(0, lastSeparatorIndex); } this._prefixMap.set(source, this._defaultLevelValue); } return level.value >= this._defaultLevelValue; } shouldLogMessage(message: LogMessage) { return this.shouldLog(message.level, message.source); } }
nw55/es-logging
test/combined-log-writer.ts
<reponame>nw55/es-logging import { LogLevelKeys } from '@nw55/common'; import { CombinedLogWriter, LogLevel, LogMessage, LogWriter } from '@nw55/logging'; import { assert } from 'chai'; import { describe, test } from 'mocha'; class TestLogWriter implements LogWriter { didLog = false; constructor(private _id: string, private _shouldLog: boolean) { } shouldLog(level: LogLevel<LogLevelKeys>, source?: string) { return this._shouldLog; } log(message: LogMessage) { this.didLog = true; } } const testLogMessage: LogMessage = { level: LogLevel.Information, message: '' }; describe('combined-log-writer', () => { test('shouldLog / log', () => { const writer1 = new TestLogWriter('1', true); const writer2 = new TestLogWriter('2', false); const writer3 = new TestLogWriter('3', false); const combined1 = new CombinedLogWriter([writer1, writer2]); assert.isTrue(combined1.shouldLog(LogLevel.Information), 'shouldLog() should return true'); combined1.log(testLogMessage); assert.isTrue(writer1.didLog, 'should call log()'); assert.isFalse(writer2.didLog, 'should not call log()'); const combined2 = new CombinedLogWriter([writer2, writer3]); assert.isFalse(combined2.shouldLog(LogLevel.Information)); combined2.log(testLogMessage); assert.isFalse(writer2.didLog, 'should not call log()'); assert.isFalse(writer3.didLog, 'should not call log()'); }); test('flattening of nested combined log writers', () => { const writer1 = new TestLogWriter('1', true); const writer2 = new TestLogWriter('2', false); const writer3 = new TestLogWriter('3', false); const combined1 = new CombinedLogWriter([writer1, writer2]); const combined2 = new CombinedLogWriter([combined1, writer3]); assert.deepStrictEqual(combined2.writers, [writer1, writer2, writer3], 'should flatten and maintain order'); }); test('static addLogWriter / removeLogWriter', () => { const writer1 = new TestLogWriter('1', true); const writer2 = new TestLogWriter('2', false); const writer3 = new TestLogWriter('3', false); const add0 = CombinedLogWriter.addLogWriter(null, writer1); assert.strictEqual(add0, writer1, 'adding to null should return added writer'); const add1 = CombinedLogWriter.addLogWriter(writer1, writer2); assert.instanceOf(add1, CombinedLogWriter, 'should create combined writer'); assert.deepStrictEqual((add1 as CombinedLogWriter).writers, [writer1, writer2], 'should combine'); const add2 = CombinedLogWriter.addLogWriter(writer3, add1); assert.instanceOf(add2, CombinedLogWriter, 'should create combined writer'); assert.deepStrictEqual((add2 as CombinedLogWriter).writers, [writer3, writer1, writer2], 'should add combined writer'); const add3 = CombinedLogWriter.addLogWriter(add1, add2); assert.instanceOf(add3, CombinedLogWriter, 'should create combined writer'); assert.deepStrictEqual((add3 as CombinedLogWriter).writers, [writer1, writer2, writer3, writer1, writer2], 'should combine combined writers'); const remove0 = CombinedLogWriter.removeLogWriter(null, writer1); assert.isNull(remove0, 'remove from null should return null'); const remove1 = CombinedLogWriter.removeLogWriter(add3, writer1); assert.instanceOf(remove1, CombinedLogWriter, 'should create combined writer'); assert.deepStrictEqual((remove1 as CombinedLogWriter).writers, [writer2, writer3, writer1, writer2], 'should remove only first instance of single from combined'); const remove2 = CombinedLogWriter.removeLogWriter(add3, add1); assert.instanceOf(remove2, CombinedLogWriter, 'should create combined writer'); assert.deepStrictEqual((remove2 as CombinedLogWriter).writers, [writer3, writer1, writer2], 'should remove combined from combined'); const remove3 = CombinedLogWriter.removeLogWriter(add3, add3); assert.isNull(remove3, 'remove from itself should return null'); const add3b = new CombinedLogWriter((add3 as CombinedLogWriter).writers); const remove4 = CombinedLogWriter.removeLogWriter(add3, add3b); assert.isNull(remove4, 'remove should work with duplicates and return null instead of empty combined'); const remove5 = CombinedLogWriter.removeLogWriter(writer1, add1); assert.isNull(remove5, 'remove combined from single should work'); }); });
nw55/es-logging
test/format.ts
<gh_stars>0 import { logFormat, LogLevel } from '@nw55/logging'; import { assert } from 'chai'; import { describe, test } from 'mocha'; describe('format', () => { test('logFormat', () => { const format = logFormat`${'level'} [${'source'}] ${logFormat.message}`; const text = format({ level: LogLevel.Warning, source: '@nw55/logging/format', message: 'Test Message' }); assert.equal(text, 'warn [@nw55/logging/format] Test Message'); }); });
nw55/es-logging
src/combined-log-writer.ts
<reponame>nw55/es-logging<gh_stars>0 import { LogMessage, LogWriter } from './common'; import { LogLevel } from './log-level'; export class CombinedLogWriter implements LogWriter { static addLogWriter(logWriter: LogWriter | null, add: LogWriter) { if (logWriter === null) return add; return new CombinedLogWriter([logWriter, add]); } static removeLogWriter(logWriter: LogWriter | null, remove: LogWriter) { if (logWriter === remove || logWriter === null) return null; if (!(logWriter instanceof CombinedLogWriter)) { if (remove instanceof CombinedLogWriter) { if (remove.writers.includes(logWriter)) return null; } return logWriter; } if (remove instanceof CombinedLogWriter) { const writersToRemove = new Map<LogWriter, number>(); for (const writer of remove.writers) writersToRemove.set(writer, (writersToRemove.get(writer) ?? 0) + 1); const writersToRetain = []; for (const writer of logWriter.writers) { const removeCount = writersToRemove.get(writer); if (removeCount !== undefined && removeCount > 0) writersToRemove.set(writer, removeCount - 1); else writersToRetain.push(writer); } if (writersToRetain.length === 0) return null; return new CombinedLogWriter(writersToRetain); } const writersToRetain = []; let removed = false; for (const writer of logWriter.writers) { if (!removed && writer === remove) removed = true; else writersToRetain.push(writer); } if (writersToRetain.length === 0) return null; return new CombinedLogWriter(writersToRetain); } private _writers: LogWriter[]; constructor(writers: readonly LogWriter[]) { this._writers = writers.flatMap(writer => writer instanceof CombinedLogWriter ? writer._writers : writer); } get writers(): readonly LogWriter[] { return this._writers; } shouldLog(level: LogLevel, source?: string) { for (const writer of this._writers) { if (writer.shouldLog(level, source)) return true; } return false; } log(message: LogMessage) { for (const writer of this._writers) { if (writer.shouldLog(message.level, message.source)) writer.log(message); } } }
nw55/es-logging
test/filter.ts
import { LogLevel, SourcePrefixLogFilter } from '@nw55/logging'; import { assert } from 'chai'; import { describe, test } from 'mocha'; describe('filter', () => { test('SourcePrefixLogFilter', () => { const filter = new SourcePrefixLogFilter('info', { '@nw55': 'warn', 'app': 'verbose', 'app/test1': 'critical' }); assert.isFalse(filter.shouldLog(LogLevel.All), 'no source All should not log'); assert.isTrue(filter.shouldLog(LogLevel.Information), 'no source Information should log'); assert.isTrue(filter.shouldLog(LogLevel.Error), 'no source Error should log'); assert.isFalse(filter.shouldLog(LogLevel.All, '@nw55'), '@nw55 All should not log'); assert.isFalse(filter.shouldLog(LogLevel.Information, '@nw55'), '@nw55 Information should not log'); assert.isTrue(filter.shouldLog(LogLevel.Error, '@nw55'), '@nw55 Error should log'); assert.isFalse(filter.shouldLog(LogLevel.All, 'app'), 'app All should not log'); assert.isTrue(filter.shouldLog(LogLevel.Information, 'app'), 'app Information should log'); assert.isTrue(filter.shouldLog(LogLevel.Error, 'app'), 'app Error should log'); assert.isFalse(filter.shouldLog(LogLevel.All, 'app/test1'), 'app/test1 All should not log'); assert.isFalse(filter.shouldLog(LogLevel.Information, 'app/test1'), 'app/test1 Information should not log'); assert.isFalse(filter.shouldLog(LogLevel.Error, 'app/test1'), 'app/test1 Error should not log'); assert.isFalse(filter.shouldLog(LogLevel.All, 'app/test2'), 'app/test2 All should not log'); assert.isTrue(filter.shouldLog(LogLevel.Information, 'app/test2'), 'app/test2 Information should log'); assert.isTrue(filter.shouldLog(LogLevel.Error, 'app/test2'), 'app/test2 Error should log'); }); });
nw55/es-logging
src/logger.ts
<filename>src/logger.ts import { AnyRecord, FatalError, LoggerStackTraceError, Mutable } from '@nw55/common'; import { LogMessage, LogWriter } from './common'; import { LogLevel } from './log-level'; type InforParams = | [message: string, details?: AnyRecord] | [message: string, code?: string, details?: AnyRecord]; function infoParamsToLogMessage(level: LogLevel, source: string | undefined, params: InforParams): LogMessage { const message = params[0]; let code; let details; if (typeof params[1] === 'string') { code = params[1]; details = params[2]; } else { details = params[1]; } return { level, source, message, code, details }; } type ErrorParams = | [message: string, details?: AnyRecord] | [message: string, code?: string, details?: AnyRecord] | [error: Error, details?: AnyRecord] | [error: Error, code?: string, details?: AnyRecord] | [message: string, error: Error, details?: AnyRecord] | [message: string, error: Error, code?: string, details?: AnyRecord]; function errorParamsToLogMessage(level: LogLevel, source: string | undefined, params: ErrorParams): Mutable<LogMessage> { let message; let error; let code; let details; if (params[0] instanceof Error) { message = params[0].toString(); error = params[0]; if (typeof params[1] === 'string') { code = params[1]; details = params[2]; } else { details = params[1]; } } else { message = params[0]; if (typeof params[1] === 'string') { code = params[1]; details = params[2]; } else if (params[1] instanceof Error) { error = params[1]; if (typeof params[2] === 'string') { code = params[2]; details = params[3]; } else { details = params[2]; } } else { details = params[1]; } } return { level, source, message, error, code, details }; } export class Logger { private _logWriter: LogWriter | null; private _source: string | undefined; constructor(logWriter: LogWriter | null, source?: string) { this._logWriter = logWriter; this._source = source; } get logWriter() { return this._logWriter; } set logWriter(v: LogWriter | null) { this._logWriter = v; } get source() { return this._source; } set source(v: string | undefined) { this._source = v; } shouldLog(level: LogLevel) { return this._logWriter?.shouldLog(level, this._source) ?? false; } private _log(message: LogMessage) { this._logWriter?.log(message); } trace(...params: InforParams) { if (this.shouldLog(LogLevel.Trace)) { const message = infoParamsToLogMessage(LogLevel.Trace, this._source, params); this._log(message); } } debug(...params: InforParams) { if (this.shouldLog(LogLevel.Debug)) { const message = infoParamsToLogMessage(LogLevel.Debug, this._source, params); this._log(message); } } verbose(...params: InforParams) { if (this.shouldLog(LogLevel.Verbose)) { const message = infoParamsToLogMessage(LogLevel.Verbose, this._source, params); this._log(message); } } info(...params: InforParams) { if (this.shouldLog(LogLevel.Information)) { const message = infoParamsToLogMessage(LogLevel.Information, this._source, params); this._log(message); } } notice(...params: InforParams) { if (this.shouldLog(LogLevel.Notice)) { const message = infoParamsToLogMessage(LogLevel.Notice, this._source, params); this._log(message); } } warn(...params: ErrorParams) { if (this.shouldLog(LogLevel.Warning)) { const message = errorParamsToLogMessage(LogLevel.Warning, this._source, params); this._log(message); } } error(...params: ErrorParams) { if (this.shouldLog(LogLevel.Error)) { const message = errorParamsToLogMessage(LogLevel.Error, this._source, params); this._log(message); } } critical(...params: ErrorParams) { if (this.shouldLog(LogLevel.Critical)) { const message = errorParamsToLogMessage(LogLevel.Critical, this._source, params); message.error ??= new LoggerStackTraceError(message.message); this._log(message); } } fatal(...params: ErrorParams): never { const message = errorParamsToLogMessage(LogLevel.Fatal, this._source, params); if (this.shouldLog(LogLevel.Fatal)) { message.error ??= new LoggerStackTraceError(message.message); this._log(message); } throw new FatalError(message.message); } }
nw55/es-logging
src/message-writer.ts
import { LogLevelKeys } from '@nw55/common'; import { LogMessage } from './common'; export interface LogMessageWriter { writeMessage(text: string, message: LogMessage): void; } function inheritLogLevelProperties<D, T = D>(properties: Partial<Record<LogLevelKeys, T>>, defaultValue: D): Record<LogLevelKeys, T | D> { const all = properties.all ?? defaultValue; const trace = properties.trace ?? all; const debug = properties.debug ?? trace; const verbose = properties.verbose ?? debug; const info = properties.info ?? verbose; const notice = properties.notice ?? info; const warn = properties.warn ?? notice; const error = properties.error ?? warn; const critical = properties.critical ?? error; const fatal = properties.fatal ?? critical; return { all, trace, debug, verbose, info, notice, warn, error, critical, fatal }; } type LogMessageTransformation = (text: string, message: LogMessage) => string; export class TransformedLogMessageWriter implements LogMessageWriter { static byLevel(baseWriter: LogMessageWriter, transformations: Partial<Record<LogLevelKeys, LogMessageTransformation>>) { const inheritedTransformations = inheritLogLevelProperties(transformations, null); const transformation: LogMessageTransformation = (text, message) => { const transformer = inheritedTransformations[message.level.key]; return transformer === null ? text : transformer(text, message); }; return new TransformedLogMessageWriter(baseWriter, transformation); } private _baseWriter: LogMessageWriter; private _transformation: LogMessageTransformation; constructor(baseWriter: LogMessageWriter, transformation: LogMessageTransformation) { this._baseWriter = baseWriter; this._transformation = transformation; } writeMessage(text: string, message: LogMessage) { const transformedText = this._transformation(text, message); this._baseWriter.writeMessage(transformedText, message); } }
nw55/es-logging
src/index.ts
export * from './combined-log-writer'; export * from './common'; export * from './console'; export * from './default-log-writer'; export * from './details-formatter'; export * from './filter'; export * from './format'; export * from './log'; export * from './log-level'; export * from './logger'; export * from './message-writer'; export * from './writable-log-message-writer';
nw55/es-logging
src/log.ts
<reponame>nw55/es-logging import { LoggingProvider } from '@nw55/common'; import { CombinedLogWriter } from './combined-log-writer'; import { LogWriter } from './common'; import { LogLevel } from './log-level'; import { Logger } from './logger'; export namespace Log { let globalLogWriter: LogWriter | null = null; export const proxyGlobalLogWriter: LogWriter = { shouldLog(level, source) { return LoggingProvider.getGlobalLoggingProvider().shouldLog(level, source); }, log(message) { LoggingProvider.getGlobalLoggingProvider().log(message.level, message.source, message.message, message); } }; export const global = new Logger(proxyGlobalLogWriter); export const loggingProvider: LoggingProvider = { shouldLog(level, source) { return globalLogWriter?.shouldLog(LogLevel.get(level), source) ?? false; }, log(level, source, message, options) { globalLogWriter?.log({ level: LogLevel.get(level), source, message, ...options }); } }; function register() { LoggingProvider.setGlobalLoggingProvider(loggingProvider); } export function getGlobalLogWriter() { return globalLogWriter; } export function setGlobalLogWriter(logWriter: LogWriter | null) { register(); globalLogWriter = logWriter; } export function addGlobalLogWriter(writer: LogWriter) { register(); globalLogWriter = CombinedLogWriter.addLogWriter(globalLogWriter, writer); } export function removeGlobalLogWriter(writer: LogWriter) { register(); globalLogWriter = CombinedLogWriter.removeLogWriter(globalLogWriter, writer); } // eslint-disable-next-line @typescript-eslint/ban-types export function createLogger(source: string | Function) { if (typeof source === 'function') source = source.name; return new Logger(proxyGlobalLogWriter, source); } }
nw55/es-logging
src/log-level.ts
import { ArgumentError, LogLevelInfo, LogLevelKeys } from '@nw55/common'; import { LogFilter } from './filter'; export class LogLevel<K extends LogLevelKeys = LogLevelKeys> implements LogLevelInfo, LogFilter { private static _byKey = new Map<LogLevelKeys, LogLevel>(); private static _byValue = new Map<number, LogLevel>(); /* eslint-disable @typescript-eslint/naming-convention */ static readonly All = new LogLevel('all', 0, 'All', false); static readonly Trace = new LogLevel('trace', 1, 'Trace', false); static readonly Debug = new LogLevel('debug', 2, 'Debug', false); static readonly Verbose = new LogLevel('verbose', 3, 'Verbose', false); static readonly Information = new LogLevel('info', 4, 'Information', false); static readonly Notice = new LogLevel('notice', 5, 'Notice', false); static readonly Warning = new LogLevel('warn', 6, 'Warning', true); static readonly Error = new LogLevel('error', 7, 'Error', true); static readonly Critical = new LogLevel('critical', 8, 'Critical', true); static readonly Fatal = new LogLevel('fatal', 9, 'Fatal', true); /* eslint-enable @typescript-eslint/naming-convention */ static get allLevels() { return this._byKey.values(); } // eslint-disable-next-line @typescript-eslint/no-shadow static get<K extends LogLevelKeys>(key: K | LogLevelInfo<K>): LogLevel<K> { if (typeof key === 'string') return LogLevel.fromKey(key); return LogLevel.fromKey(key.key); } // eslint-disable-next-line @typescript-eslint/no-shadow static fromKey<K extends LogLevelKeys>(key: K): LogLevel<K> { const level = LogLevel._byKey.get(key); if (level === undefined) throw new ArgumentError(); return level as LogLevel<K>; } static fromValue(value: number): LogLevel { const level = LogLevel._byValue.get(value); if (level === undefined) throw new ArgumentError(); return level; } private _key: K; private _value: number; private _name: string; private _symbol: string; private _isError: boolean; constructor(key: K, value: number, name: string, isError: boolean) { this._key = key; this._value = value; this._name = name; this._symbol = name.charAt(0); this._isError = isError; LogLevel._byKey.set(key, this); LogLevel._byValue.set(value, this); } get key() { return this._key; } get value() { return this._value; } get name() { return this._name; } get symbol() { return this._symbol; } get isError() { return this._isError; } shouldLog(level: LogLevel) { return level._value >= this._value; } shouldLogMessage(message: { level: LogLevel; }) { return this.shouldLog(message.level); } valueOf() { return this._value; } toString() { return 'LogLevel.' + this._name; } }
nw55/es-logging
src/default-log-writer.ts
<gh_stars>0 import { LogMessage, LogWriter } from './common'; import { LogFilter } from './filter'; import { LogFormat, logFormat } from './format'; import { LogLevel } from './log-level'; import { LogMessageWriter } from './message-writer'; export interface DefaultLogWriterOptions { readonly filter?: LogFilter; readonly format?: LogFormat; readonly messageWriter: LogMessageWriter; } export class DefaultLogWriter implements LogWriter { private _filter: LogFilter; private _format: LogFormat; private _messageWriter: LogMessageWriter; constructor(options: DefaultLogWriterOptions) { this._filter = options.filter ?? LogLevel.Information; this._format = options.format ?? logFormat.message; this._messageWriter = options.messageWriter; } shouldLog(level: LogLevel, source?: string) { return this._filter.shouldLog(level, source); } log(message: LogMessage) { if (this._filter.shouldLogMessage(message)) { const text = this._format(message); this._messageWriter.writeMessage(text, message); } } }
nw55/es-logging
src/details-formatter.ts
import { LogMessage } from './common'; export type LogErrorFormatter = (error: Error, message: LogMessage) => string; export type LogDetailsFormatter = (details: unknown, message: LogMessage) => string;
nw55/es-logging
src/writable-log-message-writer.ts
<filename>src/writable-log-message-writer.ts import { LogMessage } from './common'; import { LogDetailsFormatter, LogErrorFormatter } from './details-formatter'; import { defaultLogFilter, LogFilter } from './filter'; import { LogMessageWriter } from './message-writer'; const asStringFormatter: LogDetailsFormatter = obj => String(obj); export interface WritableLogMessageWriterOptions { readonly eol?: string; readonly logErrors?: boolean | LogFilter; readonly logDetails?: boolean | LogFilter; readonly errorFormatter?: LogErrorFormatter; readonly detailsFormatter?: LogDetailsFormatter; } interface Writable { write(data: string): void; } export class WritableLogMessageWriter implements LogMessageWriter { private _writable: Writable; private _eol: string; private _logErrors: LogFilter; private _logDetails: LogFilter; private _errorFormatter: LogErrorFormatter; private _detailsFormatter: LogDetailsFormatter; constructor(writable: Writable, options: WritableLogMessageWriterOptions = {}) { this._writable = writable; this._eol = options.eol ?? '\n'; this._logErrors = defaultLogFilter(options.logErrors ?? true); this._logDetails = defaultLogFilter(options.logDetails ?? false); this._errorFormatter = options.errorFormatter ?? asStringFormatter; this._detailsFormatter = options.detailsFormatter ?? asStringFormatter; } writeMessage(text: string, message: LogMessage) { this._writable.write(text); this._writable.write(this._eol); if (message.error !== undefined && this._logErrors.shouldLogMessage(message)) { const errorString = this._errorFormatter(message.error, message); this._writable.write(errorString); this._writable.write(this._eol); } if (message.details !== undefined && this._logDetails.shouldLogMessage(message)) { const detailsString = this._detailsFormatter(message.details, message); this._writable.write(detailsString); this._writable.write(this._eol); } } }
nw55/es-logging
src/common.ts
import { LogDetails } from '@nw55/common'; import { LogLevel } from './log-level'; export interface LogMessage extends LogDetails { readonly level: LogLevel; readonly source?: string; readonly message: string; } export interface LogWriter { shouldLog: (level: LogLevel, source?: string) => boolean; log: (message: LogMessage) => void; }
nw55/es-logging
src/console.ts
<gh_stars>0 import { LogMessage } from './common'; import { defaultLogFilter, LogFilter } from './filter'; import { LogMessageWriter } from './message-writer'; type DetailsAndErrorParams = | [message: string, details?: unknown] | [message: string, error: Error, details?: unknown]; type ConsoleLogMessageWriterOptions = Readonly<{ logErrors?: true | LogFilter; logDetails: true | LogFilter; writer: (...params: DetailsAndErrorParams) => void; errorWriter?: (...params: DetailsAndErrorParams) => void; } | { logErrors?: true | LogFilter; logDetails?: false; writer: (message: string, error?: Error) => void; errorWriter?: (message: string, error?: Error) => void; } | { logErrors: false; logDetails: true | LogFilter; writer: (message: string, details?: unknown) => void; errorWriter?: (message: string, details?: unknown) => void; } | { logErrors: false; logDetails?: false; writer: (message: string) => void; errorWriter?: (message: string) => void; }>; interface Console { log(text: string, ...args: unknown[]): void; error(text: string, ...args: unknown[]): void; } type UnsafeWriter = (text: string, ...args: unknown[]) => void; export class ConsoleLogMessageWriter implements LogMessageWriter { static createDefault(console: Console, details: 'none' | 'errors' | 'details' | 'all' = 'errors') { return new ConsoleLogMessageWriter({ writer: console.log.bind(console), errorWriter: console.error.bind(console), logErrors: details === 'errors' || details === 'all', logDetails: details === 'details' || details === 'all' }); } private _writer: UnsafeWriter; private _errorWriter: UnsafeWriter; private _logErrors: LogFilter; private _logDetails: LogFilter; constructor(options: ConsoleLogMessageWriterOptions) { this._writer = options.writer as UnsafeWriter; this._errorWriter = (options.errorWriter ?? options.writer) as UnsafeWriter; this._logErrors = defaultLogFilter(options.logErrors ?? true); this._logDetails = defaultLogFilter(options.logDetails ?? false); } writeMessage(text: string, message: LogMessage) { const writer = message.level.isError ? this._errorWriter : this._writer; if (this._logErrors.shouldLogMessage(message) && message.error !== undefined) { if (this._logDetails.shouldLogMessage(message) && message.details !== undefined) writer(text, message.error, message.details); else writer(text, message.error); } else if (this._logDetails.shouldLogMessage(message) && message.details !== undefined) { writer(text, message.details); } else { writer(text); } } }
nw55/es-logging
src/format.ts
<reponame>nw55/es-logging import { ArgumentError } from '@nw55/common'; import { LogMessage } from './common'; export type LogFormat = (message: LogMessage) => string; type LogFormatPlaceholder = keyof typeof knownLogFormats | LogFormat; function placeholderLogFormat(placeholder: LogFormatPlaceholder): LogFormat { if (typeof placeholder === 'string') return knownLogFormats[placeholder]; return placeholder; } function concatenatedLogFormat(segments: LogFormat[]): LogFormat { return message => segments.map(segment => segment(message)).join(''); } export function logFormat(strings: TemplateStringsArray, ...placeholders: LogFormatPlaceholder[]): LogFormat { const segments: LogFormat[] = []; for (let i = 0; i < strings.length; i++) { if (i !== 0) segments.push(placeholderLogFormat(placeholders[i - 1])); if (strings[i] !== '') segments.push(logFormat.literal(strings[i])); } return concatenatedLogFormat(segments); } // eslint-disable-next-line no-redeclare -- merging function and namespace export namespace logFormat { const datePad = (v: number) => v < 10 ? '0' + String(v) : String(v); const isoDateFormat: LogFormat = () => { const now = new Date(); return `${now.getUTCFullYear()}-${datePad(now.getUTCMonth() + 1)}-${datePad(now.getUTCDate())}`; }; const localeDateFormat: LogFormat = () => new Date().toLocaleDateString(); const unixDateFormat: LogFormat = () => Date.now().toString(); const isoTimeFormat: LogFormat = () => { const now = new Date(); return `${datePad(now.getUTCHours())}:${datePad(now.getUTCMinutes())}:${datePad(now.getUTCSeconds())}.${(now.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5)}`; }; const localeTimeFormat: LogFormat = () => new Date().toLocaleTimeString(); const isoDateTimeFormat: LogFormat = () => new Date().toISOString(); const localeDateTimeFormat: LogFormat = () => new Date().toLocaleString(); export function date(format: 'iso' | 'locale' | 'unix' = 'iso'): LogFormat { switch (format) { case 'iso': return isoDateFormat; case 'locale': return localeDateFormat; case 'unix': return unixDateFormat; } throw new ArgumentError(); } export function time(format: 'iso' | 'locale' = 'iso'): LogFormat { switch (format) { case 'iso': return isoTimeFormat; case 'locale': return localeTimeFormat; } throw new ArgumentError(); } export function dateTime(format: 'iso' | 'locale' = 'iso'): LogFormat { switch (format) { case 'iso': return isoDateTimeFormat; case 'locale': return localeDateTimeFormat; } throw new ArgumentError(); } const levelKeyFormat: LogFormat = message => message.level.key; const levelNameFormat: LogFormat = message => message.level.name; const levelSymbolFormat: LogFormat = message => message.level.symbol; export function level(format: 'key' | 'name' | 'symbol' = 'key'): LogFormat { switch (format) { case 'key': return levelKeyFormat; case 'name': return levelNameFormat; case 'symbol': return levelSymbolFormat; } throw new ArgumentError(); } export function source(defaultSource = ''): LogFormat { return message => message.source ?? defaultSource; } export function sourceFormat(format: string, placeholder = '%', defaultSource = ''): LogFormat { return message => message.source === undefined ? defaultSource : format.replace(placeholder, message.source); } export function code(defaultCode = ''): LogFormat { return message => message.code ?? defaultCode; } export function codeFormat(format: string, placeholder = '%', defaultCode = ''): LogFormat { return message => message.code === undefined ? defaultCode : format.replace(placeholder, message.code); } const errorNameFormat: LogFormat = message => message.error?.name ?? ''; const errorMessageFormat: LogFormat = message => message.error?.message ?? ''; const errorNameAndMessageFormat: LogFormat = message => message.error === undefined ? '' : `${message.error.name}: ${message.error.message}`; export function error(format: 'name' | 'message' | 'name-and-message' = 'name-and-message'): LogFormat { switch (format) { case 'name': return errorNameFormat; case 'message': return errorMessageFormat; case 'name-and-message': return errorNameAndMessageFormat; } throw new ArgumentError(); } export const detailsString: LogFormat = message => String(message.details); // eslint-disable-next-line @typescript-eslint/no-shadow export const message: LogFormat = message => message.message; export function literal(text: string): LogFormat { return () => text; } } const knownLogFormats = { date: logFormat.date(), time: logFormat.time(), datetime: logFormat.dateTime(), level: logFormat.level(), source: logFormat.source(), code: logFormat.code(), error: logFormat.error(), details: logFormat.detailsString, message: logFormat.message };
ZxBing0066/zlib
packages/generate-password/index.ts
<reponame>ZxBing0066/zlib // exclude `l`, `o` const DefaultLowerCaseChars = 'abcdefghijkmnpqrstuvwxyz'; // exclude 'I', 'O' const DefaultUpperCaseChars = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; // exclude '1' const DefaultDigits = '23456789'; // symbols const DefaultSymbols = '-_.:!'; // sequences of '-' or '_' will change to long strokes in many fonts, that will make the password difficult to read const isDifficultToRead = (password: string) => /[_]{2}|[\-]{2}/.test(password); const randomIndex = (max: number) => Math.floor(Math.random() * max); const randomPick = (collection: string | string[]) => collection[randomIndex(collection.length)]; const shuffle = (passwordChars: string[], l = passwordChars.length, remainingTimes = 0) => { const r = passwordChars.length; for (let i = 0; i < l; i++) { const randomI = randomIndex(r); const tmp = passwordChars[i]; passwordChars[i] = passwordChars[randomI]; passwordChars[randomI] = tmp; } if (remainingTimes > 0) shuffle(passwordChars, l, remainingTimes - 1); }; const passwordGenerate = ({ length: passwordLength = 15, symbols: Symbols, digits: Digits = DefaultDigits, lowerCaseChars: LowerCaseChars = DefaultLowerCaseChars, upperCaseChars: UpperCaseChars = DefaultUpperCaseChars, customChars: CustomChars, shuffleTimes = 1 }: { /** length of the password, pass a [min, max] as length range */ length?: number | [number, number]; /** custom your symbol collection */ symbols?: string | true; /** custom your digit collection */ digits?: string; /** custom your lowercase char collection */ lowerCaseChars?: string; /** custom your uppercase char collection */ upperCaseChars?: string; /** add your own char collection */ customChars?: string; /** the number of do shuffle */ shuffleTimes?: number; } = {}) => { if (Array.isArray(passwordLength)) { const [min, max] = passwordLength; if (!min || !max || max < min || min < 5 || max > 99) throw new Error(`Invalid passwordLength: ${JSON.stringify(passwordLength)}`); passwordLength = min + randomIndex(max - min + 1); } if (passwordLength < 5 || passwordLength > 99) throw new Error(`Invalid passwordLength: ${passwordLength}`); if (Symbols === true) Symbols = DefaultSymbols; const passwordChars = []; const allCollections: string[] = []; [LowerCaseChars, UpperCaseChars, Digits, Symbols, CustomChars].forEach( collection => collection?.length && allCollections.push(collection) ); if (!allCollections.length) throw new Error(`Invalid options without any char for generate password`); const al = allCollections.length; for (let i = 0; i < al; i++) { passwordChars.push(randomPick(allCollections[i])); } const restCount = passwordLength - passwordChars.length; const fullCollection = allCollections.join(''); for (let i = 0; i < restCount; i++) { passwordChars.push(randomPick(fullCollection)); } shuffle(passwordChars, al); if (shuffleTimes > 0) shuffle(passwordChars, passwordLength, shuffleTimes - 1); const needCheckReadAbility = fullCollection.indexOf('_') >= 0 || fullCollection.indexOf('-') >= 0; let remainingAttempts = 5; while (needCheckReadAbility && isDifficultToRead(passwordChars.join('')) && remainingAttempts--) { shuffle(passwordChars); } return passwordChars.join(''); }; export default passwordGenerate;
ZxBing0066/zlib
packages/shuffle/index.ts
<filename>packages/shuffle/index.ts const randomIndex = (l: number) => Math.floor(Math.random() * l); function shuffle( target: string, option?: { // By default, string shuffle will broken with char to multiple chars, use this for fix fix?: true; } ): string; function shuffle<T = any>( target: T[], option?: { // Default run as a pure function, shuffle will not affect to your origin array, you can set to false for close this pure?: boolean; } ): T[]; function shuffle<T = any>( target: T[] | string, option?: { fix?: boolean; pure?: boolean; } ) { const isString = typeof target === 'string'; let shuffleTarget: T[] | string[]; if (isString) { if (option?.fix) { shuffleTarget = Array.from(target); } else { shuffleTarget = target.split(''); } } else { if (option?.pure === false) { shuffleTarget = target; } else { shuffleTarget = target.slice(); } } let l = shuffleTarget.length; while (l) { let i = randomIndex(l--); const tmp = shuffleTarget[i]; shuffleTarget[i] = shuffleTarget[l]; shuffleTarget[l] = tmp; } return isString ? shuffleTarget.join('') : shuffleTarget; } export default shuffle;
ZxBing0066/zlib
packages/diff/index.ts
<reponame>ZxBing0066/zlib<gh_stars>1-10 interface Diff<T = any> { type: 'ADD' | 'REMOVE' | 'CHANGE'; path: (string | number)[]; old?: T; new?: T; } const needDig = (obj: any) => { if (obj !== null && typeof obj === 'object') { const cname = Object.getPrototypeOf(obj).constructor.name; if (cname === 'Object' || cname === 'Array') return cname; } }; const diff = <T = any, TObj = Record<string, T> | T[]>(oldObj: TObj, newObj: TObj) => { const result: Diff[] = []; const _diff = (oldObj: TObj, newObj: TObj, isArray: boolean) => { if (isArray) { const oldL = (oldObj as unknown as any[]).length, newL = (newObj as unknown as any[]).length; for (let i = oldL; i < newL; i++) { result.push({ type: 'ADD', path: [i], new: newObj[i] }); } } else { for (const key in newObj) { if (!(key in oldObj)) { result.push({ type: 'ADD', path: [key], new: newObj[key] }); } } } for (let key in oldObj) { isArray && ((key as string | number) = +key); const oldV = oldObj[key]; const path = [key]; if (!(key in newObj)) { result.push({ type: 'REMOVE', path, old: oldV }); continue; } const newV = newObj[key]; const t = needDig(oldV); if (!t || t !== needDig(newV)) { if (oldV !== newV) { result.push({ type: 'CHANGE', path, old: oldV, new: newV }); } continue; } let i = result.length; _diff(oldV as unknown as TObj, newV as unknown as TObj, t === 'Array'); const j = result.length; for (; i < j; i++) { result[i].path.unshift(key); } } }; _diff(oldObj == null ? ({} as TObj) : oldObj, newObj == null ? ({} as TObj) : newObj, Array.isArray(oldObj)); return result; }; export default diff;
abraham/gde-social
packages/web/functions/src/mdc.test.ts
import { activatedClass } from './mdc'; test('activatedClass', () => { expect(activatedClass('angular', 'angular')).toEqual( 'mdc-list-item--activated', ); expect(activatedClass('angular', 'android')).toEqual(''); });
abraham/gde-social
packages/stream/pubsub.ts
import { PubSub, Topic } from '@google-cloud/pubsub'; const projectId = process.env.GCLOUD_PROJECT_ID; const pubsub = new PubSub({ projectId, }); export async function publish(statusId: string): Promise<boolean> { const topicName = `projects/${projectId}/topics/new_status`; await getTopicAndPublish(topicName, statusId); return true; } async function getTopicAndPublish(topicName: string, statusId: string) { const publisher = await getTopic(topicName); const data = Buffer.from(JSON.stringify({ statusId })); return publisher.publish(data).catch(() => { return createTopic(topicName) .then(() => getTopic(topicName)) .then((publisher) => publisher.publish(data)); }); } async function getTopic(topicName: string): Promise<Topic> { return pubsub.topic(topicName); } async function createTopic(topicName: string): Promise<Topic> { const [topic] = await pubsub.createTopic(topicName); return topic; }
abraham/gde-social
packages/web/functions/src/mdc.ts
<reponame>abraham/gde-social export const activatedClass = (a: string, b: string): string => a === b ? 'mdc-list-item--activated' : '';
abraham/gde-social
packages/web/functions/src/data/status.data.ts
<reponame>abraham/gde-social<gh_stars>1-10 import { Status } from 'twitter-d'; export const status: Status = { created_at: 'Tue Mar 21 20:50:14 +0000 2006', id: 20, id_str: '20', full_text: 'just setting up my twttr', truncated: false, display_text_range: [0, 24], entities: { hashtags: [], symbols: [], user_mentions: [], urls: [], }, source: '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', in_reply_to_status_id: null, in_reply_to_status_id_str: null, in_reply_to_user_id: null, in_reply_to_user_id_str: null, in_reply_to_screen_name: null, user: { id: 12, id_str: '12', name: 'jack', screen_name: 'jack', location: '', description: '', url: null, entities: { description: { urls: [], }, }, protected: false, followers_count: 4133490, friends_count: 3196, listed_count: 27270, created_at: 'Tue Mar 21 20:50:14 +0000 2006', favourites_count: 19728, verified: true, statuses_count: 22897, profile_image_url_https: 'https://pbs.twimg.com/profile_images/839863609345794048/mkpdB9Tf_normal.jpg', profile_banner_url: 'https://pbs.twimg.com/profile_banners/12/1483046077', default_profile: false, default_profile_image: false, }, coordinates: null, place: null, contributors: null, is_quote_status: false, retweet_count: 106177, favorite_count: 79867, favorited: false, retweeted: false, lang: 'en', };
abraham/gde-social
packages/web/functions/src/status.ts
import { Status, convertDate, parseHashtags } from './twitter'; export const version = 2; export function buildStatus(status: Status) { const createdAt = convertDate(status.created_at); const hashtags = parseHashtags(status).reduce( (sortableHashtags: any, hashtag: string) => { sortableHashtags[hashtag] = createdAt; return sortableHashtags; }, {}, ); const hasLinks = (status.entities.urls || []).length > 0; return { createdAt, data: JSON.stringify(status), hashtags, hasLinks, updatedAt: Date.now(), version, }; }
abraham/gde-social
packages/web/scripts/migrate.ts
import * as admin from 'firebase-admin'; import { buildStatus, version } from '../functions/src/status'; admin.initializeApp(); const db = admin.firestore(); async function migrate() { let next = true; let query = page(); let migrated = 0; while (next) { const snapshot = await query.get(); const lastDocument = snapshot.docs[snapshot.docs.length - 1]; console.log(`Updating ${snapshot.docs.length} documents`); const batch = db.batch(); snapshot.forEach((document) => { migrated++; batch.set(document.ref, buildStatus(JSON.parse(document.data().data))); }); batch.commit(); if (snapshot.docs.length === 0) { next = false; } else { query = page(lastDocument); } } console.log(`Migrated ${migrated}`); } function page( lastDocument?: FirebaseFirestore.QueryDocumentSnapshot, ): FirebaseFirestore.Query { let query = db .collection('statuses') .orderBy('version') .orderBy('createdAt') .where('version', '<', version) .limit(500); if (lastDocument) { query = query.startAfter( lastDocument.data().version, lastDocument.data().createdAt, ); } return query; } migrate();
abraham/gde-social
packages/web/scripts/copy-data.ts
<reponame>abraham/gde-social import * as admin from 'firebase-admin'; const fromProjectId = 'gde-social'; const toProjectId = 'gde-social-dev'; const limit = 100; const fromApp = admin.initializeApp({ projectId: fromProjectId }, 'from'); const fromDb = fromApp.firestore(); const toApp = admin.initializeApp({ projectId: toProjectId }, 'to'); const toDb = toApp.firestore(); console.log(`Copying from ${fromProjectId} to ${toProjectId}`); async function copy() { const collections = await fromDb.getCollections(); for (const collection of collections) { const snapshots = await collection .orderBy('createdAt', 'desc') .limit(limit) .get(); console.log(`Copying ${snapshots.size} ${collection.id} documents`); const batch = toDb.batch(); snapshots.forEach((document) => { batch.set( toDb.collection(collection.id).doc(document.id), document.data(), ); }); batch.commit(); } } copy();
abraham/gde-social
packages/web/scripts/count.ts
<reponame>abraham/gde-social import * as admin from 'firebase-admin'; admin.initializeApp(); const db = admin.firestore(); async function count() { let next = true; let query = page(); let counted = 0; while (next) { const snapshot = await query.get(); const lastDocument = snapshot.docs[snapshot.docs.length - 1]; counted = counted + snapshot.docs.length; console.log(`Counted ${snapshot.docs.length} of ${counted} documents`); if (snapshot.docs.length === 0) { next = false; } else { query = page(lastDocument); } } console.log(`Counted ${counted}`); } function page( lastDocument?: FirebaseFirestore.QueryDocumentSnapshot, ): FirebaseFirestore.Query { let query = db.collection('statuses').orderBy('createdAt').limit(500); if (lastDocument) { query = query.startAfter(lastDocument.data().createdAt); } return query; } count();
abraham/gde-social
packages/web/scripts/bearer.ts
import * as request from 'request-promise-native'; const config = require('../.runtimeconfig.json').twitter; const credentials = Buffer.from(`${config.key}:${config.secret}`).toString( 'base64', ); const url = 'https://api.twitter.com/oauth2/token'; interface BearerToken { token_type: string; access_token: string; } async function getBearerToken() { const token: BearerToken = await request({ url: url, method: 'POST', headers: { Authorization: `Basic ${credentials}`, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, body: 'grant_type=client_credentials', }).then(JSON.parse); console.log('access_token:'); console.log(token.access_token); } getBearerToken();
abraham/gde-social
packages/stream/app.ts
<gh_stars>1-10 import * as Twit from 'twit'; import { Status, User } from 'twitter-d'; import { publish } from './pubsub'; const config = require('./.runtimeconfig.json').twitter; const T = new Twit({ ...config, strictSSL: true, } as Twit.Options); // TODO: remove 'as Twit.Options' const listParams = { slug: 'web-gdes', owner_screen_name: 'robertnyman', count: 5000, }; async function getListMembers(client: Twit): Promise<User[]> { const t = await client.get('lists/members', listParams); return (t.data as { users: User[] }).users; } async function run() { console.log('Running'); const users = await getListMembers(T); const userIds = users.map((user) => user.id_str); console.log(`Got ${userIds.length} list members`); // TODO: remove `as any` const stream = T.stream('statuses/filter', { follow: userIds.join(','), } as any); console.log('Connected to stream'); stream.on('tweet', async (tweet: Status) => { if (userIds.includes(tweet.user.id_str)) { const result = await publish(tweet.id_str); console.log(`New tweet: ${tweet.id_str}, status: ${result}`); } else { console.log(`Ignoring related tweet: ${tweet.id_str}`); } }); } run();
abraham/gde-social
packages/web/functions/src/pagination.test.ts
<reponame>abraham/gde-social import { LIMIT } from './pagination'; test('LIMIT', () => { expect(LIMIT).toEqual(25); });
abraham/gde-social
packages/web/functions/src/index.ts
import * as express from 'express'; import * as exphbs from 'express-handlebars'; import * as admin from 'firebase-admin'; import * as functions from 'firebase-functions'; import { activatedClass as mdcActivatedClass } from './mdc'; import { LIMIT } from './pagination'; import { buildStatus } from './status'; import { Status, TwitterClient } from './twitter'; admin.initializeApp(); const app = express(); const db = admin.firestore(); const twitter = TwitterClient(functions.config().twitter); const suggestedHashtags = [ 'angular', 'perfmatters', 'polymer', 'pwa', 'webcomponents', ]; app.set('view engine', 'handlebars'); app.engine( 'handlebars', exphbs({ defaultLayout: 'index', helpers: { mdcActivatedClass }, }), ); app.get('/', async (_request, response) => { const snaps = await db .collection('statuses') .orderBy('createdAt', 'desc') .limit(LIMIT) .get(); render(response, snaps, 'index'); }); app.get('/links', async (_request, response) => { const snaps = await db .collection('statuses') .orderBy('createdAt', 'desc') .where('hasLinks', '==', true) .limit(LIMIT) .get(); render(response, snaps, 'links'); }); app.get( '/hashtag/:hashtag', async (request: express.Request, response: express.Response) => { const hashtag = request.params.hashtag.toLowerCase().trim(); const snaps = await db .collection('statuses') .where(`hashtags.${hashtag}`, '>', 0) .orderBy(`hashtags.${hashtag}`, 'desc') .limit(LIMIT) .get(); render(response, snaps, hashtag); }, ); exports.app = functions.https.onRequest(app); exports.update_statuses = functions.pubsub .topic('fifteen-minute-tick') .onPublish(getNewStatuses); exports.new_status = functions.pubsub .topic('new_status') .onPublish(getNewStatuses); async function getNewStatuses( _message: functions.pubsub.Message, _context: functions.EventContext, ) { const latestId = await latestStatusId(); const tweets = await twitter.getListTweets(200, latestId); console.log(`Got ${tweets.length} tweets`); return Promise.all(tweets.map(setStatus)).catch((error) => console.error(new Error(`ERROR saving all, ${error}`)), ); } function setStatus(tweet: Status) { return db .collection('statuses') .doc(tweet.id_str) .set(buildStatus(tweet)) .catch((error) => console.error(new Error(`ERROR saving ${tweet.id_str}, ${error}`)), ); } function render( response: express.Response, snaps: FirebaseFirestore.QuerySnapshot, routeName: string, ) { const statuses = snaps.docs.map((snap) => snap.data()); const newestCreatedAt = statuses.length > 0 ? statuses[0].createdAt : '0'; const oldestCreatedAt = statuses.length > 0 ? statuses[statuses.length - 1].createdAt : ''; response.set('Cache-Control', 'public, max-age=300, s-maxage=300'); response.render('index', { recentHashtags: getHashtags(statuses), suggestedHashtags, oldestCreatedAt, newestCreatedAt, routeName, statuses, }); } function getHashtags(statuses: FirebaseFirestore.DocumentData[]): string[] { const hashtags: string[] = []; statuses.forEach((status) => { Object.keys(status.hashtags).forEach((hashtag: string) => { if (!hashtags.includes(hashtag)) { hashtags.push(hashtag); } }); }); return hashtags; } async function latestStatusId(): Promise<string> { const snaps = await db .collection('statuses') .orderBy('createdAt', 'desc') .limit(1) .get(); if (snaps.docs.length > 0) { return snaps.docs[0].id; } else { return '1'; } }
abraham/gde-social
packages/web/functions/src/twitter.ts
import * as Twit from 'twit'; import { Status, User } from 'twitter-d'; export { Status }; export interface TwitterCredentials { consumer_key: string; consumer_secret: string; access_token: string; access_token_secret: string; } export interface StatusRef { id: string; updatedAt: Date; data: Status; } const defaultParams = { include_entities: true, tweet_mode: 'extended', }; const listParams = { ...defaultParams, slug: 'web-gdes', owner_screen_name: 'robertnyman', }; const timelineParams = { ...defaultParams, }; export function TwitterClient(credentials: TwitterCredentials) { const client = buildClient(credentials); return { getListMembers: (count: number) => getListMembers(client, count), getListTweets: (count: number, sinceId: string) => getListTweets(client, count, sinceId), getUserTweets: (screenName: string, count: number, maxId?: string) => getUserTweets(client, screenName, count, maxId), }; } export async function getListMembers( client: Twit, count: number, ): Promise<User[]> { const t = await client.get('lists/members', { ...listParams, count }); return (t.data as { users: User[] }).users; } export async function getListTweets( client: Twit, count: number, since_id: string, ): Promise<Status[]> { const t = await client.get('lists/statuses', { ...listParams, count, since_id, }); return t.data as Status[]; } export async function getUserTweets( client: Twit, screen_name: string, count: number, max_id?: string, ): Promise<Status[]> { const options: Twit.Params = { ...timelineParams, screen_name, count }; if (max_id) { options.max_id = max_id; } const t = await client.get('statuses/user_timeline', options); return t.data as Status[]; } function buildClient(credentials: TwitterCredentials): Twit { return new Twit({ ...credentials, app_only_auth: true, }); } export function convertDate(date: string): number { return new Date(Date.parse(date.replace(/( \+)/, ' UTC$1'))).getTime(); } export function parseHashtags(status: Status): string[] { return (status.entities.hashtags || []).map((hashtag) => hashtag.text.toLowerCase(), ); }
abraham/gde-social
packages/web/scripts/crawl-list.ts
<reponame>abraham/gde-social<filename>packages/web/scripts/crawl-list.ts import * as admin from 'firebase-admin'; import { TwitterClient } from '../functions/src/twitter'; import { buildStatus } from '../functions/src/status'; const config = require('../.runtimeconfig.json').twitter; admin.initializeApp(); const db = admin.firestore(); const twitter = TwitterClient(config); async function crawl() { let counted = 0; let request = 0; const users = await twitter.getListMembers(5000); console.log(`Getting tweets from ${users.length} users`); for (const user of users) { let next = true; let lastId: string | undefined; while (next) { request++; const tweets = await twitter.getUserTweets(user.screen_name, 200, lastId); console.log( `Getting ${tweets.length} tweets from ${ user.screen_name } [index: ${users.indexOf(user)}, request: ${request}]`, ); const batch = db.batch(); for (const tweet of tweets) { counted++; const doc = db.collection('statuses').doc(tweet.id_str); batch.set(doc, buildStatus(tweet)); } await batch.commit(); if (tweets.length <= 1) { next = false; } else { lastId = tweets[tweets.length - 1].id_str; } } } console.log(`Got ${counted} tweets give or take`); } crawl();
abraham/gde-social
packages/web/functions/src/status.test.ts
import { version, buildStatus } from './status'; import { status } from './data/status.data'; test('version', () => { expect(version).toEqual(2); }); beforeEach(() => { jest.spyOn(global.Date, 'now').mockImplementation(() => 123456789); }); afterEach(() => { jest.clearAllMocks(); }); test('buildStatus', () => { expect(buildStatus(status)).toEqual({ createdAt: 1142974214000, data: JSON.stringify(status), hasLinks: false, hashtags: {}, updatedAt: Date.now(), version: 2, }); });
vcalendars/internal-season-api
index.ts
import Knex from 'knex'; import Logger from '@danielemeryau/logger'; import { InternalSeasonServiceServer } from '@teamest/internal-season-server'; import InternalSeasonService from './src/service'; const logger = new Logger('internal-season-api'); const PORT = (process.env.PORT && parseInt(process.env.PORT)) || 9010; async function start() { const dbConnection = { host: process.env.MYSQL_HOST || 'localhost', user: process.env.MYSQL_USER || 'internal_season', password: process.env.MYSQL_PASS || '<PASSWORD>', database: process.env.MYSQL_DATABASE || 'season_data', }; logger.info(`Connecting to MySql ${dbConnection.user}@${dbConnection.host}`); const knex = Knex({ client: 'mysql2', connection: dbConnection, migrations: { tableName: 'migrations', }, }); try { await knex.raw('select 1+1 as result'); logger.info('Connected to database successfully'); } catch (err) { logger.error('Error connecting to database', err); throw new Error('Error connecting to database'); } const service = new InternalSeasonService(knex, logger); const server = new InternalSeasonServiceServer( 'internal-season-api/server', PORT, service, ); server.listen(); } start() .then(() => {}) .catch((error) => { console.error(error); process.exit(1); });
vcalendars/internal-season-api
migrations/20200130162934_table_creation.ts
import * as Knex from 'knex'; export async function up(knex: Knex): Promise<any> { await knex.schema.createTable('team_season', function(table) { table.uuid('team_season_id').primary(); table.string('team_name').notNullable(); table.string('competition_name').notNullable(); table.string('season_name').notNullable(); table.timestamps(false, true); }); return knex.schema.createTable('team_season_version', function(table) { table.uuid('team_season_version_id').primary(); table.uuid('team_season_id').notNullable(); table.foreign('team_season_id').references('team_season.team_season_id'); table.json('events').notNullable(); table.dateTime('first_scraped').notNullable(); table.dateTime('last_scraped').notNullable(); }); } export async function down(knex: Knex): Promise<any> { await knex.schema.dropTable('team_season_version'); return knex.schema.dropTable('team_season'); }
vcalendars/internal-season-api
src/data.types.ts
import { SerialisedEvent } from "@teamest/models/raw"; export interface TeamSeason { team_season_id: string; team_name: string; competition_name: string; season_name: string; created_at: string; updated_at: string; } export interface TeamSeasonVersion { team_season_version_id: string; team_season_id: string; events: SerialisedEvent[]; first_scraped: string; last_scraped: string; }
vcalendars/internal-season-api
knexfile.ts
<reponame>vcalendars/internal-season-api<filename>knexfile.ts module.exports = { development: { client: 'mysql2', connection: { host: process.env.MYSQL_HOST || 'localhost', user: process.env.MYSQL_USER || 'internal_season', password: process.env.MYSQL_PASS || '<PASSWORD>', database: process.env.MYSQL_DATABASE || 'season_data', }, }, };
vcalendars/internal-season-api
src/service.ts
<filename>src/service.ts import Knex from 'knex'; import Logger from '@danielemeryau/logger'; import deepEqual from 'fast-deep-equal'; import { v4 as uuidv4 } from 'uuid'; import { Event } from '@teamest/models/raw'; import * as DataTypes from './data.types'; import { SavedTeamSeason } from '@teamest/models/processed'; import { IInternalSeasonService, InternalSeasonServiceTypes, } from '@teamest/internal-season-server'; import parseDates from './parseDates'; export function eventDataHasChanged( existing: Event[], current: Event[], ): boolean { return !deepEqual(existing, current); } export default class InternalSeasonService implements IInternalSeasonService { private knex: Knex; private logger: Logger; constructor(knex: Knex, logger: Logger) { this.knex = knex; this.logger = logger; this.GetSeasonsForTeam = this.GetSeasonsForTeam.bind(this); this.UpdateTeamSeason = this.UpdateTeamSeason.bind(this); } async GetSeasonsForTeam( request: InternalSeasonServiceTypes.GetSeasonsForTeamRequest, ): Promise<InternalSeasonServiceTypes.GetSeasonsForTeamResponse> { const { teamSpecifiers, updatedSince } = request; const teamSeasonMatches = await this.knex('team_season') .select<DataTypes.TeamSeason[]>( 'team_season_id', 'team_season.competition_name', 'team_season.season_name', 'team_season.team_name', ) .whereIn( ['competition_name', 'season_name', 'team_name'], teamSpecifiers.map((ts) => [ ts.competitionName, ts.seasonName, ts.teamName, ]), ); let matches: SavedTeamSeason[] = []; for (const match of teamSeasonMatches) { const latestVersion = await this.knex('team_season_version') .where({ team_season_id: match.team_season_id, }) .select<DataTypes.TeamSeasonVersion>( 'events', 'first_scraped', 'last_scraped', ) .modify(function (qb) { if (updatedSince) { qb.where('team_season_version.first_scraped', '>', updatedSince); } }) .orderBy('last_scraped', 'desc') .first(); if (latestVersion) { const deserialisedEvents = parseDates(latestVersion.events); matches.push({ competitionName: match.competition_name, seasonName: match.season_name, teamName: match.team_name, events: deserialisedEvents, lastChanged: latestVersion.first_scraped, lastScraped: latestVersion.last_scraped, }); } } return { matchingTeamSeasons: matches, }; } async UpdateTeamSeason( request: InternalSeasonServiceTypes.UpdateTeamSeasonRequest, ): Promise<InternalSeasonServiceTypes.UpdateTeamSeasonResponse> { let result: InternalSeasonServiceTypes.UpdateTeamSeasonResponse; const { teamSeason } = request; const { competitionName: receivedCompetitionName, seasonName: receivedSeasonName, teamName: recievedTeamName, events: receivedEvents, lastScraped: receivedLastScraped, } = teamSeason; const trx = await this.knex.transaction(); try { const existing = await trx .select<DataTypes.TeamSeason>('team_season_id') .from('team_season') .where({ season_name: receivedSeasonName, team_name: recievedTeamName, competition_name: receivedCompetitionName, }) .first(); if (existing) { this.logger.info(`Team season exists`, { id: existing.team_season_id, competitionName: receivedCompetitionName, teamName: recievedTeamName, seasonName: receivedSeasonName, }); const latestVersionEvents = await trx .select<DataTypes.TeamSeasonVersion>( 'team_season_version_id', 'events', ) .from('team_season_version') .where({ team_season_id: existing.team_season_id }) .orderBy('last_scraped', 'desc') .first(); if (!latestVersionEvents) { throw new Error( 'team_season exists without any team_season_version entries!', ); } const deserialisedLatestEvents = parseDates(latestVersionEvents.events); this.logger.debug('Diffing existing events against recieved', { deserialisedLatestEvents, receivedEvents, }); if (eventDataHasChanged(deserialisedLatestEvents, receivedEvents)) { this.logger.info('Events have changed, updating.', { competitionName: receivedCompetitionName, teamName: recievedTeamName, seasonName: receivedSeasonName, }); await trx('team_season_version').insert<DataTypes.TeamSeasonVersion>({ team_season_version_id: uuidv4(), team_season_id: existing.team_season_id, events: JSON.stringify(receivedEvents), first_scraped: receivedLastScraped, last_scraped: receivedLastScraped, }); result = { teamSeasonId: existing.team_season_id, competitionName: receivedCompetitionName, seasonName: receivedSeasonName, teamName: recievedTeamName, wasModified: true, }; } else { this.logger.info('Events are unchanged , updating last_scraped', { competitionName: receivedCompetitionName, teamName: recievedTeamName, seasonName: receivedSeasonName, }); await trx('team_season_version') .where({ team_season_version_id: latestVersionEvents.team_season_version_id, }) .update<DataTypes.TeamSeasonVersion>({ last_scraped: receivedLastScraped, }); result = { teamSeasonId: existing.team_season_id, competitionName: receivedCompetitionName, seasonName: receivedSeasonName, teamName: recievedTeamName, wasModified: false, }; } } else { this.logger.info( "Team season doesn't exist, inserting with latest events", { competitionName: receivedCompetitionName, teamName: recievedTeamName, seasonName: receivedSeasonName, }, ); const teamSeasonId = uuidv4(); await trx('team_season').insert<DataTypes.TeamSeason>({ competition_name: receivedCompetitionName, team_season_id: teamSeasonId, season_name: receivedSeasonName, team_name: recievedTeamName, }); await trx('team_season_version').insert<DataTypes.TeamSeasonVersion>({ team_season_version_id: uuidv4(), team_season_id: teamSeasonId, events: JSON.stringify(receivedEvents), first_scraped: receivedLastScraped, last_scraped: receivedLastScraped, }); result = { teamSeasonId, competitionName: receivedCompetitionName, seasonName: receivedSeasonName, teamName: recievedTeamName, wasModified: true, }; } await trx.commit(); } catch (err) { await trx.rollback(); throw err; } return result; } async destroy() { await this.knex.destroy(); } }
schippie/NG2-Stream-Pipe
example/app/app.ts
<reponame>schippie/NG2-Stream-Pipe import {Component} from 'angular2/core'; import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router'; import {HomeComponent} from './components/home/home'; @Component({ selector: 'my-app', template: '<router-outlet></router-outlet>', directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ { path: '/', redirectTo: ['/Home'] }, { path: '/home', component: HomeComponent, name: 'Home' } ]) export class AppComponent { constructor() { } }
schippie/NG2-Stream-Pipe
example/app/injectables/providers.ts
/** * Within this file you can specify all the providers that you require within your application * This is kept outside of the main.ts to make that file a lot cleaner. */ import {ROUTER_PROVIDERS} from 'angular2/router'; export const CUSTOM_PROVIDERS = [ ROUTER_PROVIDERS ];
schippie/NG2-Stream-Pipe
example/app/main.ts
<gh_stars>1-10 import '!style!css!sass!./assets/css/style.scss'; import 'es6-shim'; import 'zone.js'; import 'reflect-metadata'; import {provide, enableProdMode} from 'angular2/core'; import {bootstrap, ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/browser'; import {CUSTOM_PROVIDERS} from './injectables/providers'; import {AppComponent} from './app' //set the environment type const ENV_PROVIDERS = []; if ('production' === process.env.ENV) enableProdMode(); else ENV_PROVIDERS.push(ELEMENT_PROBE_PROVIDERS); /** * We bootstrap or application here. We only add our CUSTOM PROVIDERS into the bootstrap to keep this class nice and clean * If we require other providers please add those to the array of providers within ./injectables/providers/ and not here! */ document.addEventListener('DOMContentLoaded', function main() { bootstrap(AppComponent, [ENV_PROVIDERS, CUSTOM_PROVIDERS]) .catch(error => console.error(error)); });
schippie/NG2-Stream-Pipe
src/stream.ts
import {Pipe, ChangeDetectorRef, OnDestroy, PipeTransform, WrappedValue} from 'angular2/core'; import {Observable} from "rxjs/Observable"; import {Subscription} from "rxjs/Subscription"; /** * The `stream` pipe subscribes to an Observable and adds the latest value automatically to its array. Or if an array is supplied by the observable (from the next() function) * it will concat the value into the latestValue array. * This allows you to subscribe to an Observable that keeps emitting new values. Without having to put the logic of merging that result into your Component code. * * Example: Code within a service / component this.observable = new Observable(observable => { var value = 0; var timeInterval = setInterval(() => { value++; observable.next(value); }, 250); return () => clearInterval(timeInterval); }); HTML template: <div *ngFor="#value in observable | stream"> {{value}} </div> * The above small example will keep adding new integer values in divs in the view as long as the observable keeps emitting them. */ @Pipe({name: 'stream', pure: false}) export class StreamPipe implements PipeTransform, OnDestroy { private subscription: Subscription; private observable: Observable<any>; private latestValue: Array<any> = []; private changed: boolean = false; constructor(private ref: ChangeDetectorRef) {} transform(obj: Observable<any>, args?: any[]): any { if(this.subscription == null) { if(obj != null) this.subscribe(obj); else return this.latestValue; } if(obj !== this.observable) { this.ngOnDestroy(); return this.transform(obj); } if(!this.changed) { return this.latestValue; } this.changed = false; return WrappedValue.wrap(this.latestValue); } subscribe(observable: Observable<any>) { this.observable = observable; this.subscription = this.observable.subscribe((value: Object | Array<any>) => { if(Array.isArray(value)) { this.latestValue = this.latestValue.concat(value); this.changed = true; this.ref.markForCheck(); return; } this.latestValue.push(value); this.changed = true; this.ref.markForCheck(); }); } ngOnDestroy(): void { if(this.subscription != null) this.subscription.unsubscribe(); this.subscription = null; this.ref = null; this.latestValue = null; this.changed = null; } }
schippie/NG2-Stream-Pipe
test/stream.spec.ts
import {describe, it, expect, beforeEach, afterEach, inject, injectAsync} from 'angular2/testing'; import {WrappedValue, ChangeDetectorRef} from 'angular2/core'; import {EventEmitter} from 'angular2/src/facade/async'; import {StreamPipe} from '../src/stream'; import {AsyncTestCompleter} from "angular2/testing_internal"; import "rxjs/Rx"; class SpyDetercotRef extends ChangeDetectorRef { markForCheck():void {} detach():void {} detectChanges():void {} checkNoChanges():void {} reattach():void {} } describe("StreamPipe", () => { var emitter; var pipe; var ref; beforeEach(() => { emitter = new EventEmitter(); ref = new SpyDetercotRef(); pipe = new StreamPipe(ref); spyOn(ref, 'markForCheck'); }); describe("transform", () => { it("should return an empty array when subscribing to an observable", () => { expect(pipe.transform(emitter).length).toBe(0); }); it("should add a value to the array once an event is emitted", (done) => { pipe.transform(emitter); emitter.subscribe((val) => { expect(ref.markForCheck).toHaveBeenCalled(); let value = pipe.transform(emitter).wrapped; expect(value.length).toBe(1); expect(value[0]).toBe(10); done(); }); emitter.emit(10); }); it("should add a value to the array once an event is emitted longer pause", (done) => { pipe.transform(emitter); emitter.subscribe((val) => { expect(ref.markForCheck).toHaveBeenCalled(); let value = pipe.transform(emitter).wrapped; expect(value.length).toBe(1); expect(value[0]).toBe(10); done(); }); setTimeout(() => { emitter.emit(10); }, 10000); }, 15000); }); });
schippie/NG2-Stream-Pipe
test/test.main.ts
/** * Import a couple of angular specific files that are generally required by all unit-tests. Through the import 'test.main.te' * These include setting the providers in testing mode etc. And include the es6-shim, zone.js and reflect-metadata */ import 'es6-shim'; import 'zone.js'; import 'reflect-metadata'; import {setBaseTestProviders} from 'angular2/testing'; import {TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS} from 'angular2/platform/testing/browser'; setBaseTestProviders( TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS );
schippie/NG2-Stream-Pipe
example/app/components/home/home.ts
<reponame>schippie/NG2-Stream-Pipe<filename>example/app/components/home/home.ts import {Component} from 'angular2/core'; import {Title} from 'angular2/platform/browser'; import {StreamPipe} from "../../../../src/stream"; import {Observable} from "rxjs/Observable"; @Component({ selector: 'home-component', template: require('./home.html'), styles: [require('./home.scss')], providers: [Title], pipes: [StreamPipe] }) export class HomeComponent { observable: Observable<number>; constructor(public title: Title) { this.title.setTitle("Home page"); this.observable = new Observable(observable => { var value = 0; var timeInterval = setInterval(() => { value++; observable.next(value); }, 1000); return () => clearInterval(timeInterval); }); } }
Broadcom/cdd-grafana-datasource
src/types.ts
<reponame>Broadcom/cdd-grafana-datasource import { DataQuery, DataSourceJsonData, SelectableValue } from '@grafana/data'; /** * CONSTANTS */ export const optionsPeriod: Array<SelectableValue<string>> = []; const optionPeriod1: SelectableValue = { label: 'Minute', value: 'MINUTE' }; const optionPeriod2: SelectableValue = { label: 'Hour', value: 'HOUR' }; const optionPeriod3: SelectableValue = { label: 'Day', value: 'DAY' }; const optionPeriod4: SelectableValue = { label: 'Week', value: 'WEEK' }; const optionPeriod5: SelectableValue = { label: 'Month', value: 'MONTH' }; const optionPeriod6: SelectableValue = { label: 'Year', value: 'YEAR' }; optionsPeriod.push(optionPeriod1); optionsPeriod.push(optionPeriod2); optionsPeriod.push(optionPeriod3); optionsPeriod.push(optionPeriod4); optionsPeriod.push(optionPeriod5); optionsPeriod.push(optionPeriod6); let initialMetric = [] as any; export function setInitialMetric(metric: string) { initialMetric = metric; } export function getInitialMetric() { return initialMetric; } /* current fields are saved here to be available both in QueryEditor.ts and datasource.ts. They are needed since the "query" object in QueryEditor.ts is not cleaned, and when changing the field Data Source in the Query Editor page, fields from the prev data source are still kept in "query" */ let currentFields = new Map<string, CddField>(); export function clearCurrentFields() { currentFields.clear(); } export function setCurrentField(fieldId: string, cddField: CddField) { currentFields.set(fieldId, cddField); } export function getCurrentFields() { return currentFields; } /** * FOR QUERY EDITOR */ export interface BasicCddDataQuery extends DataQuery { start_date?: string; end_date?: string; page_size?: string; page_number?: string; } export interface FieldsQuery extends BasicCddDataQuery { metric_name?: string; filter?: string; } export interface Metric { name?: string; monitoringMetricDescription?: string; monitoringMetricCategory?: string; className?: string; } export interface CddField { id: string; tagName: string; tagDisplayName: string; className?: string; } export interface FieldsList { aaa: string; bbb: string; } export interface CddQuery extends DataQuery { queryMetric: string; period: string; } /** * FOR CONFIG EDITOR */ /** * These are options configured for each DataSource instance */ export interface CddDataSourceOptions extends DataSourceJsonData { serverURL?: string; tenantId?: string; } /** * Value that is used in the backend, but never sent over HTTP to the frontend */ export interface MySecureJsonData { apiKey?: string; }
Broadcom/cdd-grafana-datasource
src/datasource.ts
import { getBackendSrv, getTemplateSrv } from '@grafana/runtime'; import { DataQueryRequest, DataQueryResponse, DataSourceApi, DataSourceInstanceSettings, MutableDataFrame, FieldType, DateTime, } from '@grafana/data'; import { optionsPeriod, CddQuery, CddDataSourceOptions, getInitialMetric, getCurrentFields } from './types'; export class DataSource extends DataSourceApi<CddQuery, CddDataSourceOptions> { url: string; annotations = {}; errorMessage = 'Check the connectivity to the CDD server and make sure that the CDD server configuration in Grafana is correct (URL, Tenant ID, and API Key).'; constructor(instanceSettings: DataSourceInstanceSettings<CddDataSourceOptions>) { super(instanceSettings); this.url = instanceSettings.url + '/reportingRoute'; // reportingRoute is the path in plugin.json } async doRequest(options: DataQueryRequest<CddQuery>, params) { let initialMetric; // for initial load of plugin after changing from another plugin if (!params.queryMetric) { await new Promise((r) => setTimeout(r, 5000)); // sleep initialMetric = getInitialMetric(); // for initial load of plugin after changing from another plugin if (initialMetric?.length !== 0) { initialMetric = initialMetric.value; } else { console.log('Select a Query Type.'); throw new Error('Select a Query Type.'); } } const fields = [] as any; const currentFields = getCurrentFields(); currentFields.forEach((value, key) => { if (params[key] !== undefined && params[key] !== '') { const field = {}; const fieldName = { tagName: key }; field['monitoringMetricTag'] = fieldName; const fieldValue = getTemplateSrv().replace(params[key], options.scopedVars); // replace Grafana variable with the selected value in the UI by user (if not variable it returns the same value) field['tagValueName'] = fieldValue; fields.push(field); } }); const body = { monitoringMetricName: params.queryMetric || initialMetric, monitoringMetricTags: fields, }; const from: DateTime = options.range.from; const to: DateTime = options.range.to; const queryParams = { start_date: from.toDate().getTime(), end_date: to.toDate().getTime(), period: params.period || optionsPeriod[0].value, page_size: 30, }; try { const result = await getBackendSrv().datasourceRequest({ method: 'POST', url: this.url + '/monitoring/metrics', params: queryParams, data: body, responseType: 'json', }); return result; } catch (error) { console.error(this.errorMessage, error); throw new Error(this.errorMessage); } } async query(options: DataQueryRequest<CddQuery>): Promise<DataQueryResponse> { const promises = options.targets.map((params) => this.doRequest(options, params).then((response) => { const frame = new MutableDataFrame({ refId: params.refId, fields: [ { name: 'Time', type: FieldType.time }, { name: 'Average', type: FieldType.number }, { name: 'Total', type: FieldType.number }, { name: 'Minimum', type: FieldType.number }, { name: 'Maximum', type: FieldType.number }, { name: 'Last Value', type: FieldType.number }, ], }); if (response.data?.data?.length > 0) { const data = response.data.data[0].monitoringMetricValues; data.map((point: any) => frame.appendRow([ point['monitoringDate'], point['averageMetricValue'], point['totalMetricValue'], point['minimumMetricValue'], point['maximumMetricValue'], point['lastMetricValue'], ]) ); } return frame; }) ); return Promise.all(promises).then((data) => ({ data })); } async doRequestTest() { try { const result = await getBackendSrv().datasourceRequest({ method: 'GET', url: this.url + '/monitoring/metrics', }); return result; } catch (error) { const errorMessage = 'Connection test failed. ' + this.errorMessage; console.error(errorMessage, error); throw new Error(this.errorMessage); } } async testDatasource() { return this.doRequestTest().then((response) => { if (response?.status !== 200) { throw new Error(this.errorMessage); } return { status: 'success', message: 'Success', }; }); } }
Broadcom/cdd-grafana-datasource
src/QueryEditor.tsx
<filename>src/QueryEditor.tsx import React, { ChangeEvent, PureComponent } from 'react'; import { getBackendSrv } from '@grafana/runtime'; import { QueryEditorProps, SelectableValue } from '@grafana/data'; import { DataSource } from './datasource'; import { CddDataSourceOptions, CddQuery, optionsPeriod, Metric, CddField, setInitialMetric, clearCurrentFields, getCurrentFields, setCurrentField, } from './types'; import { FieldCddInput } from './FieldCddInput'; import { FieldCddSelect } from './FieldCddSelect'; type Props = QueryEditorProps<DataSource, CddQuery, CddDataSourceOptions>; type CddState = { metricOptions: SelectableValue[]; }; export class QueryEditor extends PureComponent<Props, CddState> { url: string; currentMetric: string | undefined; historicFieldsList; errorMessage = 'Check the connectivity to the CDD server and make sure that the CDD server configuration in Grafana is correct (URL, Tenant ID, and API Key).'; constructor(public props: Props) { super(props); this.url = props.datasource.url; this.historicFieldsList = new Set<string>(); this.state = { metricOptions: [] as any, }; } componentDidMount() { this.updateMetricsField(); } async updateMetricsField() { this.doRequestMetrics().then(async (response) => { if (response.data) { const optionsMetric = [] as any; response.data.map((metric: Metric) => { const optionMetric: SelectableValue = { label: metric.monitoringMetricDescription, value: metric.name }; optionsMetric.push(optionMetric); }); this.setState(() => { return { metricOptions: optionsMetric }; }); setInitialMetric(optionsMetric[0]); await this.updateFieldsList(); } else { throw new Error('No metric response from CDD server'); } }); } async updateFieldsList() { if (!this.currentMetric) { return; } this.doRequestFields().then((response) => { clearCurrentFields(); response.data.data.map((field: CddField) => { setCurrentField(field.tagName, field); }); const { onRunQuery } = this.props; onRunQuery(); }); } async doRequestMetrics() { try { const result = await getBackendSrv().datasourceRequest({ method: 'GET', url: this.url + '/monitoring/metrics', params: { page_size: 30 }, }); return result; } catch (error) { console.error(this.errorMessage, error); throw new Error(this.errorMessage); } } async doRequestFields() { try { const result = await getBackendSrv().datasourceRequest({ method: 'GET', url: this.url + '/monitoring/metrics/tags', params: { metric_name: this.currentMetric, page_size: 30 }, }); return result; } catch (error) { console.error(this.errorMessage, error); throw new Error(this.errorMessage); } } onQueryMetricChange = (value: SelectableValue<string>) => { this.currentMetric = value.value; const { onChange, query, onRunQuery } = this.props; const selectedMetric = this.getOptionQueryMetric(value.value); onChange({ ...query, queryMetric: selectedMetric.value }); this.updateFieldsList(); onRunQuery(); }; onPeriodChange = (value: SelectableValue<string>) => { const { onChange, query, onRunQuery } = this.props; const selectedPeriod = this.getOptionPeriod(value.value); onChange({ ...query, period: selectedPeriod.value }); onRunQuery(); }; onGenericFieldChange = (fieldName: string, event: ChangeEvent<HTMLInputElement>) => { const { onChange, query, onRunQuery } = this.props; const savedQueryValues = { ...query }; savedQueryValues[fieldName] = event.target.value; onChange(savedQueryValues); onRunQuery(); }; getOptionQueryMetric = (value: string | undefined): SelectableValue => { const defaultOptionMetric = this.state.metricOptions.length > 0 ? this.state.metricOptions[0] : { label: 'Loading...', value: 'typesLoading' }; const foundOptionType = this.state.metricOptions.find((option) => option.value === value) || defaultOptionMetric; return foundOptionType; }; getOptionPeriod = (value: string | undefined): SelectableValue => { const foundOptionPeriod = optionsPeriod.find((option) => option.value === value) || optionsPeriod[0]; return foundOptionPeriod; }; getFieldValue(tagId: string) { return this.props.query[tagId] || ''; } render() { const { period, queryMetric } = this.props.query; const queryPeriodValue = this.getOptionPeriod(period); const queryMetricValue = this.getOptionQueryMetric(queryMetric); this.currentMetric = queryMetricValue.value; const fieldsToRender = [] as any; let fields = getCurrentFields(); fields.forEach((field: CddField, fieldName: string) => { fieldsToRender.push( <FieldCddInput labelWidth={20} value={this.getFieldValue(fieldName)} onChange={(e) => this.onGenericFieldChange(fieldName, e)} label={field.tagDisplayName} /*tooltip={field.tagDisplayName}*/ /> ); }); return ( <div className="gf-form-group"> <FieldCddSelect options={this.state.metricOptions} value={queryMetricValue} onChange={this.onQueryMetricChange} label="Query Type" tooltip_label="Select the tests metric to retrieve" /> <FieldCddSelect options={optionsPeriod} value={queryPeriodValue} onChange={this.onPeriodChange} label="Interval" tooltip_label="The data will be returned grouped by the time interval" /> <div>{fieldsToRender}</div> </div> ); } }
Broadcom/cdd-grafana-datasource
src/ConfigEditor.tsx
import React, { ChangeEvent, PureComponent } from 'react'; import { LegacyForms } from '@grafana/ui'; import { DataSourcePluginOptionsEditorProps } from '@grafana/data'; import { CddDataSourceOptions, MySecureJsonData } from './types'; const { SecretFormField, FormField } = LegacyForms; interface Props extends DataSourcePluginOptionsEditorProps<CddDataSourceOptions> {} interface State {} export class ConfigEditor extends PureComponent<Props, State> { onServerURLChange = (event: ChangeEvent<HTMLInputElement>) => { const { onOptionsChange, options } = this.props; const jsonData = { ...options.jsonData, serverURL: event.target.value, }; onOptionsChange({ ...options, jsonData }); }; onTenantIdChange = (event: ChangeEvent<HTMLInputElement>) => { const { onOptionsChange, options } = this.props; const jsonData = { ...options.jsonData, tenantId: event.target.value, }; onOptionsChange({ ...options, jsonData }); }; // Secure field (only sent to the backend) onAPIKeyChange = (event: ChangeEvent<HTMLInputElement>) => { const { onOptionsChange, options } = this.props; onOptionsChange({ ...options, secureJsonData: { apiKey: event.target.value, }, }); }; onResetAPIKey = () => { const { onOptionsChange, options } = this.props; onOptionsChange({ ...options, secureJsonFields: { ...options.secureJsonFields, apiKey: false, }, secureJsonData: { ...options.secureJsonData, apiKey: '', }, }); }; render() { const { options } = this.props; const { jsonData, secureJsonFields } = options; const secureJsonData = (options.secureJsonData || {}) as MySecureJsonData; return ( <div className="gf-form-group"> <div className="gf-form"> <FormField label="CDD Server URL" tooltip="Specify the server URL, for example, https://myserver.acme.com:8080. For SaaS use the URL https://cddirector.io/cdd" labelWidth={10} inputWidth={25} onChange={this.onServerURLChange} value={jsonData.serverURL || ''} placeholder="https://myserver.acme.com:8080" /> </div> <div className="gf-form"> <FormField label="Tenant ID" tooltip="For an on-prem install of Continuous Delivery Director, the tenant ID is 00000000-0000-0000-0000-000000000000. For Continuous Delivery Director SaaS, you can find the tenant ID under User Settings." labelWidth={10} inputWidth={25} onChange={this.onTenantIdChange} value={jsonData.tenantId || ''} placeholder="00000000-0000-0000-0000-000000000000" /> </div> <div className="gf-form-inline"> <div className="gf-form"> <SecretFormField isConfigured={(secureJsonFields && secureJsonFields.apiKey) as boolean} value={secureJsonData.apiKey || ''} label="API Key" tooltip="Specify the CDD user API key" placeholder="API Key" labelWidth={10} inputWidth={20} onReset={this.onResetAPIKey} onChange={this.onAPIKeyChange} /> </div> </div> </div> ); } }
849203846/alibabacloud-console-widget
packages/widget-loader/index.d.ts
<gh_stars>1-10 /// <reference types="react" /> import { ComponentType, SuspenseProps } from 'react'; // FIXME 非 OneConsole 的场景,这里每一个都要设置... export interface IWidgetUtilsConsole { getLang?: () => string; getLocale?: () => string; getChannel?: () => string; getCurrentUid?: () => string; getParentUid?: () => string; getAccountType?: () => string; getRegionName?: (regionId: string) => string; getZoneName?: (zoneId: string) => string; useCORS?: () => boolean; } export interface IDependencies { // OneConsole 下有统一的设值,但非 OneConsole(比如 console-base)下就必须全部设置... // 否则会抛错 抛错位置在 `packages/widget-loader/src/utils/wind/checkConsoleUtils.js` '@alicloud/widget-utils-console'?: IWidgetUtilsConsole; [k: string]: any; } export interface ICreateOptions { initiator?: string; dependencies?: IDependencies; lazy?: boolean; windRuntime?: { preload?: boolean; runtimeVersion?: string; messageVersion?: string; }; // consoleConfig?: IWidgetUtilsConsole; // deprecated 不 export suspense?: SuspenseProps; } export interface IWidgetOptions { id: string; version: string; } export interface ILoadOptions { lazy: boolean; suspense: SuspenseProps; } export interface IFnLoader { <T = {}>(widgetOptions: IWidgetOptions, loadOptions?: ILoadOptions): ComponentType<T>; } export default function (opts?: ICreateOptions): IFnLoader;
849203846/alibabacloud-console-widget
packages/widget-utils-rc/index.d.ts
<gh_stars>1-10 /// <reference types="react" /> import { Component, ComponentType, ReactNode } from 'react'; interface IChannelLinkProps { id: string; values?: { [k: string]: string; }; children: ReactNode; target?: string; className?: string; shape?: string; type?: string; size?: string; disabled?: boolean; url?: string; extra?: string; } export class ChannelLink extends Component<IChannelLinkProps> {} interface IChannelFeatureProps { id: string; children: ReactNode; activeRegionId?: string; determinator?: (feature: { status: boolean; regions?: string[]; }) => boolean; fallback?: ReactNode; } export class ChannelFeature extends Component<IChannelFeatureProps> {} // export function configWindStylePrefix(C: ComponentType): ComponentType; // deprecate 掉了,就不 export 了这里 export function configWind(C: ComponentType): ComponentType; export function withContainer(C: ComponentType): ComponentType; interface ICreateRootParam { id: string; stateHandlers: { initialState: object | ((props: object) => any); stateUpdaters: { [k: string]: (state?: object, props?: object) => (...payload: any[]) => object; }; }; } // TODO 这里的泛型 P 是一个无奈之举 // 按道理应该通过 Exclude、Omit 等来自动收取 HOC 里包裹的 Props,但那个有些麻烦(手写的话..) // 所以只好先让组件把自己的 Props 接口 export 出来在 createRoot 的时候收取.. // P -> 在 Widget 中定义的 props export function createRoot<P = {}>(param: ICreateRootParam): (Widget: ComponentType<P>) => ComponentType<P>;
849203846/alibabacloud-console-widget
packages/widget-hooks/index.d.ts
<filename>packages/widget-hooks/index.d.ts /// <reference types="react" /> import { ReactElement } from 'react'; interface IConsoleConfig { features: { [k: string]: { status: boolean; attribute?: { regions?: string[]; }; }; }; links: { [k: string]: string; }; } export declare function useConsoleConfig(): IConsoleConfig; // 基本上不要用 export declare function useConsoleConfig<T = void>(key: string): T; declare function intl <T = string>(key: string, values?: { [k: string]: string; }): T; declare namespace intl { function set(basic?: { messages?: { [k: string]: string; }; }, extra?: { determineLocale?: { cookie: string; }; }): void; function setLocale(locale: string): void; function setMessages(messages: { [k: string]: string; }): void; function getLocale(): string; function getMessages(): { [k: string]: string; }; function message<T = string>(key: string, values?: { [k: string]: string; }): T; function number(value: number, options?: Intl.NumberFormatOptions): string; function date(date: Date | number | string, options?: 'date' | 'time' | 'dateTime' | 'dateTimeWithTimeZone' | Intl.DateTimeFormatOptions): string; function html(key: string, values?: { [k: string]: string; }): ReactElement; } export declare function useIntl(): typeof intl; export declare function useChannelLink(id: string, values?: { [k: string]: string; }): string; export declare function useFeature( id: string, activeRegionId?: string, determinator?: (feature: { status: boolean; regions?: string[] }) => boolean ) export declare function useGlobalState<T>(): T; export declare function useGlobalState<T = string>(stateName: string): [T, (state: T) => void]; export declare function useRefresher(id: string): number;
thomas-lab/Leaflet.MapboxVectorTile
exported_typings/leaflet-mvt.d.ts
<filename>exported_typings/leaflet-mvt.d.ts<gh_stars>0 declare module LeafletMVT { // Tag interface export interface Style {} interface PointBaseStyle { color: string; radius: number; } export interface PointStyle extends PointBaseStyle, Style { selected?: PointBaseStyle } interface LineBaseStyle { color: string; size: number; } export interface LineStyle extends LineBaseStyle, Style { selected?: LineBaseStyle } interface PolygonBaseStyle { color: string; outline?: LineBaseStyle; } export interface PolygonStyle extends PolygonBaseStyle, Style { selected?: PolygonBaseStyle } export interface VectorTileFeature { type: number; // 1 for Point, 2 for LineString, 3 for Polygon properties: {[k: string]: any}; } export interface StyleFunction { (feature: VectorTileFeature): Style } export interface Feature extends VectorTileFeature { id: string; select(): void; deselect(): void; toggle(): void; redraw(): void; style: Style; } export interface Layer { features: {[id: string]: Feature}; } export interface Options { url: string; debug?: boolean; clickableLayers?: string[]; mutexToggle?: boolean; getIDForLayerFeature: (feature: LeafletMVT.VectorTileFeature) => string; filter: (feature: LeafletMVT.VectorTileFeature) => boolean; style?: LeafletMVT.StyleFunction | {[name: string]: LeafletMVT.StyleFunction}; visibleLayers?: string[] | {[name: string]: string}; onClick?: (e: L.LeafletMouseEvent) => any; buffer?: number; } } declare module L { module TileLayer { export interface MVTSource extends L.TileLayer { layers: {[name: string]: LeafletMVT.Layer}; setStyle(styleFn: LeafletMVT.StyleFunction, name?: string): void; featureAtLatLng(latlng: LatLng): LeafletMVT.Feature; featureAtContainerPoint(containerPoint: Point): LeafletMVT.Feature; } } interface TileLayerStatic { MVTSource: { /** * Instantiates a MapboxVectorTile layer object given a base URL of the tile server. */ new(options: LeafletMVT.Options): TileLayer.MVTSource; }; } }
foxhatleo/dragonglass-level-editor
components/AuthManager.tsx
<gh_stars>0 import React, {useEffect, useState} from "react"; import {Button, Modal} from "react-bootstrap"; import * as Dispatcher from "../redux/action/Dispatcher"; import {connect, ConnectedProps} from "react-redux"; import {bindActionCreators} from "redux"; import State from "../redux/store/State"; import * as Config from "../config/Google"; import {isDebug} from "../config/Debug"; enum AuthManagerStage { ERROR, LOAD_AUTH, INIT_CLIENT, AUTH_READY, } const connector = connect( (s: State) => ({loggedIn: s.loggedIn}), (d) => bindActionCreators(Dispatcher, d), ); const AuthManager: React.FunctionComponent<ConnectedProps<typeof connector>> = (p) => { const [stage, setStage] = useState<AuthManagerStage>(AuthManagerStage.LOAD_AUTH); const fail = (c: string, e: any) => { setStage(AuthManagerStage.ERROR); p.fail(["auth:" + c, e]); } useEffect(() => { if (isDebug()) return; try { switch (stage) { case AuthManagerStage.LOAD_AUTH: { gapi.load("client:auth2", { onerror: (e: any) => fail("loadAuth", e), callback: () => setStage(AuthManagerStage.INIT_CLIENT), }); break; } case AuthManagerStage.INIT_CLIENT: { gapi.client.init({ apiKey: Config.API_KEY, clientId: Config.CLIENT_ID, discoveryDocs: Config.DISCOVERY_DOCS, scope: Config.SCOPES.join(" "), }).then(() => { gapi.auth2.getAuthInstance().isSignedIn.listen(p.updateSignInStatus); p.updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); setStage(AuthManagerStage.AUTH_READY); }, (e: any) => fail("initClient", e)); break; } } } catch (e) { fail("uncaught", e); } }, [stage]); const logIn = () => { gapi.auth2.getAuthInstance().signIn() .then(() => {p.updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get())}); }; const header = () => { if (stage === AuthManagerStage.AUTH_READY) return "Sign In with your Cornell Google account"; return "Initializing"; } const content = () => { switch (stage) { case AuthManagerStage.ERROR: return (<>Cannot connect to Google auth server.<br/>Refresh this page.</>); case AuthManagerStage.INIT_CLIENT: return (<>Initializing Google client...</>); case AuthManagerStage.LOAD_AUTH: return (<>Loading Google auth module...</>); case AuthManagerStage.AUTH_READY: if (p.loggedIn) return <>Logged in. Please wait...</>; return ( <> Level files are stored in the Google Drive of your Cornell account.<br/> To continue, authorize access to your Google account. <p> <strong>Privacy policy</strong><br/> This level editor only requests access to the files that you have opened or created with this app (in other words, the level files). It will <em>NOT</em> have access to any other file in your Google Drive or any other part of your account (including but not limited to Gmail, Contacts, Calendar, etc). </p> <p> <strong>Privacy policy</strong><br/> The privacy policy of this app is available <a href={"https://github.com/foxhatleo/panic-painter-level-editor/blob/master/PRIVACY.md"}>here</a>. </p> <p> <strong>If you are stuck on this screen</strong><br/> Try to clear cookies and cache of your browser. If problem persists, try disabling browser extensions or settings that limit third-party cookies. </p> </> ); } }; return ( <Modal backdrop="static" show={!isDebug() && (stage !== AuthManagerStage.AUTH_READY || !p.loggedIn)} onHide={() => {}}> <Modal.Header><Modal.Title>{header()}</Modal.Title></Modal.Header> <Modal.Body>{content()}</Modal.Body> {stage == AuthManagerStage.AUTH_READY ? <Modal.Footer> <Button onClick={logIn} variant="primary" disabled={stage != AuthManagerStage.AUTH_READY}> Authorize </Button> </Modal.Footer> : ""} </Modal> ); }; export default connector(AuthManager);
foxhatleo/dragonglass-level-editor
components/FileManager.tsx
import React, {ChangeEvent, SyntheticEvent, useEffect, useState} from "react"; import {connect, ConnectedProps} from "react-redux"; import State from "../redux/store/State"; import {bindActionCreators} from "redux"; import * as Dispatcher from "../redux/action/Dispatcher"; import {Button, FormControl, Modal} from "react-bootstrap"; import {isDebug} from "../config/Debug"; const EXT = ".ppl"; const EXT_LEN = EXT.length; const nwConnector = connect( (s: State) => ({loggedIn: s.loggedIn}), (d) => bindActionCreators(Dispatcher, d), ); type NewWindowProps = { folderId: string; show: boolean; } const _NewWindow: React.FunctionComponent<ConnectedProps<typeof nwConnector> & NewWindowProps> = (p) => { const [filename, _setFilename] = useState<string>(EXT); const [creating, setCreating] = useState<boolean>(false); const setFilename = (e: ChangeEvent<HTMLInputElement>) => { let fn = e.currentTarget.value.trim(); fn = fn.replaceAll(/[#%<>&*{}?\/\\$+!`|=:@]/g, ""); if (!fn.endsWith(EXT)) fn += EXT; _setFilename(fn); } const selectDetect = (e: SyntheticEvent<HTMLInputElement>) => { e.currentTarget.selectionEnd = Math.min(e.currentTarget.selectionEnd || 0, filename.length - EXT_LEN); e.currentTarget.selectionStart = Math.min(e.currentTarget.selectionEnd || 0, e.currentTarget.selectionStart || 0); }; const create = () => { if (filename.length <= EXT_LEN || creating) return; setCreating(true); gapi.client.drive.files.create({ resource: { "name": filename, "mimeType": 'application/panic-painter-level', "parents": [p.folderId] }, }).then((result) => { const fid = JSON.parse(result.body)["id"]; window.location.replace(`/${fid}/edit`); }).catch((e) => p.fail(["create", e])); }; const createKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === "Enter" || e.keyCode === 13) { create(); } }; return ( <Modal backdrop="static" show={p.loggedIn && p.show} onHide={() => { }}> <Modal.Header><Modal.Title>Enter file name</Modal.Title></Modal.Header> <Modal.Body> Enter a name for your new level file. <p> <FormControl onSelect={selectDetect} disabled={creating} autoCapitalize="no" onChange={setFilename} onKeyUp={createKeyUp} value={filename}/> </p> </Modal.Body> <Modal.Footer> <Button variant="primary" disabled={filename.length <= EXT_LEN || creating} onClick={create}> Continue </Button> </Modal.Footer> </Modal> ) }; const NewWindow = nwConnector(_NewWindow); const gFilesReady = () => (typeof gapi !== "undefined" && gapi.client && gapi.client.drive && gapi.client.drive.files); export function reload(c: string, p: {fileId: string} & typeof Dispatcher, onDone: () => void, onFail?: (e: any) => void) { if (!gFilesReady()) { onDone(); return; } Promise.all([ gapi.client.drive.files.get({fileId: p.fileId, alt: "media"}), gapi.client.drive.files.get({fileId: p.fileId}), ]).then(([media, metadata]) => { onDone(); p.setName(JSON.parse(metadata.body)["name"]); p.parseData(media.body || ""); p.markReady(); }).catch((e) => typeof onFail === "function" ? onFail(e) : p.fail([c, e])); } const fmConnector = connect( (s: State) => ({fileId: s.fileId, loggedIn: s.loggedIn}), (d) => bindActionCreators(Dispatcher, d), ); const FileManager: React.FunctionComponent<ConnectedProps<typeof fmConnector> & { createMode: boolean; }> = (p) => { if (isDebug()) { p.setName("Debug Mode") p.markReady(); return <></>; } const [loading, setLoading] = useState<boolean>(false); const [driveApiReady, setDriveApiReady] = useState<boolean>(false); const showFolder = p.createMode && driveApiReady; // Monitor for Google Drive API for when it is ready. useEffect(() => { const i = setInterval(() => { if (gFilesReady()) { setDriveApiReady(true); clearInterval(i); } }, 50); }, []); // When everything is ready, load file. useEffect(() => { if (p.fileId && p.loggedIn && driveApiReady && !p.createMode) { setLoading(true); reload("open", p, () => setLoading(false)); } }, [p.fileId, driveApiReady, p.loggedIn]); return ( <> <NewWindow folderId={p.fileId} show={showFolder}/> <Modal backdrop="static" show={loading} onHide={() => { }}> <Modal.Header><Modal.Title>Loading file...</Modal.Title></Modal.Header> <Modal.Body> Loading level file... This make take a few seconds. </Modal.Body> </Modal> </> ); }; export default fmConnector(FileManager);
foxhatleo/dragonglass-level-editor
config/Debug.ts
export function isDebug(): boolean { return (typeof location !== "undefined" && ( location.hostname === "localhost" || location.hostname === "127.0.0.1")); }