conflict_resolution
stringlengths
27
16k
<<<<<<< projectionsMap: new Map<ITargetedInstruction, IProjections>(), watches: [], ======= projectionsMap: new Map<IInstruction, IProjections>(), >>>>>>> projectionsMap: new Map<IInstruction, IProjections>(), watches: [], <<<<<<< projectionsMap: new Map<ITargetedInstruction, IProjections>(), watches: [], ======= projectionsMap: new Map<IInstruction, IProjections>(), >>>>>>> projectionsMap: new Map<IInstruction, IProjections>(), watches: [], <<<<<<< projectionsMap: new Map<ITargetedInstruction, IProjections>(), watches: [], ======= projectionsMap: new Map<IInstruction, IProjections>(), >>>>>>> projectionsMap: new Map<IInstruction, IProjections>(), watches: [], <<<<<<< ] as ((ctx: HTMLTestContext, $1: CTCResult, $2: CTCResult, $3: CTCResult, $4: CTCResult) => CTCResult)[] ], (ctx, $1, $2, $3, $4, [input, output]) => { ======= ] as ((ctx: TestContext, $1: CTCResult, $2: CTCResult, $3: CTCResult, $4: CTCResult) => CTCResult)[] ], (ctx, $1, $2, $3, $4, [input, output]) => { >>>>>>> ] as ((ctx: TestContext, $1: CTCResult, $2: CTCResult, $3: CTCResult, $4: CTCResult) => CTCResult)[] ], (ctx, $1, $2, $3, $4, [input, output]) => { <<<<<<< projectionsMap: new Map<ITargetedInstruction, IProjections>(), watches: [], ======= projectionsMap: new Map<IInstruction, IProjections>(), >>>>>>> projectionsMap: new Map<IInstruction, IProjections>(), watches: [],
<<<<<<< import { LoggerService } from '../logging/logger.service'; import { OidcSecurityCommon } from './oidc.security.common'; ======= import { StoragePersistanceService } from '../storage'; import { LoggerService } from './oidc.logger.service'; >>>>>>> import { StoragePersistanceService } from '../storage'; import { LoggerService } from '../logging/logger.service';
<<<<<<< import { Injectable } from '@angular/core'; import { forkJoin, Observable, of, throwError, TimeoutError, timer } from 'rxjs'; import { map, mergeMap, retryWhen, switchMap, take, timeout } from 'rxjs/operators'; import { AuthStateService } from '../authState/auth-state.service'; import { AuthWellKnownService } from '../config/auth-well-known.service'; import { ConfigurationProvider } from '../config/config.provider'; import { FlowsDataService } from '../flows/flows-data.service'; import { RefreshSessionIframeService } from '../iframe/refresh-session-iframe.service'; import { SilentRenewService } from '../iframe/silent-renew.service'; import { LoggerService } from '../logging/logger.service'; import { FlowHelper } from '../utils/flowHelper/flow-helper.service'; import { RefreshSessionRefreshTokenService } from './refresh-session-refresh-token.service'; export const MAX_RETRY_ATTEMPTS = 3; @Injectable({ providedIn: 'root' }) export class RefreshSessionService { constructor( private flowHelper: FlowHelper, private configurationProvider: ConfigurationProvider, private flowsDataService: FlowsDataService, private loggerService: LoggerService, private silentRenewService: SilentRenewService, private authStateService: AuthStateService, private authWellKnownService: AuthWellKnownService, private refreshSessionIframeService: RefreshSessionIframeService, private refreshSessionRefreshTokenService: RefreshSessionRefreshTokenService ) {} forceRefreshSession(customParams?: { [key: string]: string | number | boolean }) { if (this.flowHelper.isCurrentFlowCodeFlowWithRefreshTokens()) { return this.startRefreshSession(customParams).pipe( map(() => { const isAuthenticated = this.authStateService.areAuthStorageTokensValid(); if (isAuthenticated) { return { idToken: this.authStateService.getIdToken(), accessToken: this.authStateService.getAccessToken(), }; } return null; }) ); } return forkJoin([this.startRefreshSession(), this.silentRenewService.refreshSessionWithIFrameCompleted$.pipe(take(1))]).pipe( timeout(this.configurationProvider.openIDConfiguration.silentRenewTimeoutInSeconds * 1000), retryWhen(this.timeoutRetryStrategy.bind(this)), map(([_, callbackContext]) => { const isAuthenticated = this.authStateService.areAuthStorageTokensValid(); if (isAuthenticated) { return { idToken: callbackContext?.authResult?.id_token, accessToken: callbackContext?.authResult?.access_token, }; } return null; }) ); } private startRefreshSession(customParams?: { [key: string]: string | number | boolean }) { const isSilentRenewRunning = this.flowsDataService.isSilentRenewRunning(); this.loggerService.logDebug(`Checking: silentRenewRunning: ${isSilentRenewRunning}`); const shouldBeExecuted = !isSilentRenewRunning; if (!shouldBeExecuted) { return of(null); } const authWellknownEndpointAdress = this.configurationProvider.openIDConfiguration?.authWellknownEndpoint; if (!authWellknownEndpointAdress) { this.loggerService.logError('no authwellknownendpoint given!'); return of(null); } return this.authWellKnownService.getAuthWellKnownEndPoints(authWellknownEndpointAdress).pipe( switchMap(() => { this.flowsDataService.setSilentRenewRunning(); if (this.flowHelper.isCurrentFlowCodeFlowWithRefreshTokens()) { // Refresh Session using Refresh tokens return this.refreshSessionRefreshTokenService.refreshSessionWithRefreshTokens(customParams); } return this.refreshSessionIframeService.refreshSessionWithIframe(customParams); }) ); } private timeoutRetryStrategy(errorAttempts: Observable<any>) { return errorAttempts.pipe( mergeMap((error, index) => { const scalingDuration = 1000; const currentAttempt = index + 1; if (!(error instanceof TimeoutError) || currentAttempt > MAX_RETRY_ATTEMPTS) { return throwError(error); } this.loggerService.logDebug(`forceRefreshSession timeout. Attempt #${currentAttempt}`); this.flowsDataService.resetSilentRenewRunning(); return timer(currentAttempt * scalingDuration); }) ); } } ======= import { Injectable } from '@angular/core'; import { forkJoin, Observable, of, throwError, TimeoutError, timer } from 'rxjs'; import { map, mergeMap, retryWhen, switchMap, take, timeout } from 'rxjs/operators'; import { AuthStateService } from '../authState/auth-state.service'; import { AuthWellKnownService } from '../config/auth-well-known.service'; import { ConfigurationProvider } from '../config/config.provider'; import { FlowsDataService } from '../flows/flows-data.service'; import { RefreshSessionIframeService } from '../iframe/refresh-session-iframe.service'; import { SilentRenewService } from '../iframe/silent-renew.service'; import { LoggerService } from '../logging/logger.service'; import { FlowHelper } from '../utils/flowHelper/flow-helper.service'; import { RefreshSessionRefreshTokenService } from './refresh-session-refresh-token.service'; @Injectable({ providedIn: 'root' }) export class RefreshSessionService { private MAX_RETRY_ATTEMPTS = 3; constructor( private flowHelper: FlowHelper, private configurationProvider: ConfigurationProvider, private flowsDataService: FlowsDataService, private loggerService: LoggerService, private silentRenewService: SilentRenewService, private authStateService: AuthStateService, private authWellKnownService: AuthWellKnownService, private refreshSessionIframeService: RefreshSessionIframeService, private refreshSessionRefreshTokenService: RefreshSessionRefreshTokenService ) {} forceRefreshSession(customParams?: { [key: string]: string | number | boolean }) { if (this.flowHelper.isCurrentFlowCodeFlowWithRefreshTokens()) { return this.startRefreshSession(customParams).pipe( map(() => { const isAuthenticated = this.authStateService.areAuthStorageTokensValid(); if (isAuthenticated) { return { idToken: this.authStateService.getIdToken(), accessToken: this.authStateService.getAccessToken(), }; } return null; }) ); } return forkJoin([ this.startRefreshSession(customParams), this.silentRenewService.refreshSessionWithIFrameCompleted$.pipe(take(1)), ]).pipe( timeout(this.configurationProvider.openIDConfiguration.silentRenewTimeoutInSeconds * 1000), retryWhen(this.TimeoutRetryStrategy.bind(this)), map(([_, callbackContext]) => { const isAuthenticated = this.authStateService.areAuthStorageTokensValid(); if (isAuthenticated) { return { idToken: callbackContext?.authResult?.id_token, accessToken: callbackContext?.authResult?.access_token, }; } return null; }) ); } private startRefreshSession(customParams?: { [key: string]: string | number | boolean }) { const isSilentRenewRunning = this.flowsDataService.isSilentRenewRunning(); this.loggerService.logDebug(`Checking: silentRenewRunning: ${isSilentRenewRunning}`); const shouldBeExecuted = !isSilentRenewRunning; if (!shouldBeExecuted) { return of(null); } const authWellknownEndpointAdress = this.configurationProvider.openIDConfiguration?.authWellknownEndpoint; if (!authWellknownEndpointAdress) { this.loggerService.logError('no authwellknownendpoint given!'); return of(null); } return this.authWellKnownService.getAuthWellKnownEndPoints(authWellknownEndpointAdress).pipe( switchMap(() => { this.flowsDataService.setSilentRenewRunning(); if (this.flowHelper.isCurrentFlowCodeFlowWithRefreshTokens()) { // Refresh Session using Refresh tokens return this.refreshSessionRefreshTokenService.refreshSessionWithRefreshTokens(customParams); } return this.refreshSessionIframeService.refreshSessionWithIframe(customParams); }) ); } private TimeoutRetryStrategy(errorAttempts: Observable<any>) { return errorAttempts.pipe( mergeMap((error, index) => { const scalingDuration = 1000; const currentAttempt = index + 1; if (!(error instanceof TimeoutError) || currentAttempt > this.MAX_RETRY_ATTEMPTS) { return throwError(error); } this.loggerService.logDebug(`forceRefreshSession timeout. Attempt #${currentAttempt}`); this.flowsDataService.resetSilentRenewRunning(); return timer(currentAttempt * scalingDuration); }) ); } } >>>>>>> import { Injectable } from '@angular/core'; import { forkJoin, Observable, of, throwError, TimeoutError, timer } from 'rxjs'; import { map, mergeMap, retryWhen, switchMap, take, timeout } from 'rxjs/operators'; import { AuthStateService } from '../authState/auth-state.service'; import { AuthWellKnownService } from '../config/auth-well-known.service'; import { ConfigurationProvider } from '../config/config.provider'; import { FlowsDataService } from '../flows/flows-data.service'; import { RefreshSessionIframeService } from '../iframe/refresh-session-iframe.service'; import { SilentRenewService } from '../iframe/silent-renew.service'; import { LoggerService } from '../logging/logger.service'; import { FlowHelper } from '../utils/flowHelper/flow-helper.service'; import { RefreshSessionRefreshTokenService } from './refresh-session-refresh-token.service'; export const MAX_RETRY_ATTEMPTS = 3; @Injectable({ providedIn: 'root' }) export class RefreshSessionService { constructor( private flowHelper: FlowHelper, private configurationProvider: ConfigurationProvider, private flowsDataService: FlowsDataService, private loggerService: LoggerService, private silentRenewService: SilentRenewService, private authStateService: AuthStateService, private authWellKnownService: AuthWellKnownService, private refreshSessionIframeService: RefreshSessionIframeService, private refreshSessionRefreshTokenService: RefreshSessionRefreshTokenService ) {} forceRefreshSession(customParams?: { [key: string]: string | number | boolean }) { if (this.flowHelper.isCurrentFlowCodeFlowWithRefreshTokens()) { return this.startRefreshSession(customParams).pipe( map(() => { const isAuthenticated = this.authStateService.areAuthStorageTokensValid(); if (isAuthenticated) { return { idToken: this.authStateService.getIdToken(), accessToken: this.authStateService.getAccessToken(), }; } return null; }) ); } return forkJoin([ this.startRefreshSession(customParams), this.silentRenewService.refreshSessionWithIFrameCompleted$.pipe(take(1)), ]).pipe( timeout(this.configurationProvider.openIDConfiguration.silentRenewTimeoutInSeconds * 1000), retryWhen(this.timeoutRetryStrategy.bind(this)), map(([_, callbackContext]) => { const isAuthenticated = this.authStateService.areAuthStorageTokensValid(); if (isAuthenticated) { return { idToken: callbackContext?.authResult?.id_token, accessToken: callbackContext?.authResult?.access_token, }; } return null; }) ); } private startRefreshSession(customParams?: { [key: string]: string | number | boolean }) { const isSilentRenewRunning = this.flowsDataService.isSilentRenewRunning(); this.loggerService.logDebug(`Checking: silentRenewRunning: ${isSilentRenewRunning}`); const shouldBeExecuted = !isSilentRenewRunning; if (!shouldBeExecuted) { return of(null); } const authWellknownEndpointAdress = this.configurationProvider.openIDConfiguration?.authWellknownEndpoint; if (!authWellknownEndpointAdress) { this.loggerService.logError('no authwellknownendpoint given!'); return of(null); } return this.authWellKnownService.getAuthWellKnownEndPoints(authWellknownEndpointAdress).pipe( switchMap(() => { this.flowsDataService.setSilentRenewRunning(); if (this.flowHelper.isCurrentFlowCodeFlowWithRefreshTokens()) { // Refresh Session using Refresh tokens return this.refreshSessionRefreshTokenService.refreshSessionWithRefreshTokens(customParams); } return this.refreshSessionIframeService.refreshSessionWithIframe(customParams); }) ); } private timeoutRetryStrategy(errorAttempts: Observable<any>) { return errorAttempts.pipe( mergeMap((error, index) => { const scalingDuration = 1000; const currentAttempt = index + 1; if (!(error instanceof TimeoutError) || currentAttempt > MAX_RETRY_ATTEMPTS) { return throwError(error); } this.loggerService.logDebug(`forceRefreshSession timeout. Attempt #${currentAttempt}`); this.flowsDataService.resetSilentRenewRunning(); return timer(currentAttempt * scalingDuration); }) ); } }
<<<<<<< import { LoggerService } from '../logging/logger.service'; ======= import { StoragePersistanceService } from '../storage'; >>>>>>> import { LoggerService } from '../logging/logger.service'; import { StoragePersistanceService } from '../storage'; <<<<<<< import { OidcSecurityCommon } from './oidc.security.common'; ======= import { LoggerService } from './oidc.logger.service'; >>>>>>>
<<<<<<< import { OidcSecurityStorage } from '../../lib/services/oidc.security.storage'; ======= import { LoggerService } from '../../lib/services/oidc.logger.service'; >>>>>>> <<<<<<< import { TestStorage } from '../common/test-storage.service'; ======= import { AbstractSecurityStorage } from '../../lib/storage'; import { BrowserStorageMock } from '../../lib/storage/browser-storage.service-mock'; import { TestLogging } from '../common/test-logging.service'; >>>>>>> import { AbstractSecurityStorage } from '../../lib/storage'; import { BrowserStorageMock } from '../../lib/storage/browser-storage.service-mock';
<<<<<<< import { async, fakeAsync, TestBed, tick } from '@angular/core/testing'; ======= import { TestBed, waitForAsync } from '@angular/core/testing'; >>>>>>> import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; <<<<<<< it('only calls start refresh session and returns idtoken and accesstoken if auth is true', async(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefeshTokens').and.returnValue(true); spyOn(refreshSessionService as any, 'startRefreshSession').and.returnValue(of(null)); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(true); refreshSessionService.forceRefreshSession().subscribe((result) => { expect(result.idToken).not.toBeUndefined(); expect(result.accessToken).not.toBeUndefined(); }); })); it('only calls start refresh session and returns null if auth is false', async(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefeshTokens').and.returnValue(true); spyOn(refreshSessionService as any, 'startRefreshSession').and.returnValue(of(null)); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(false); refreshSessionService.forceRefreshSession().subscribe((result) => { expect(result).toBeNull(); }); })); it('calls start refresh session and waits for completed, returns idtoken and accesstoken if auth is true', async(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefeshTokens').and.returnValue(false); spyOn(refreshSessionService as any, 'startRefreshSession').and.returnValue(of(null)); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(true); spyOnProperty(configurationProvider, 'openIDConfiguration').and.returnValue({ silentRenewTimeoutInSeconds: 10 }); refreshSessionService.forceRefreshSession().subscribe((result) => { expect(result.idToken).toBeDefined(); expect(result.accessToken).toBeDefined(); }); (silentRenewService as any).fireRefreshWithIframeCompleted({ authResult: { id_token: 'id_token', access_token: 'access_token' }, }); })); it('calls start refresh session and waits for completed, returns null if auth is false', async(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefeshTokens').and.returnValue(false); spyOn(refreshSessionService as any, 'startRefreshSession').and.returnValue(of(null)); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(false); spyOnProperty(configurationProvider, 'openIDConfiguration').and.returnValue({ silentRenewTimeoutInSeconds: 10 }); refreshSessionService.forceRefreshSession().subscribe((result) => { expect(result).toBeNull(); }); (silentRenewService as any).fireRefreshWithIframeCompleted({ authResult: { id_token: 'id_token', access_token: 'access_token' }, }); })); it('occurs timeout error and retry mechanism exhausted max retry count throws error', fakeAsync(() => { const openIDConfiguration = { silentRenewTimeoutInSeconds: 10, }; spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefeshTokens').and.returnValue(false); spyOn(refreshSessionService as any, 'startRefreshSession').and.returnValue(of(null)); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(false); spyOnProperty(configurationProvider, 'openIDConfiguration').and.returnValue(openIDConfiguration); const resetSilentRenewRunningSpy = spyOn(flowsDataService, 'resetSilentRenewRunning'); const expectedInvokeCount = (refreshSessionService as any).MAX_RETRY_ATTEMPTS; refreshSessionService.forceRefreshSession().subscribe( () => { fail('It should not return any result.'); }, (error) => { expect(error).toBeInstanceOf(TimeoutError); expect(resetSilentRenewRunningSpy).toHaveBeenCalledTimes(expectedInvokeCount); } ); tick(openIDConfiguration.silentRenewTimeoutInSeconds * 10000); })); it('occurs unknown error throws it to subscriber', fakeAsync(() => { const openIDConfiguration = { silentRenewTimeoutInSeconds: 10, }; const expectedErrorMessage = 'Test error message'; spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefeshTokens').and.returnValue(false); spyOn(refreshSessionService as any, 'startRefreshSession').and.returnValue(throwError(new Error(expectedErrorMessage))); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(false); spyOnProperty(configurationProvider, 'openIDConfiguration').and.returnValue(openIDConfiguration); const resetSilentRenewRunningSpy = spyOn(flowsDataService, 'resetSilentRenewRunning'); refreshSessionService.forceRefreshSession().subscribe( () => { fail('It should not return any result.'); }, (error) => { expect(error).toBeInstanceOf(Error); expect((error as Error).message === expectedErrorMessage).toBeTruthy(); expect(resetSilentRenewRunningSpy).not.toHaveBeenCalled(); } ); })); describe('NOT isCurrentFlowCodeFlowWithRefeshTokens', () => { it('does return null when not authenticated', async(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefeshTokens').and.returnValue(false); ======= it( 'only calls start refresh session and returns idtoken and accesstoken if auth is true', waitForAsync(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefreshTokens').and.returnValue(true); spyOn(refreshSessionService as any, 'startRefreshSession').and.returnValue(of(null)); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(true); refreshSessionService.forceRefreshSession().subscribe((result) => { expect(result.idToken).not.toBeUndefined(); expect(result.accessToken).not.toBeUndefined(); }); }) ); it( 'only calls start refresh session and returns null if auth is false', waitForAsync(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefreshTokens').and.returnValue(true); >>>>>>> it( 'only calls start refresh session and returns idtoken and accesstoken if auth is true', waitForAsync(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefreshTokens').and.returnValue(true); spyOn(refreshSessionService as any, 'startRefreshSession').and.returnValue(of(null)); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(true); spyOnProperty(configurationProvider, 'openIDConfiguration').and.returnValue({ silentRenewTimeoutInSeconds: 10 }); refreshSessionService.forceRefreshSession().subscribe((result) => { expect(result.idToken).not.toBeUndefined(); expect(result.accessToken).not.toBeUndefined(); }); }) ); it( 'only calls start refresh session and returns null if auth is false', waitForAsync(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlowWithRefreshTokens').and.returnValue(true); <<<<<<< spyOnProperty(configurationProvider, 'openIDConfiguration').and.returnValue({ silentRenewTimeoutInSeconds: 10 }); const spyInsideMap = spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(true); refreshSessionService .forceRefreshSession() .toPromise() .then((result) => expect(result).toEqual({ idToken: 'id_token', accessToken: 'access_token' })) .then(() => expect(spyInsideMap).toHaveBeenCalledTimes(1)); ======= spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(false); >>>>>>> spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue(false); spyOnProperty(configurationProvider, 'openIDConfiguration').and.returnValue({ silentRenewTimeoutInSeconds: 10 });
<<<<<<< eagerLoadAuthWellKnownEndpoints: true, ======= disableRefreshIdTokenAuthTimeValidation: false, >>>>>>> eagerLoadAuthWellKnownEndpoints: true, disableRefreshIdTokenAuthTimeValidation: false, <<<<<<< eagerLoadAuthWellKnownEndpoints: true, ======= disableRefreshIdTokenAuthTimeValidation: false, >>>>>>> eagerLoadAuthWellKnownEndpoints: true, disableRefreshIdTokenAuthTimeValidation: false, <<<<<<< eagerLoadAuthWellKnownEndpoints: true, ======= disableRefreshIdTokenAuthTimeValidation: false, >>>>>>> eagerLoadAuthWellKnownEndpoints: true, disableRefreshIdTokenAuthTimeValidation: false,
<<<<<<< import { OidcSecurityUserService } from '../userData/oidc.security.user-service'; import { UrlService } from '../utils'; ======= import { RandomService, UrlService } from '../utils'; >>>>>>> import { OidcSecurityUserService } from '../userData/oidc.security.user-service'; import { RandomService, UrlService } from '../utils';
<<<<<<< } // @internal export interface ProcessorConstructor { transformName(fileName: string, settings: ReadonlyMap<string, any>): string; new(source: string, sourceFileName: string, targetFileName: string, settings: ReadonlyMap<string, any>): AbstractProcessor; } export interface ProcessorUpdateResult { transformed: string; changeRange?: ts.TextChangeRange; } export abstract class AbstractProcessor { /** * Returns the resulting file name. */ public static transformName(fileName: string, _settings: ReadonlyMap<string, any>): string { return fileName; } constructor( protected source: string, protected sourceFileName: string, protected targetFileName: string, protected settings: ReadonlyMap<string, any>, ) {} public abstract preprocess(): string; public abstract postprocess(failures: Failure[]): Failure[]; public abstract updateSource(newSource: string, changeRange: ts.TextChangeRange): ProcessorUpdateResult; } ======= } export interface MessageHandler { log(message: string): void; warn(message: string): void; error(e: Error): void; } export abstract class MessageHandler {} export interface FileSystemReader { readFile(file: string): Buffer; readDirectory(dir: string): string[]; stat(path: string): Stats; } export abstract class FileSystemReader {} export interface Stats { isDirectory(): boolean; isFile(): boolean; } export interface RuleLoaderHost { loadCoreRule(name: string): RuleConstructor | undefined; loadCustomRule(name: string, directory: string): RuleConstructor | undefined; } export abstract class RuleLoaderHost {} export interface FormatterLoaderHost { loadCoreFormatter(name: string): FormatterConstructor | undefined; loadCustomFormatter(name: string, basedir: string): FormatterConstructor | undefined; } export abstract class FormatterLoaderHost {} export interface CacheManager { get<K, V>(id: CacheIdentifier<K, V>, key: K): V | undefined; resolve<K, V>(id: CacheIdentifier<K, V>, key: K, cb: (key: K) => V): V; set<K, V>(id: CacheIdentifier<K, V>, key: K, value: V): void; delete<K>(id: CacheIdentifier<K, any>, key: K): void; has<K>(id: CacheIdentifier<K, any>, key: K): boolean; clear(id: CacheIdentifier<any, any>): void; } export abstract class CacheManager {} export class CacheIdentifier<K, V> { protected key: K; protected value: V; constructor(public description: string) {} } export interface Resolver { resolve(id: string, basedir: string, extensions: string[], paths?: string[]): string; require(id: string, options?: {cache?: boolean}): any; } export abstract class Resolver {} export const CurrentDirectory = Symbol('CurrentDirectory'); export const HomeDirectory = Symbol('HomeDirectory'); >>>>>>> } // @internal export interface ProcessorConstructor { transformName(fileName: string, settings: ReadonlyMap<string, any>): string; new(source: string, sourceFileName: string, targetFileName: string, settings: ReadonlyMap<string, any>): AbstractProcessor; } export interface ProcessorUpdateResult { transformed: string; changeRange?: ts.TextChangeRange; } export abstract class AbstractProcessor { /** * Returns the resulting file name. */ public static transformName(fileName: string, _settings: ReadonlyMap<string, any>): string { return fileName; } constructor( protected source: string, protected sourceFileName: string, protected targetFileName: string, protected settings: ReadonlyMap<string, any>, ) {} public abstract preprocess(): string; public abstract postprocess(failures: Failure[]): Failure[]; public abstract updateSource(newSource: string, changeRange: ts.TextChangeRange): ProcessorUpdateResult; } export interface MessageHandler { log(message: string): void; warn(message: string): void; error(e: Error): void; } export abstract class MessageHandler {} export interface FileSystemReader { readFile(file: string): Buffer; readDirectory(dir: string): string[]; stat(path: string): Stats; } export abstract class FileSystemReader {} export interface Stats { isDirectory(): boolean; isFile(): boolean; } export interface RuleLoaderHost { loadCoreRule(name: string): RuleConstructor | undefined; loadCustomRule(name: string, directory: string): RuleConstructor | undefined; } export abstract class RuleLoaderHost {} export interface FormatterLoaderHost { loadCoreFormatter(name: string): FormatterConstructor | undefined; loadCustomFormatter(name: string, basedir: string): FormatterConstructor | undefined; } export abstract class FormatterLoaderHost {} export interface CacheManager { get<K, V>(id: CacheIdentifier<K, V>, key: K): V | undefined; resolve<K, V>(id: CacheIdentifier<K, V>, key: K, cb: (key: K) => V): V; set<K, V>(id: CacheIdentifier<K, V>, key: K, value: V): void; delete<K>(id: CacheIdentifier<K, any>, key: K): void; has<K>(id: CacheIdentifier<K, any>, key: K): boolean; clear(id: CacheIdentifier<any, any>): void; } export abstract class CacheManager {} export class CacheIdentifier<K, V> { protected key: K; protected value: V; constructor(public description: string) {} } export interface Resolver { resolve(id: string, basedir: string, extensions: string[], paths?: string[]): string; require(id: string, options?: {cache?: boolean}): any; } export abstract class Resolver {} export const CurrentDirectory = Symbol('CurrentDirectory'); export const HomeDirectory = Symbol('HomeDirectory');
<<<<<<< export * from './stitching'; export * from './transforms'; ======= export * from './stitching'; export * from './schemaVisitor'; >>>>>>> export * from './stitching'; export * from './transforms'; export * from './schemaVisitor';
<<<<<<< import * as TextObjectsWordTest from './TextObjects/Word.test'; ======= import * as MotionIntegrationTest from './MotionIntegration.test'; >>>>>>> import * as MotionIntegrationTest from './MotionIntegration.test'; import * as TextObjectsWordTest from './TextObjects/Word.test'; <<<<<<< suite('Extension Tests', () => { suite('MotionWordTests', () => { MotionWordTests.run(); }); suite('TextObjectsTests', () => { TextObjectsWordTest.run(); }); ======= suite('Extension Tests', () => { MotionWordTests.run(); MotionIntegrationTest.run(); >>>>>>> suite('Extension Tests', () => { MotionWordTests.run(); MotionIntegrationTest.run(); TextObjectsWordTest.run();
<<<<<<< { keys: 'c i {char}', command: (args: {character: string}) => ActionMoveCursor.byMotions({motions: [ MotionMatchPairs.matchOpening(args, LastCharacterMatching.Exclude, FirstPosPairMatching.Ignore) ]}) //we should not apply the delete move is the first cursor move is invalid. //for now, this implementation leads to issue like this (cursor : -) // 11111"22222" // - //when we enter ci" //leads to // 1"22222" // - .then(() => ActionDelete.byMotions({motions: [MotionMatchPairs.matchClosing(args, LastCharacterMatching.Include, FirstPosPairMatching.Notice)], shouldYank: true})) .then(() => ActionMode.toInsert()) }, { keys: 'S', command: () => { return ActionMoveCursor.byMotions({motions: [MotionLine.firstNonBlank()]}) .then(ActionDelete.byMotions.bind(undefined, {motions: [MotionLine.end()], shouldYank: true})) .then(() => ActionMode.toInsert()); } }, { keys: 'c {motion}', command: (args: {motions: Motion[], shouldYank?: boolean}) => ActionDelete.byMotions(args).then(() => ActionMode.toInsert()), args: {shouldYank: true, cwNeedsFixup: true} }, { keys: 'J', command: ActionJoinLines.onSelections }, { keys: 'r {char}', command: ActionReplace.characters }, { keys: 'y y', command: ActionRegister.yankLines }, { keys: 'Y', command: ActionRegister.yankLines }, { keys: 'y {motion}', command: ActionRegister.yankByMotions }, { keys: 'p', command: ActionRegister.putAfter }, { keys: 'P', command: ActionRegister.putBefore }, { keys: 'n', command: ActionFind.next }, { keys: 'N', command: ActionFind.prev }, { keys: '*', command: () => ActionFind.byIndicator().then(() => ActionFind.next()) }, { keys: '#', command: () => ActionFind.byIndicator().then(() => ActionFind.prev()) }, { keys: 'u', command: ActionHistory.undo }, { keys: 'ctrl+r', command: ActionHistory.redo }, { keys: '< <', command: ActionIndent.decrease }, { keys: '> >', command: ActionIndent.increase }, { keys: '/', command: ActionFind.focusFindWidget }, { keys: 'v', command: ActionMode.toVisual }, { keys: 'V', command: ActionMode.toVisualLine }, ======= >>>>>>>
<<<<<<< ======= import {ActionFold} from '../Actions/Fold'; import {MotionLine} from '../Motions/Line'; >>>>>>> import {ActionFold} from '../Actions/Fold';
<<<<<<< { keys: 'z .', command: ActionReveal.primaryCursor, args: {revealType: TextEditorRevealType.InCenter} }, { keys: 'z z', command: ActionReveal.primaryCursor, args: {revealType: TextEditorRevealType.InCenter} }, { keys: 'ctrl+c', command: () => Configuration.get('bindCtrlC') ======= { keys: 'ctrl+c', command: () => Configuration.getExtensionSetting('bindCtrlC') >>>>>>> { keys: 'z .', command: ActionReveal.primaryCursor, args: {revealType: TextEditorRevealType.InCenter} }, { keys: 'z z', command: ActionReveal.primaryCursor, args: {revealType: TextEditorRevealType.InCenter} }, { keys: 'ctrl+c', command: () => Configuration.getExtensionSetting('bindCtrlC')
<<<<<<< export class StyleSheetManager extends React.Component<{sheet: ServerStyleSheet}, any> {} export class ServerStyleSheet { collectStyles(tree: any): StyleSheetManager; getStyleTags(): string; getStyleElement(): Component<any>; } ======= export class ServerStyleSheet { collectStyles(children: ReactElement<any>): ReactElement<any> getStyleTags(): string getStyleElement(): ReactElement<any>[] static create(): StyleSheet } >>>>>>> export class StyleSheetManager extends React.Component<{sheet: ServerStyleSheet}, any> {} export class ServerStyleSheet { collectStyles(children: ReactElement<any>): StyleSheetManager collectStyles(tree: any): StyleSheetManager; getStyleTags(): string; getStyleElement(): ReactElement<any>[] static create(): StyleSheet }
<<<<<<< import { InvalidationMode, SyncMode } from "@/core/comm/types"; import { GlobalPoint, Ray } from "@/game/geom"; ======= import { GlobalPoint, LocalPoint } from "@/game/geom"; >>>>>>> import { InvalidationMode, SyncMode } from "@/core/comm/types"; <<<<<<< const polygon = computeVisibility(center, TriangulationTarget.VISION, shape.floor); this.vCtx.beginPath(); this.vCtx.moveTo(g2lx(polygon[0][0]), g2ly(polygon[0][1])); for (const point of polygon) this.vCtx.lineTo(g2lx(point[0]), g2ly(point[1])); this.vCtx.closePath(); this.vCtx.fill(); if (aura.dim > 0) { // Fill the light aura with a radial dropoff towards the outside. const gradient = this.vCtx.createRadialGradient( lcenter.x, lcenter.y, g2lr(aura.value), lcenter.x, lcenter.y, g2lr(aura.value + aura.dim), ); gradient.addColorStop(0, "rgba(0, 0, 0, 1)"); gradient.addColorStop(1, "rgba(0, 0, 0, 0)"); this.vCtx.fillStyle = gradient; } else { this.vCtx.fillStyle = "rgba(0, 0, 0, 1)"; } this.vCtx.globalCompositeOperation = "source-in"; this.vCtx.beginPath(); this.vCtx.arc(lcenter.x, lcenter.y, g2lr(aura.value + aura.dim), 0, 2 * Math.PI); this.vCtx.fill(); ctx.drawImage(this.virtualCanvas, 0, 0); // aura.lastPath = this.updateAuraPath(polygon, auraCircle); // shape.invalidate(true); ======= >>>>>>>
<<<<<<< import { g2l, g2lr, g2lx, g2ly, g2lz } from "@/game/units"; ======= import { g2l, g2lr, g2lx, g2ly, g2lz, getUnitDistance } from "@/game/units"; import { addBlocker, getBlockers, getVisionSources, setVisionSources, sliceBlockers } from "@/game/visibility/utils"; import tinycolor from "tinycolor2"; >>>>>>> import { g2l, g2lr, g2lx, g2ly, g2lz, getUnitDistance } from "@/game/units"; import { addBlocker, getBlockers, getVisionSources, setVisionSources, sliceBlockers } from "@/game/visibility/utils"; import tinycolor from "tinycolor2"; <<<<<<< import { TriangulationTarget } from "../visibility/te/pa"; ======= import { TriangulationTarget } from "../visibility/te/pa"; import { computeVisibility } from "../visibility/te/te"; import { updateAuraPath } from "./utils"; >>>>>>> import { TriangulationTarget } from "../visibility/te/pa"; import { computeVisibility } from "../visibility/te/te"; import { updateAuraPath } from "./utils"; <<<<<<< checkVisionSources(recalculate = true): boolean { let alteredVision = false; const self = this; const obstructionIndex = visibilityStore.visionBlockers.indexOf(this.uuid); ======= checkVisionSources(recalculate = true): void { const visionBlockers = getBlockers(TriangulationTarget.VISION, this.floor); const obstructionIndex = visionBlockers.indexOf(this.uuid); let update = false; >>>>>>> checkVisionSources(recalculate = true): boolean { let alteredVision = false; const visionBlockers = getBlockers(TriangulationTarget.VISION, this.floor); const obstructionIndex = visionBlockers.indexOf(this.uuid); <<<<<<< visibilityStore.visionBlockers.push(this.uuid); if (recalculate) { visibilityStore.addToTriag({ target: TriangulationTarget.VISION, shape: this }); visibilityStore.recalculateVision(); alteredVision = true; } ======= addBlocker(TriangulationTarget.VISION, this.uuid, this.floor); update = true; >>>>>>> addBlocker(TriangulationTarget.VISION, this.uuid, this.floor); if (recalculate) visibilityStore.addToTriag({ target: TriangulationTarget.VISION, shape: this }); alteredVision = true; <<<<<<< return alteredVision; ======= setVisionSources(visionSources, this.floor); >>>>>>> setVisionSources(visionSources, this.floor); return alteredVision; <<<<<<< const obstructionIndex = visibilityStore.movementblockers.indexOf(this.uuid); let alteredMovement = false; ======= const movementBlockers = getBlockers(TriangulationTarget.MOVEMENT, this.floor); const obstructionIndex = movementBlockers.indexOf(this.uuid); let update = false; >>>>>>> const movementBlockers = getBlockers(TriangulationTarget.MOVEMENT, this.floor); const obstructionIndex = movementBlockers.indexOf(this.uuid); <<<<<<< visibilityStore.movementblockers.push(this.uuid); if (recalculate) { visibilityStore.addToTriag({ target: TriangulationTarget.MOVEMENT, shape: this }); visibilityStore.recalculateMovement(); alteredMovement = true; } ======= addBlocker(TriangulationTarget.MOVEMENT, this.uuid, this.floor); update = true; >>>>>>> addBlocker(TriangulationTarget.MOVEMENT, this.uuid, this.floor); if (recalculate) visibilityStore.addToTriag({ target: TriangulationTarget.MOVEMENT, shape: this }); alteredMovement = true;
<<<<<<< import { calculateDelta } from "../tools/utils"; ======= import { calculateDelta } from "../tools/tools"; import { SelectTool } from "../tools/select"; >>>>>>> import { SelectTool } from "../tools/select"; import { calculateDelta } from "../tools/utils";
<<<<<<< import Tools from "@/game/ui/tools/tools.vue"; import { getRef } from "@/core/utils"; ======= import { uuidv4 } from "@/core/utils"; >>>>>>> <<<<<<< ======= import { ServerAura } from "@/game/comm/types/shapes"; import { EventBus } from "@/game/event-bus"; >>>>>>> <<<<<<< deleteShapes() ======= if (layerManager.getLayer === undefined) { console.log("No active layer selected for delete operation"); return; } const l = layerManager.getLayer()!; for (let i = l.selection.length - 1; i >= 0; i--) { const sel = l.selection[i]; if (gameStore.selectionHelperID === sel.uuid) { l.selection.splice(i, 1); continue; } l.removeShape(sel, true, false); EventBus.$emit("SelectionInfo.Shape.Set", null); EventBus.$emit("Initiative.Remove", sel.uuid); } >>>>>>> deleteShapes(); <<<<<<< export function onKeyDown(event: KeyboardEvent) { updateKeyboardState(event); ======= export function onKeyDown(event: KeyboardEvent): void { >>>>>>> export function onKeyDown(event: KeyboardEvent): void { updateKeyboardState(event); <<<<<<< // Ctrl-c - Copy copyShapes() ======= const layer = layerManager.getLayer(); if (!layer) return; if (!layer.selection) return; const clipboard = []; for (const shape of layer.selection) { if (gameStore.selectionHelperID === shape.uuid) continue; clipboard.push(shape.asDict()); } gameStore.setClipboard(clipboard); >>>>>>> // Ctrl-c - Copy copyShapes(); <<<<<<< // Ctrl-v - Paste pasteShapes() ======= const layer = layerManager.getLayer(); if (!layer) return; if (!gameStore.clipboard) return; layer.selection = []; for (const clip of gameStore.clipboard) { clip.x += 10; clip.y += 10; clip.uuid = uuidv4(); const oldTrackers = clip.trackers; clip.trackers = []; for (const tracker of oldTrackers) { const newTracker: Tracker = { ...tracker, uuid: uuidv4(), }; clip.trackers.push(newTracker); } const oldAuras = clip.auras; clip.auras = []; for (const aura of oldAuras) { const newAura: ServerAura = { ...aura, uuid: uuidv4(), }; clip.auras.push(newAura); } const shape = createShapeFromDict(clip); if (shape === undefined) continue; layer.addShape(shape, true); layer.selection.push(shape); } if (layer.selection.length === 1) EventBus.$emit("SelectionInfo.Shape.Set", layer.selection[0]); else EventBus.$emit("SelectionInfo.Shape.Set", null); layer.invalidate(false); >>>>>>> // Ctrl-v - Paste pasteShapes();
<<<<<<< } export function getFogColour(opposite: boolean = false): string { const tc = gameManager.fowColour.spectrum("get"); if (Settings.IS_DM) tc.setAlpha(opposite ? 1 : Settings.fowOpacity); else tc.setAlpha(1); return tc.toRgbString(); } export function alphSort(a: string, b: string) { if (a.toLowerCase() < b.toLowerCase()) return -1; else return 1; } export function getHTMLTextWidth(element: JQuery<HTMLElement>): number { let fakeElement = $('#emptyspan'); if (fakeElement.length == 0) { fakeElement = $('<span id="emptyspan"></span>'); fakeElement.hide().appendTo(document.body) } let text = element.text(); if (text === '' && typeof element.val() === 'string') text = <string>element.val(); else return 0; fakeElement.text(text).css('font', element.css('font')); return Math.ceil(<number>fakeElement.width()); } export function partition<T>(arr: T[], predicate: (n: T) => boolean) { const ret: T[][] = [[], []]; arr.forEach((n) => predicate(n) ? ret[1].push(n) : ret[0].push(n)); return ret; } export function capitalize(text: string) { return text.charAt(0).toUpperCase() + text.slice(1); } // Reference: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript export function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } export function calcFontScale(ctx: CanvasRenderingContext2D, text: string, width: number, height: number) { const points = Number(ctx.font.split("px")[0]) * 0.2; const fontWidth = ctx.measureText(text).width; return Math.min(width / fontWidth, height / points); } export function fixedEncodeURIComponent(str: string) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); } export class OrderedMap<K, V> { keys: K[] = []; values: V[] = []; get(key: K) { return this.values[this.keys.indexOf(key)]; } getIndexValue(idx: number) { return this.values[idx]; } getIndexKey(idx: number) { return this.keys[idx]; } set(key: K, value: V) { this.keys.push(key); this.values.push(value); } indexOf(element: K) { return this.keys.indexOf(element); } remove(element: K) { const idx = this.indexOf(element); this.keys.splice(idx, 1); this.values.splice(idx, 1); } ======= >>>>>>> } export function getFogColour(opposite: boolean = false): string { const tc = gameManager.fowColour.spectrum("get"); if (Settings.IS_DM) tc.setAlpha(opposite ? 1 : Settings.fowOpacity); else tc.setAlpha(1); return tc.toRgbString();
<<<<<<< import { labelMap } from '../common'; ======= import { auth } from '../../../assets/data-test-attributes'; >>>>>>> import { labelMap } from '../common'; import { auth } from '../../../assets/data-test-attributes';
<<<<<<< this.storage = new Storage(this.config.cache!); TrustedAuthority.setTrustedAuthoritiesFromConfig(this.config.auth.knownAuthorities!, this.config.auth.instanceMetadata!); this.cacheContext = new CacheContext(); ======= B2cAuthority.setKnownAuthorities(this.config.auth.knownAuthorities!); >>>>>>> TrustedAuthority.setTrustedAuthoritiesFromConfig(this.config.auth.knownAuthorities!, this.config.auth.instanceMetadata!);
<<<<<<< private readonly _renderState: WebGLRenderState = this._globalGameObject.getOrAddComponent(WebGLRenderState); ======= >>>>>>>
<<<<<<< idTokenClaims: StringDict; refreshToken: string; accessToken: string; expiresOn: Date; extExpiresOn?: Date; // TODO: Check what this maps to in other libraries userRequestState?: string; // TODO: remove, just check how state is handled in other libraries familyId?: string; // TODO: Check wider audience } ======= idTokenClaims: StringDict; accessToken: string; refreshToken: string; // TODO: Confirm if we need to return this to the user, follow up with msal-browser expiresOn: Date; extExpiresOn?: Date; // TODO: Check what this maps to in other libraries userRequestState?: string; // TODO: remove, just check how state is handled in other libraries familyId?: string; // TODO: Check wider audience }; >>>>>>> idTokenClaims: StringDict; accessToken: string; refreshToken: string; // TODO: Confirm if we need to return this to the user, follow up with msal-browser expiresOn: Date; extExpiresOn?: Date; // TODO: Check what this maps to in other libraries userRequestState?: string; // TODO: remove, just check how state is handled in other libraries familyId?: string; // TODO: Check wider audience }
<<<<<<< </div> ` ======= `; >>>>>>> </div> `;
<<<<<<< export class CredentialsClass { ======= const CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future export class Credentials { >>>>>>> const CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future export class CredentialsClass { <<<<<<< private _identityId; ======= private _nextCredentialsRefresh: Number; >>>>>>> private _identityId; private _nextCredentialsRefresh: Number; <<<<<<< logger.debug('are these credentials expired?', credentials); const ts = Math.floor(Date.now() / 1000); const delta = 10 * 60; // 10 minutes in seconds const { expiration } = credentials; // returns unix time stamp if (expiration > ts + delta) { ======= logger.debug('is this credentials expired?', credentials); const ts = new Date().getTime(); const delta = 10 * 60 * 1000; // 10 minutes const { expired, expireTime } = credentials; if ( !expired && expireTime > ts + delta && ts < this._nextCredentialsRefresh ) { >>>>>>> logger.debug('are these credentials expired?', credentials); const ts = Math.floor(Date.now() / 1000); const delta = 10 * 60; // 10 minutes in seconds const { expiration } = credentials; // returns unix time stamp if (expiration > ts + delta && ts < this._nextCredentialsRefresh) { <<<<<<< credentials .then(async credentials => { logger.debug('Load credentials successfully', credentials); if (this._identityId && !credentials.identityId) { credentials['identityId'] = this._identityId; ======= credentials.get(async err => { if (err) { logger.debug('Failed to load credentials', credentials); rej(err); return; } logger.debug('Load credentials successfully', credentials); that._credentials = credentials; that._credentials.authenticated = authenticated; that._credentials_source = source; that._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL; if (source === 'federated') { const user = Object.assign( { id: this._credentials.identityId }, info.user ); const { provider, token, expires_at, identity_id } = info; try { this._storage.setItem( 'aws-amplify-federatedInfo', JSON.stringify({ provider, token, user, expires_at, identity_id, }) ); } catch (e) { logger.debug('Failed to put federated info into auth storage', e); >>>>>>> credentials .then(async credentials => { logger.debug('Load credentials successfully', credentials); if (this._identityId && !credentials.identityId) { credentials['identityId'] = this._identityId;
<<<<<<< const packageInfo = require('../../package.json'); ======= import { version } from '../../package.json'; import { appendToUserAgent } from '@aws-sdk/util-user-agent-browser'; >>>>>>> const packageInfo = require('../../package.json'); import { appendToUserAgent } from '@aws-sdk/util-user-agent-browser';
<<<<<<< import { Amplify, ConsoleLogger as Logger, Credentials } from '@aws-amplify/core'; ======= import Amplify, { ConsoleLogger as Logger, Credentials } from '@aws-amplify/core'; import Auth from '@aws-amplify/auth'; >>>>>>> import { Amplify, ConsoleLogger as Logger, Credentials } from '@aws-amplify/core'; import { Auth } from '@aws-amplify/auth';
<<<<<<< /** * JWK Key Format string (Type MUST be defined for window crypto APIs) */ export const KEY_FORMAT_JWK = "jwk"; ======= // JWK Key Format string (Type MUST be defined for window crypto APIs) export const KEY_FORMAT_JWK = "jwk"; // Supported wrapper SKUs export enum WrapperSKU { React = "@azure/msal-react", Angular = "@azure/msal-angular" } >>>>>>> /** * JWK Key Format string (Type MUST be defined for window crypto APIs) */ export const KEY_FORMAT_JWK = "jwk"; // Supported wrapper SKUs export enum WrapperSKU { React = "@azure/msal-react", Angular = "@azure/msal-angular" }
<<<<<<< public sendMFACode(confirmationCode: string, callbacks: { onSuccess: (session: CognitoUserSession) => void, onFailure: (err: any) => void }, mfaType: string): void; public forgetDevice(callbacks: {onSuccess: (success: string) => void, onFailure: (err: Error) => void}): void; public forgetSpecificDevice(deviceKey: string, callbacks: {onSuccess: (success: string) => void, onFailure: (err: Error) => void}): void; ======= public sendMFACode(confirmationCode: string, callbacks: { onSuccess: (session: CognitoUserSession) => void, onFailure: (err: any) => void }, mfaType?: string): void; >>>>>>> public forgetDevice(callbacks: {onSuccess: (success: string) => void, onFailure: (err: Error) => void}): void; public forgetSpecificDevice(deviceKey: string, callbacks: {onSuccess: (success: string) => void, onFailure: (err: Error) => void}): void; public sendMFACode(confirmationCode: string, callbacks: { onSuccess: (session: CognitoUserSession) => void, onFailure: (err: any) => void }, mfaType?: string): void;
<<<<<<< @Input() authState: AuthState; @Input() hide: string[] = []; ======= @Input() authState: AuthState; >>>>>>> @Input() authState: AuthState; @Input() hide: string[] = []; <<<<<<< let authComponent = this.framework && this.framework.toLowerCase() === 'ionic' ? new ComponentMount(ForgotPasswordComponentIonic,{hide: this.hide, authState: this.authState}) : new ComponentMount(ForgotPasswordComponentCore, {hide: this.hide, authState: this.authState}); ======= const authComponent = this.framework && this.framework.toLowerCase() === 'ionic' ? new ComponentMount(ForgotPasswordComponentIonic,{authState: this.authState}) : new ComponentMount(ForgotPasswordComponentCore, {authState: this.authState}); >>>>>>> const authComponent = this.framework && this.framework.toLowerCase() === 'ionic' ? new ComponentMount(ForgotPasswordComponentIonic,{hide: this.hide, authState: this.authState}) : new ComponentMount(ForgotPasswordComponentCore, {hide: this.hide, authState: this.authState});
<<<<<<< @Input() signUpConfig: any; ======= @Input() hide: string[] = []; >>>>>>> @Input() signUpConfig: any; @Input() hide: string[] = []; <<<<<<< const authComponent = this.framework && this.framework.toLowerCase() === 'ionic' ? new ComponentMount(SignUpComponentIonic, { authState: this.authState, signUpConfig: this.signUpConfig }) : new ComponentMount(SignUpComponentCore, { authState: this.authState, signUpConfig: this.signUpConfig }); ======= let authComponent = this.framework && this.framework.toLowerCase() === 'ionic' ? new ComponentMount(SignUpComponentIonic,{hide: this.hide, authState: this.authState}) : new ComponentMount(SignUpComponentCore, {hide: this.hide, authState: this.authState}); >>>>>>> const authComponent = this.framework && this.framework.toLowerCase() === 'ionic' ? new ComponentMount(SignUpComponentIonic, { authState: this.authState, signUpConfig: this.signUpConfig, hide: this.hide, }) : new ComponentMount(SignUpComponentCore, { authState: this.authState, signUpConfig: this.signUpConfig, hide: this.hide, });
<<<<<<< import { includes, labelMap, composePhoneNumber } from '../common'; import { UsernameAttributes, UsernameFieldOutput } from '../types'; ======= import { includes } from '../common'; import { auth } from '../../../assets/data-test-attributes'; >>>>>>> import { includes, labelMap, composePhoneNumber } from '../common'; import { UsernameAttributes, UsernameFieldOutput } from '../types'; import { auth } from '../../../assets/data-test-attributes'; <<<<<<< <amplify-auth-username-field-core [usernameAttributes]="_usernameAttributes" (usernameFieldChanged)="onUsernameFieldChanged($event)" ></amplify-auth-username-field-core> ======= <div class="amplify-amplify-form-row amplify-signin-username"> <label class="amplify-input-label" for="amplifyUsername"> {{ this.amplifyService.i18n().get('Username *') }} </label> <input #amplifyUsername (keyup)="setUsername($event.target.value)" class="amplify-form-input" type="text" required placeholder="{{ this.amplifyService.i18n().get('Username') }}" [value]="username" data-test="${auth.signIn.usernameInput}" /> </div> >>>>>>> <amplify-auth-username-field-core [usernameAttributes]="_usernameAttributes" (usernameFieldChanged)="onUsernameFieldChanged($event)" ></amplify-auth-username-field-core>
<<<<<<< ======= AWSKinesisFirehoseProvider, AmazonPersonalizeProvider, >>>>>>> AWSKinesisFirehoseProvider, AmazonPersonalizeProvider, <<<<<<< /** * @deprecated use named import */ export default Amplify; ======= export { Auth, Analytics, Storage, API, PubSub, I18n, Logger, Hub, Cache, JS, ClientDevice, Signer, ServiceWorker, Interactions, UI, XR, Predictions, }; export { AuthClass, AnalyticsClass, APIClass, StorageClass, PubSubClass, InteractionsClass, XRClass, AnalyticsProvider, AWSPinpointProvider, AWSKinesisProvider, AWSKinesisFirehoseProvider, AmazonPersonalizeProvider, }; export { graphqlOperation }; >>>>>>> /** * @deprecated use named import */ export default Amplify;
<<<<<<< identityPoolId: "awsCognitoIdentityPoolId", mandatorySignIn: false, }; ======= identityPoolId: "awsCognitoIdentityPoolId", mandatorySignIn: false } >>>>>>> identityPoolId: "awsCognitoIdentityPoolId", mandatorySignIn: false } <<<<<<< identityPoolId: "awsCognitoIdentityPoolId" }; ======= identityPoolId: "awsCognitoIdentityPoolId", mandatorySignIn: false } >>>>>>> identityPoolId: "awsCognitoIdentityPoolId", mandatorySignIn: false } <<<<<<< identityPoolId: "awsCognitoIdentityPoolId", mandatorySignIn: false, ======= identityPoolId: "awsCognitoIdentityPoolId", mandatorySignIn: false >>>>>>> identityPoolId: "awsCognitoIdentityPoolId", mandatorySignIn: false <<<<<<< token: 'token', user: { name: 'user' } }; ======= token: 'token' } >>>>>>> token: 'token' } <<<<<<< test('happy case for source userpool', async () => { const auth = new Auth(authOptions); const user = new CognitoUser({ Username: 'username', Pool: userPool }); auth['credentials_source'] = 'aws'; auth['credentials'] = new CognitoIdentityCredentials({ IdentityPoolId: 'identityPoolId' }); const spyonAuth = jest.spyOn(Auth.prototype, "currentUserCredentials") .mockImplementationOnce(() => { return new Promise((resolve, reject) => { resolve(); }); }); const spyon = jest.spyOn(CognitoUserPool.prototype, "getCurrentUser") .mockImplementationOnce(() => { return user; }); const spyon2 = jest.spyOn(CognitoUser.prototype, "signOut"); // @ts-ignore await auth.signOut(); expect.assertions(1); expect(spyon2).toBeCalled(); spyonAuth.mockClear(); spyon.mockClear(); spyon2.mockClear(); }); test('no UserPool', async () => { // @ts-ignore ======= test('happy case for no userpool', async () => { >>>>>>> test('happy case for source userpool', async () => { const auth = new Auth(authOptions); const user = new CognitoUser({ Username: 'username', Pool: userPool }); auth['credentials_source'] = 'aws'; auth['credentials'] = new CognitoIdentityCredentials({ IdentityPoolId: 'identityPoolId' }); const spyonAuth = jest.spyOn(Auth.prototype, "currentUserCredentials") .mockImplementationOnce(() => { return new Promise((resolve, reject) => { resolve(); }); }); const spyon = jest.spyOn(CognitoUserPool.prototype, "getCurrentUser") .mockImplementationOnce(() => { return user; }); const spyon2 = jest.spyOn(CognitoUser.prototype, "signOut"); // @ts-ignore await auth.signOut(); expect.assertions(1); expect(spyon2).toBeCalled(); spyonAuth.mockClear(); spyon.mockClear(); spyon2.mockClear(); }); test('happy case for no userpool', async () => { // @ts-ignore <<<<<<< describe('sendCustomChallengeAnswer', () => { test('happy case', async () => { const spyon = jest.spyOn(CognitoUser.prototype, 'sendCustomChallengeAnswer') .mockImplementationOnce((challengeResponses, callback) => { callback.onSuccess(session); }); const auth = new Auth(authOptions); const user = new CognitoUser({ Username: 'username', Pool: userPool }); const userAfterCustomChallengeAnswer = Object.assign( new CognitoUser({ Username: 'username', Pool: userPool }), { "challengeName": "CUSTOM_CHALLENGE", "challengeParam": "challengeParam" }); expect.assertions(1); expect(await auth.sendCustomChallengeAnswer(userAfterCustomChallengeAnswer, 'challengeResponse')).toEqual(user); spyon.mockClear(); }); test('customChallenge', async () => { const spyon = jest.spyOn(CognitoUser.prototype, 'sendCustomChallengeAnswer') .mockImplementationOnce((challengeResponses, callback) => { callback.customChallenge('challengeParam'); }); const auth = new Auth(authOptions); const user = new CognitoUser({ Username: 'username', Pool: userPool }); const userAfterCustomChallengeAnswer = Object.assign( new CognitoUser({ Username: 'username', Pool: userPool }), { "challengeName": "CUSTOM_CHALLENGE", "challengeParam": "challengeParam" }); expect.assertions(1); expect(await auth.sendCustomChallengeAnswer(userAfterCustomChallengeAnswer, 'challengeResponse')).toEqual(userAfterCustomChallengeAnswer); spyon.mockClear(); }); test('onFailure', async () => { const spyon = jest.spyOn(CognitoUser.prototype, 'sendCustomChallengeAnswer') .mockImplementationOnce((challengeResponses, callback) => { callback.onFailure('err'); }); const auth = new Auth(authOptions); const userAfterCustomChallengeAnswer = Object.assign( new CognitoUser({ Username: 'username', Pool: userPool }), { "challengeName": "CUSTOM_CHALLENGE", "challengeParam": "challengeParam" }); expect.assertions(1); try { await auth.sendCustomChallengeAnswer(userAfterCustomChallengeAnswer, 'challengeResponse'); } catch (e) { expect(e).toBe('err'); } spyon.mockClear(); }); test('no userPool', async () => { const spyon = jest.spyOn(CognitoUser.prototype, 'sendCustomChallengeAnswer'); // @ts-ignore const auth = new Auth(authOptionsWithNoUserPoolId); const userAfterCustomChallengeAnswer = Object.assign( new CognitoUser({ Username: 'username', Pool: userPool }), { "challengeName": "CUSTOM_CHALLENGE", "challengeParam": "challengeParam" }); expect.assertions(1); try { await auth.sendCustomChallengeAnswer(userAfterCustomChallengeAnswer, 'challengeResponse'); } catch (e) { expect(e).not.toBeNull(); } spyon.mockClear(); }); }); ======= describe('hosted ui test', () => { test('happy case', () => { const oauth = {}; const authOptions = { Auth: { userPoolId: "awsUserPoolsId", userPoolWebClientId: "awsUserPoolsWebClientId", region: "region", identityPoolId: "awsCognitoIdentityPoolId", oauth } }; const spyon = jest.spyOn(Auth.prototype, 'currentAuthenticatedUser').mockImplementationOnce(() => { return Promise.reject('err'); }); const auth = new Auth(authOptions); expect(spyon).toBeCalled(); spyon.mockClear(); }); }); >>>>>>> describe('sendCustomChallengeAnswer', () => { test('happy case', async () => { const spyon = jest.spyOn(CognitoUser.prototype, 'sendCustomChallengeAnswer') .mockImplementationOnce((challengeResponses, callback) => { callback.onSuccess(session); }); const auth = new Auth(authOptions); const user = new CognitoUser({ Username: 'username', Pool: userPool }); const userAfterCustomChallengeAnswer = Object.assign( new CognitoUser({ Username: 'username', Pool: userPool }), { "challengeName": "CUSTOM_CHALLENGE", "challengeParam": "challengeParam" }); expect.assertions(1); expect(await auth.sendCustomChallengeAnswer(userAfterCustomChallengeAnswer, 'challengeResponse')).toEqual(user); spyon.mockClear(); }); test('customChallenge', async () => { const spyon = jest.spyOn(CognitoUser.prototype, 'sendCustomChallengeAnswer') .mockImplementationOnce((challengeResponses, callback) => { callback.customChallenge('challengeParam'); }); const auth = new Auth(authOptions); const user = new CognitoUser({ Username: 'username', Pool: userPool }); const userAfterCustomChallengeAnswer = Object.assign( new CognitoUser({ Username: 'username', Pool: userPool }), { "challengeName": "CUSTOM_CHALLENGE", "challengeParam": "challengeParam" }); expect.assertions(1); expect(await auth.sendCustomChallengeAnswer(userAfterCustomChallengeAnswer, 'challengeResponse')).toEqual(userAfterCustomChallengeAnswer); spyon.mockClear(); }); test('onFailure', async () => { const spyon = jest.spyOn(CognitoUser.prototype, 'sendCustomChallengeAnswer') .mockImplementationOnce((challengeResponses, callback) => { callback.onFailure('err'); }); const auth = new Auth(authOptions); const userAfterCustomChallengeAnswer = Object.assign( new CognitoUser({ Username: 'username', Pool: userPool }), { "challengeName": "CUSTOM_CHALLENGE", "challengeParam": "challengeParam" }); expect.assertions(1); try { await auth.sendCustomChallengeAnswer(userAfterCustomChallengeAnswer, 'challengeResponse'); } catch (e) { expect(e).toBe('err'); } spyon.mockClear(); }); test('no userPool', async () => { const spyon = jest.spyOn(CognitoUser.prototype, 'sendCustomChallengeAnswer'); // @ts-ignore const auth = new Auth(authOptionsWithNoUserPoolId); const userAfterCustomChallengeAnswer = Object.assign( new CognitoUser({ Username: 'username', Pool: userPool }), { "challengeName": "CUSTOM_CHALLENGE", "challengeParam": "challengeParam" }); expect.assertions(1); try { await auth.sendCustomChallengeAnswer(userAfterCustomChallengeAnswer, 'challengeResponse'); } catch (e) { expect(e).toBe('No userPool'); } spyon.mockClear(); }); }); describe('hosted ui test', () => { test('happy case', () => { const oauth = {}; const authOptions = { Auth: { userPoolId: "awsUserPoolsId", userPoolWebClientId: "awsUserPoolsWebClientId", region: "region", identityPoolId: "awsCognitoIdentityPoolId", oauth } }; const spyon = jest.spyOn(Auth.prototype, 'currentAuthenticatedUser').mockImplementationOnce(() => { return Promise.reject('err'); }); const auth = new Auth(authOptions); expect(spyon).toBeCalled(); spyon.mockClear(); }); });
<<<<<<< import { Component, Input } from '@angular/core'; import { AmplifyService, AuthState } from '../../../providers'; import { UsernameAttributes } from '../types'; import { countrylist, country } from '../../../assets/countries'; import { emailFieldTemplate, usernameFieldTemplate, phoneNumberFieldTemplate } from '../angular-templates'; ======= import { Component, Input, OnInit, Inject } from '@angular/core'; import { AmplifyService } from '../../../providers/amplify.service'; import { AuthState } from '../../../providers/auth.state'; >>>>>>> import { UsernameAttributes } from '../types'; import { countrylist, country } from '../../../assets/countries'; import { emailFieldTemplate, usernameFieldTemplate, phoneNumberFieldTemplate } from '../angular-templates'; import { Component, Input, OnInit, Inject } from '@angular/core'; import { AmplifyService } from '../../../providers/amplify.service'; import { AuthState } from '../../../providers/auth.state'; <<<<<<< <div class="amplify-form-header">{{ this.amplifyService.i18n().get('Reset your password') }}</div> <div class="amplify-form-text" *ngIf="!code_sent">{{ this.amplifyService.i18n().get('You will receive a verification code') }}</div> <div class="amplify-form-text" *ngIf="code_sent">{{ this.amplifyService.i18n().get('Enter the code you received and set a new password') }}</div> <div class="amplify-form-row" *ngIf="!code_sent"> <div *ngIf="this._usernameAttributes === 'email'">` + emailFieldTemplate + `</div> <div *ngIf="this._usernameAttributes === 'phone_number'">` + phoneNumberFieldTemplate + `</div> <div *ngIf="this._usernameAttributes !== 'email' && this._usernameAttributes !== 'phone_number'">` + usernameFieldTemplate + `</div> </div> ======= <div class="amplify-form-header"> {{ this.amplifyService.i18n().get('Reset your password') }} </div> <div class="amplify-form-text" *ngIf="!code_sent"> {{ this.amplifyService.i18n().get('You will receive a verification code') }} </div> <div class="amplify-form-text" *ngIf="code_sent"> {{ this.amplifyService.i18n().get('Enter the code you received and set a new password') }} </div> <div class="amplify-form-row" *ngIf="!code_sent"> <label class="amplify-input-label" for="usernameinput"> {{ this.amplifyService.i18n().get('Username *') }} </label> <input #usernameinput (keyup)="setUsername($event.target.value)" class="amplify-form-input" type="text" placeholder="{{ this.amplifyService.i18n().get('Username') }}" [value]="username" /> </div> >>>>>>> <div class="amplify-form-header"> {{ this.amplifyService.i18n().get('Reset your password') }} </div> <div class="amplify-form-text" *ngIf="!code_sent"> {{ this.amplifyService.i18n().get('You will receive a verification code') }} </div> <div class="amplify-form-text" *ngIf="code_sent"> {{ this.amplifyService.i18n().get('Enter the code you received and set a new password') }} </div> <div class="amplify-form-row" *ngIf="!code_sent"> <div *ngIf="this._usernameAttributes === 'email'">` + emailFieldTemplate + `</div> <div *ngIf="this._usernameAttributes === 'phone_number'">` + phoneNumberFieldTemplate + `</div> <div *ngIf="this._usernameAttributes !== 'email' && this._usernameAttributes !== 'phone_number'">` + usernameFieldTemplate + `</div> </div> <<<<<<< _usernameAttributes: string | Array<string> = []; ======= >>>>>>> _usernameAttributes: string | Array<string> = []; <<<<<<< this.username = authState.user? authState.user.username || '' : ''; this.email = authState.user? authState.user.email || '' : ''; this.country_code = authState.user? authState.user.country_code || '' : '1'; this.local_phone_number = authState.user? authState.user.local_phone_number || '' : ''; ======= this.username = (authState.user && authState.user.username) ? authState.user.username : ''; } ngOnInit() { if (!this.amplifyService.auth()){ throw new Error('Auth module not registered on AmplifyService provider'); } >>>>>>> this.email = (authState.user && authState.user.email)? authState.user.email : ''; this.country_code = (authState.user && authState.user.contry_code) ? authState.user.country_code : '1'; this.local_phone_number = (authState.user && authState.user.local_phone_number) ? authState.user.local_phone_number : ''; this.username = (authState.user && authState.user.username) ? authState.user.username : ''; } ngOnInit() { if (!this.amplifyService.auth()){ throw new Error('Auth module not registered on AmplifyService provider'); }
<<<<<<< <div class="amplify-form-container" *ngIf="_show"> <div class="amplify-form-body"> <div class="amplify-form-row" *ngIf="!shouldHide('SignIn')"> <div class="amplify-form-cell-left"> <a class="amplify-form-link" (click)="onSignIn()" >Back to Sign In</a> ======= <div class="amplify-container" *ngIf="_show"> <div class="amplify-form-container"> <div class="amplify-form-body"> <div class="amplify-form-header">Confirm Sign in</div> <div class="amplify-form-row"> <label class="amplify-input-label" for="code"> Confirmation Code *</label> <input #code (change)="setCode(code.value)" (keyup)="setCode(code.value)" (keyup.enter)="onConfirm()" class="amplify-form-input" type="text" placeholder="Enter your Code" /> </div> <div class="amplify-form-actions"> <div class="amplify-form-cell-left"> <div class="amplify-form-actions-left"> <a class="amplify-form-link" (click)="onSignIn()">Back to Sign in</a> </div> </div> <div class="amplify-form-cell-right"> <button class="amplify-form-button" (click)="onConfirm()">Confirm</button> </div> </div> >>>>>>> <div class="amplify-container" *ngIf="_show"> <div class="amplify-form-container"> <div class="amplify-form-body"> <div class="amplify-form-header">Confirm Sign in</div> <div class="amplify-form-row" *ngIf="!shouldHide('SignIn')"> <label class="amplify-input-label" for="code"> Confirmation Code *</label> <input #code (change)="setCode(code.value)" (keyup)="setCode(code.value)" (keyup.enter)="onConfirm()" class="amplify-form-input" type="text" placeholder="Enter your Code" /> </div> <div class="amplify-form-actions"> <div class="amplify-form-cell-left"> <div class="amplify-form-actions-left"> <a class="amplify-form-link" (click)="onSignIn()">Back to Sign in</a> </div> </div> <div class="amplify-form-cell-right"> <button class="amplify-form-button" (click)="onConfirm()">Confirm</button> </div> </div>
<<<<<<< // for backward compatibility if (!this._config['AWSPinpoint']) { this._config['AWSPinpoint'] = Object.assign({}, this._config); } ======= >>>>>>>
<<<<<<< <amplify-auth-sign-in-ionic *ngIf="!shouldHide('SignIn')" [authState]="authState" ></amplify-auth-sign-in-ionic> <amplify-auth-sign-up-ionic *ngIf="!shouldHide('SignUp')" [authState]="authState" [signUpConfig]="_signUpConfig" ></amplify-auth-sign-up-ionic> <amplify-auth-confirm-sign-up-ionic *ngIf="!shouldHide('ConfirmSignUp')" [authState]="authState" ></amplify-auth-confirm-sign-up-ionic> <amplify-auth-confirm-sign-in-ionic *ngIf="!shouldHide('ConfirmSignIn')" [authState]="authState" ></amplify-auth-confirm-sign-in-ionic> <amplify-auth-forgot-password-ionic *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" ></amplify-auth-forgot-password-ionic> <amplify-auth-greetings-ionic *ngIf="!shouldHide('Greetings')" [authState]="authState" ></amplify-auth-greetings-ionic> <amplify-auth-require-new-password-ionic *ngIf="!shouldHide('RequireNewPassword')" [authState]="authState" ></amplify-auth-require-new-password-ionic> </div> `; ======= <div> <amplify-auth-sign-in-ionic [authState]="authState"></amplify-auth-sign-in-ionic> </div> <div> <amplify-auth-sign-up-ionic *ngIf="!shouldHide('SignUp')" [authState]="authState" [hide]="hide" ></amplify-auth-sign-up-ionic> </div> <div> <amplify-auth-confirm-sign-up-ionic *ngIf="!shouldHide('ConfirmSignUp')" [authState]="authState" [hide]="hide" ></amplify-auth-confirm-sign-up-ionic> </div> <div> <amplify-auth-confirm-sign-in-ionic *ngIf="!shouldHide('ConfirmSignIn')" [authState]="authState" [hide]="hide" ></amplify-auth-confirm-sign-in-ionic> </div> <div> <amplify-auth-forgot-password-ionic *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" [hide]="hide" ></amplify-auth-forgot-password-ionic> </div> <div> <amplify-auth-greetings-ionic *ngIf="!shouldHide('Greetings') && authState.state === 'signedIn'" [authState]="authState" ></amplify-auth-greetings-ionic> </div> <div> <amplify-auth-require-new-password-ionic *ngIf="!shouldHide('RequireNewPassword')" [authState]="authState" [hide]="hide" ></amplify-auth-require-new-password-ionic> </div> ` >>>>>>> <amplify-auth-sign-in-ionic *ngIf="!shouldHide('SignIn')" [authState]="authState" ></amplify-auth-sign-in-ionic> <amplify-auth-sign-up-ionic *ngIf="!shouldHide('SignUp')" [authState]="authState" [signUpConfig]="_signUpConfig" [hide]="hide" ></amplify-auth-sign-up-ionic> <amplify-auth-confirm-sign-up-ionic *ngIf="!shouldHide('ConfirmSignUp')" [authState]="authState" [hide]="hide" ></amplify-auth-confirm-sign-up-ionic> <amplify-auth-confirm-sign-in-ionic *ngIf="!shouldHide('ConfirmSignIn')" [authState]="authState" [hide]="hide" ></amplify-auth-confirm-sign-in-ionic> <amplify-auth-forgot-password-ionic *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" [hide]="hide" ></amplify-auth-forgot-password-ionic> <amplify-auth-greetings-ionic *ngIf="!shouldHide('Greetings')" [authState]="authState" ></amplify-auth-greetings-ionic> <amplify-auth-require-new-password-ionic *ngIf="!shouldHide('RequireNewPassword')" [authState]="authState" [hide]="hide" ></amplify-auth-require-new-password-ionic> </div> `;
<<<<<<< }, userTimeoutReached: { code: "user_timeout_reached", desc: "User defined timeout for device code polling reached", ======= }, tokenClaimsRequired: { code: "token_claims_cnf_required_for_signedjwt", desc: "Cannot generate a POP jwt if the token_claims are not populated" }, noAuthorizationCodeFromServer: { code: "authorization_code_missing_from_server_response", desc: "Srver response does not contain an authorization code to proceed" >>>>>>> }, userTimeoutReached: { code: "user_timeout_reached", desc: "User defined timeout for device code polling reached", }, tokenClaimsRequired: { code: "token_claims_cnf_required_for_signedjwt", desc: "Cannot generate a POP jwt if the token_claims are not populated" }, noAuthorizationCodeFromServer: { code: "authorization_code_missing_from_server_response", desc: "Srver response does not contain an authorization code to proceed" <<<<<<< /** * Throws error if the user defined timeout is reached. */ static createUserTimeoutReachedError(): ClientAuthError { return new ClientAuthError(ClientAuthErrorMessage.userTimeoutReached.code, ClientAuthErrorMessage.userTimeoutReached.desc); } ======= /** * Throws error if token claims are not populated for a signed jwt generation */ static createTokenClaimsRequiredError(): ClientAuthError { return new ClientAuthError(ClientAuthErrorMessage.tokenClaimsRequired.code, ClientAuthErrorMessage.tokenClaimsRequired.desc); } /** * Throws error when the authorization code is missing from the server response */ static createNoAuthCodeInServerResponseError(): ClientAuthError { return new ClientAuthError(ClientAuthErrorMessage.noAuthorizationCodeFromServer.code, ClientAuthErrorMessage.noAuthorizationCodeFromServer.desc); } >>>>>>> /** * Throws error if the user defined timeout is reached. */ static createUserTimeoutReachedError(): ClientAuthError { return new ClientAuthError(ClientAuthErrorMessage.userTimeoutReached.code, ClientAuthErrorMessage.userTimeoutReached.desc); } /* * Throws error if token claims are not populated for a signed jwt generation */ static createTokenClaimsRequiredError(): ClientAuthError { return new ClientAuthError(ClientAuthErrorMessage.tokenClaimsRequired.code, ClientAuthErrorMessage.tokenClaimsRequired.desc); } /** * Throws error when the authorization code is missing from the server response */ static createNoAuthCodeInServerResponseError(): ClientAuthError { return new ClientAuthError(ClientAuthErrorMessage.noAuthorizationCodeFromServer.code, ClientAuthErrorMessage.noAuthorizationCodeFromServer.desc); }
<<<<<<< CognitoUser.prototype.getUsername = () => { return 'username'; } ======= CognitoUser.prototype.getUserData = (callback) => { callback(null, 'data'); } >>>>>>> CognitoUser.prototype.getUsername = () => { return 'username'; } CognitoUser.prototype.getUserData = (callback) => { callback(null, 'data'); }
<<<<<<< // Auth if (config['aws_cognito_identity_pool_id'] || config['aws_user_pools_id']) { amplifyConfig.Auth = { userPoolId: config['aws_user_pools_id'], userPoolWebClientId: config['aws_user_pools_web_client_id'], region: config['aws_cognito_region'], identityPoolId: config['aws_cognito_identity_pool_id'], mandatorySignIn: config['aws_mandatory_sign_in'] === 'enable', }; } ======= // Auth if (config['aws_cognito_identity_pool_id'] || config['aws_user_pools_id']) { const Auth = { userPoolId: config['aws_user_pools_id'], userPoolWebClientId: config['aws_user_pools_web_client_id'], region: config['aws_cognito_region'], identityPoolId: config['aws_cognito_identity_pool_id'], identityPoolRegion: config['aws_cognito_region'], mandatorySignIn: config['aws_mandatory_sign_in'] === 'enable' ? true : false, }; amplifyConfig.Auth = Auth; } >>>>>>> // Auth if (config['aws_cognito_identity_pool_id'] || config['aws_user_pools_id']) { amplifyConfig.Auth = { userPoolId: config['aws_user_pools_id'], userPoolWebClientId: config['aws_user_pools_web_client_id'], region: config['aws_cognito_region'], identityPoolId: config['aws_cognito_identity_pool_id'], identityPoolRegion: config['aws_cognito_region'], mandatorySignIn: config['aws_mandatory_sign_in'] === 'enable', }; }
<<<<<<< [usernameAttributes]="_usernameAttributes" ======= [hide]="hide" >>>>>>> [usernameAttributes]="_usernameAttributes" [hide]="hide" <<<<<<< [usernameAttributes]="_usernameAttributes" ======= [hide]="hide" >>>>>>> [usernameAttributes]="_usernameAttributes" [hide]="hide" <<<<<<< [usernameAttributes]="_usernameAttributes" ======= [hide]="hide" >>>>>>> [usernameAttributes]="_usernameAttributes" [hide]="hide" <<<<<<< *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" [usernameAttributes]="_usernameAttributes" ======= *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" [hide]="hide" >>>>>>> *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" [usernameAttributes]="_usernameAttributes" [hide]="hide"
<<<<<<< import { appendToUserAgent } from '@aws-sdk/util-user-agent-browser'; const BASE_USER_AGENT = `aws-amplify/${version}`; ======= >>>>>>> const BASE_USER_AGENT = `aws-amplify/${version}`;
<<<<<<< <div> <amplify-auth-sign-in-ionic [authState]="authState"></amplify-auth-sign-in-ionic> </div> <div> <amplify-auth-sign-up-ionic *ngIf="!shouldHide('SignUp')" [authState]="authState" [hide]="hide" ></amplify-auth-sign-up-ionic> </div> <div> <amplify-auth-confirm-sign-up-ionic *ngIf="!shouldHide('ConfirmSignUp')" [authState]="authState" [hide]="hide" ></amplify-auth-confirm-sign-up-ionic> </div> <div> <amplify-auth-confirm-sign-in-ionic *ngIf="!shouldHide('ConfirmSignIn')" [authState]="authState" [hide]="hide" ></amplify-auth-confirm-sign-in-ionic> </div> <div> <amplify-auth-forgot-password-ionic *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" [hide]="hide" ></amplify-auth-forgot-password-ionic> </div> <div> <amplify-auth-greetings-ionic *ngIf="!shouldHide('Greetings')" [authState]="authState" ></amplify-auth-greetings-ionic> </div> <div> <amplify-auth-require-new-password-ionic *ngIf="!shouldHide('RequireNewPassword')" [authState]="authState" [hide]="hide" ></amplify-auth-require-new-password-ionic> </div> ` ======= <amplify-auth-sign-in-ionic *ngIf="!shouldHide('SignIn')" [authState]="authState" ></amplify-auth-sign-in-ionic> <amplify-auth-sign-up-ionic *ngIf="!shouldHide('SignUp')" [authState]="authState" ></amplify-auth-sign-up-ionic> <amplify-auth-confirm-sign-up-ionic *ngIf="!shouldHide('ConfirmSignUp')" [authState]="authState" ></amplify-auth-confirm-sign-up-ionic> <amplify-auth-confirm-sign-in-ionic *ngIf="!shouldHide('ConfirmSignIn')" [authState]="authState" ></amplify-auth-confirm-sign-in-ionic> <amplify-auth-forgot-password-ionic *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" ></amplify-auth-forgot-password-ionic> <amplify-auth-greetings-ionic *ngIf="!shouldHide('Greetings') && authState.state === 'signedIn'" [authState]="authState" ></amplify-auth-greetings-ionic> <amplify-auth-require-new-password-ionic *ngIf="!shouldHide('RequireNewPassword')" [authState]="authState" ></amplify-auth-require-new-password-ionic> </div> `; >>>>>>> <div> <amplify-auth-sign-in-ionic [authState]="authState"></amplify-auth-sign-in-ionic> </div> <div> <amplify-auth-sign-up-ionic *ngIf="!shouldHide('SignUp')" [authState]="authState" [hide]="hide" ></amplify-auth-sign-up-ionic> </div> <div> <amplify-auth-confirm-sign-up-ionic *ngIf="!shouldHide('ConfirmSignUp')" [authState]="authState" [hide]="hide" ></amplify-auth-confirm-sign-up-ionic> </div> <div> <amplify-auth-confirm-sign-in-ionic *ngIf="!shouldHide('ConfirmSignIn')" [authState]="authState" [hide]="hide" ></amplify-auth-confirm-sign-in-ionic> </div> <div> <amplify-auth-forgot-password-ionic *ngIf="!shouldHide('ForgotPassword')" [authState]="authState" [hide]="hide" ></amplify-auth-forgot-password-ionic> </div> <div> <amplify-auth-greetings-ionic *ngIf="!shouldHide('Greetings') && authState.state === 'signedIn'" [authState]="authState" ></amplify-auth-greetings-ionic> </div> <div> <amplify-auth-require-new-password-ionic *ngIf="!shouldHide('RequireNewPassword')" [authState]="authState" [hide]="hide" ></amplify-auth-require-new-password-ionic> </div> `
<<<<<<< const { userPoolId, userPoolWebClientId, cookieStorage, oauth, region, identityPoolId, mandatorySignIn } = this._config; ======= const { userPoolId, userPoolWebClientId, cookieStorage, oauth, refreshHandlers } = this._config; >>>>>>> const { userPoolId, userPoolWebClientId, cookieStorage, oauth, region, identityPoolId, mandatorySignIn, refreshHandlers } = this._config; <<<<<<< Credentials.set({ provider, token, user, expires_at }, 'federation').then((cred) => { ======= that._setCredentialsFromFederation({ provider, token, identity_id, user, expires_at }).then((cred) => { >>>>>>> Credentials.set({ provider, token, identity_id, user, expires_at }, 'federation').then((cred) => { <<<<<<< ======= private pickupCredentials() { logger.debug('picking up credentials'); if (!this._gettingCredPromise || !this._gettingCredPromise.isPending()) { logger.debug('getting new cred promise'); if (AWS.config && AWS.config.credentials && AWS.config.credentials instanceof Credentials) { this._gettingCredPromise = JS.makeQuerablePromise(this._setCredentialsFromAWS()); } else { this._gettingCredPromise = JS.makeQuerablePromise(this.keepAlive()); } } else { logger.debug('getting old cred promise'); } return this._gettingCredPromise; } private _setCredentialsFromAWS() { const credentials = AWS.config.credentials; logger.debug('setting credentials from aws'); const that = this; if (credentials instanceof Credentials){ return this._loadCredentials(credentials, 'aws', undefined, null); } else { logger.debug('AWS.config.credentials is not an instance of AWS Credentials'); return Promise.reject('AWS.config.credentials is not an instance of AWS Credentials'); } } private _setCredentialsForGuest() { logger.debug('setting credentials for guest'); const { identityPoolId, region, mandatorySignIn } = this._config; if (mandatorySignIn) { return Promise.reject('cannot get guest credentials when mandatory signin enabled'); } const credentials = new CognitoIdentityCredentials( { IdentityPoolId: identityPoolId }, { region }); const that = this; return this._loadCredentials(credentials, 'guest', false, null); } private _setCredentialsFromSession(session) { logger.debug('set credentials from session'); const idToken = session.getIdToken().getJwtToken(); const { region, userPoolId, identityPoolId } = this._config; const key = 'cognito-idp.' + region + '.amazonaws.com/' + userPoolId; const logins = {}; logins[key] = idToken; const credentials = new CognitoIdentityCredentials( { IdentityPoolId: identityPoolId, Logins: logins }, { region }); const that = this; return this._loadCredentials(credentials, 'userPool', true, null); } private _setCredentialsFromFederation(params) { const { provider, token, identity_id, user, expires_at } = params; const domains = { 'google': 'accounts.google.com', 'facebook': 'graph.facebook.com', 'amazon': 'www.amazon.com', 'developer': 'cognito-identity.amazonaws.com' }; // Use custom provider url instead of the predefined ones const domain = domains[provider] || provider; if (!domain) { return Promise.reject('You must specify a federated provider'); } const logins = {}; logins[domain] = token; const { identityPoolId, region } = this._config; const credentials = new AWS.CognitoIdentityCredentials( { IdentityPoolId: identityPoolId, IdentityId: identity_id, Logins: logins }, { region }); Cache.setItem('federatedInfo', { provider, token, identity_id, user, expires_at }, { priority: 1 }); return this._loadCredentials(credentials, 'federated', true, user); } private _loadCredentials(credentials, source, authenticated, rawUser) { const that = this; return new Promise((res, rej) => { credentials.getPromise().then( () => { logger.debug('Load credentials successfully', credentials); that.credentials = credentials; that.credentials.authenticated = authenticated; that.credentials_source = source; if (source === 'federated') { that.user = Object.assign( { id: this.credentials.identityId }, rawUser ); Cache.setItem('federatedUser', that.user, { priority: 1 }); } res(that.credentials); }, (err) => { logger.debug('Failed to load credentials', credentials); rej(err); } ); }); } private keepAlive() { logger.debug('checking if credentials exists and not expired'); const cred = this.credentials; if (cred && !this._isExpired(cred)) { logger.debug('credentials not changed and not expired, directly return'); return Promise.resolve(cred); } logger.debug('need to get a new credential or refresh the existing one'); return this.currentUserCredentials(); } >>>>>>>
<<<<<<< import {OracleDriver} from "../driver/oracle/OracleDriver"; ======= import {EntitySchema} from "../"; >>>>>>> import {EntitySchema} from "../"; import {OracleDriver} from "../driver/oracle/OracleDriver";
<<<<<<< import {Constants, SSOTypes} from "./Constants"; import { AuthenticationParameters, QPDict } from "./AuthenticationParameters"; ======= import {Constants, SSOTypes, PromptState} from "./Constants"; import { AuthenticationParameters } from "./AuthenticationParameters"; >>>>>>> import {Constants, SSOTypes, PromptState} from "./Constants"; import { AuthenticationParameters } from "./AuthenticationParameters"; <<<<<<< ======= //#region Token Processing (Extract to TokenProcessing.ts) /** * decode a JWT * * @param jwtToken */ static decodeJwt(jwtToken: string): any { if (this.isEmpty(jwtToken)) { return null; } const idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; const matches = idTokenPartsRegex.exec(jwtToken); if (!matches || matches.length < 4) { //this._requestContext.logger.warn("The returned id_token is not parseable."); return null; } const crackedToken = { header: matches[1], JWSPayload: matches[2], JWSSig: matches[3] }; return crackedToken; } /** * Extract IdToken by decoding the RAWIdToken * * @param encodedIdToken */ static extractIdToken(encodedIdToken: string): any { // id token will be decoded to get the username const decodedToken = this.decodeJwt(encodedIdToken); if (!decodedToken) { return null; } try { const base64IdToken = decodedToken.JWSPayload; const base64Decoded = this.base64Decode(base64IdToken); if (!base64Decoded) { //this._requestContext.logger.info("The returned id_token could not be base64 url safe decoded."); return null; } // ECMA script has JSON built-in support return JSON.parse(base64Decoded); } catch (err) { //this._requestContext.logger.error("The returned id_token could not be decoded" + err); } return null; } //#endregion >>>>>>> <<<<<<< ======= //#region Scopes (extract to Scopes.ts) /** * Check if there are dup scopes in a given request * * @param cachedScopes * @param scopes */ // TODO: Rename this, intersecting scopes isn't a great name for duplicate checker static isIntersectingScopes(cachedScopes: Array<string>, scopes: Array<string>): boolean { cachedScopes = this.convertToLowerCase(cachedScopes); for (let i = 0; i < scopes.length; i++) { if (cachedScopes.indexOf(scopes[i].toLowerCase()) > -1) { return true; } } return false; } /** * Check if a given scope is present in the request * * @param cachedScopes * @param scopes */ static containsScope(cachedScopes: Array<string>, scopes: Array<string>): boolean { cachedScopes = this.convertToLowerCase(cachedScopes); return scopes.every((value: any): boolean => cachedScopes.indexOf(value.toString().toLowerCase()) >= 0); } /** * toLower * * @param scopes */ // TODO: Rename this, too generic name for a function that only deals with scopes static convertToLowerCase(scopes: Array<string>): Array<string> { return scopes.map(scope => scope.toLowerCase()); } /** * remove one element from a scope array * * @param scopes * @param scope */ // TODO: Rename this, too generic name for a function that only deals with scopes static removeElement(scopes: Array<string>, scope: string): Array<string> { return scopes.filter(value => value !== scope); } //#endregion //#region URL Processing (Extract to UrlProcessing.ts?) static getDefaultRedirectUri(): string { return window.location.href.split("?")[0].split("#")[0]; } /** * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d * @param href The url * @param tenantId The tenant id to replace */ static replaceTenantPath(url: string, tenantId: string): string { url = url.toLowerCase(); var urlObject = this.GetUrlComponents(url); var pathArray = urlObject.PathSegments; if (tenantId && (pathArray.length !== 0 && (pathArray[0] === Constants.common || pathArray[0] === SSOTypes.ORGANIZATIONS))) { pathArray[0] = tenantId; } return this.constructAuthorityUriFromObject(urlObject, pathArray); } static constructAuthorityUriFromObject(urlObject: IUri, pathArray: string[]) { return this.CanonicalizeUri(urlObject.Protocol + "//" + urlObject.HostNameAndPort + "/" + pathArray.join("/")); } /** * Parses out the components from a url string. * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url. */ static GetUrlComponents(url: string): IUri { if (!url) { throw "Url required"; } // https://gist.github.com/curtisz/11139b2cfcaef4a261e0 var regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"); var match = url.match(regEx); if (!match || match.length < 6) { throw "Valid url required"; } let urlComponents = <IUri>{ Protocol: match[1], HostNameAndPort: match[4], AbsolutePath: match[5] }; let pathSegments = urlComponents.AbsolutePath.split("/"); pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements urlComponents.PathSegments = pathSegments; return urlComponents; } /** * Given a url or path, append a trailing slash if one doesnt exist * * @param url */ static CanonicalizeUri(url: string): string { if (url) { url = url.toLowerCase(); } if (url && !Utils.endsWith(url, "/")) { url += "/"; } return url; } /** * Checks to see if the url ends with the suffix * Required because we are compiling for es5 instead of es6 * @param url * @param str */ // TODO: Rename this, not clear what it is supposed to do static endsWith(url: string, suffix: string): boolean { if (!url || !suffix) { return false; } return url.indexOf(suffix, url.length - suffix.length) !== -1; } /** * Utils function to remove the login_hint and domain_hint from the i/p extraQueryParameters * @param url * @param name */ static urlRemoveQueryStringParameter(url: string, name: string): string { if (this.isEmpty(url)) { return url; } var regex = new RegExp("(\\&" + name + "=)[^\&]+"); url = url.replace(regex, ""); // name=value& regex = new RegExp("(" + name + "=)[^\&]+&"); url = url.replace(regex, ""); // name=value regex = new RegExp("(" + name + "=)[^\&]+"); url = url.replace(regex, ""); return url; } /** * @hidden * @ignore * * Returns the anchor part(#) of the URL */ static getHashFromUrl(urlStringOrFragment: string): string { const index = urlStringOrFragment.indexOf("#"); const indexWithSlash = urlStringOrFragment.indexOf("#/"); if (indexWithSlash > -1) { return urlStringOrFragment.substring(indexWithSlash + 2); } if (index > -1) { return urlStringOrFragment.substring(index + 1); } return urlStringOrFragment; } //#endregion >>>>>>> <<<<<<< ======= //#region Response Helpers static setResponseIdToken(originalResponse: AuthResponse, idTokenObj: IdToken) : AuthResponse { let exp = Number(idTokenObj.expiration); if (exp && !originalResponse.expiresOn) { originalResponse.expiresOn = new Date(exp * 1000); } return { ...originalResponse, idToken: idTokenObj, idTokenClaims: idTokenObj.claims, uniqueId: idTokenObj.objectId || idTokenObj.subject, tenantId: idTokenObj.tenantId, }; } //#endregion >>>>>>>
<<<<<<< import {EntityManager} from "../../entity-manager/EntityManager"; ======= import {OrmUtils} from "../../util/OrmUtils"; import {InsertResult} from "../InsertResult"; >>>>>>> import {OrmUtils} from "../../util/OrmUtils"; <<<<<<< import {Broadcaster} from "../../subscriber/Broadcaster"; ======= import {TableIndexOptions} from "../../schema-builder/options/TableIndexOptions"; import {TableUnique} from "../../schema-builder/table/TableUnique"; import {BaseQueryRunner} from "../../query-runner/BaseQueryRunner"; >>>>>>> import {TableIndexOptions} from "../../schema-builder/options/TableIndexOptions"; import {TableUnique} from "../../schema-builder/table/TableUnique"; import {BaseQueryRunner} from "../../query-runner/BaseQueryRunner"; import {Broadcaster} from "../../subscriber/Broadcaster"; <<<<<<< /** * Connection used by this query runner. */ connection: Connection; /** * Broadcaster used on this query runner to broadcast entity events. */ broadcaster: Broadcaster; /** * Isolated entity manager working only with current query runner. */ manager: EntityManager; /** * Indicates if connection for this query runner is released. * Once its released, query runner cannot run queries anymore. */ isReleased = false; /** * Indicates if transaction is in progress. */ isTransactionActive = false; /** * Stores temporarily user data. * Useful for sharing data with subscribers. */ data = {}; ======= >>>>>>> /** * Broadcaster used on this query runner to broadcast entity events. */ broadcaster: Broadcaster; <<<<<<< ======= * Insert a new row with given values into the given table. * Returns value of the generated column if given and generate column exist in the table. */ async insert(tableName: string, keyValues: ObjectLiteral): Promise<InsertResult> { const keys = Object.keys(keyValues); const columns = keys.map(key => `\`${key}\``).join(", "); const values = keys.map(key => "?").join(","); const parameters = keys.map(key => keyValues[key]); const generatedColumns = this.connection.hasMetadata(tableName) ? this.connection.getMetadata(tableName).generatedColumns : []; const sql = `INSERT INTO ${this.escapeTableName(tableName)}(${columns}) VALUES (${values})`; const result = await this.query(sql, parameters); const generatedMap = generatedColumns.reduce((map, generatedColumn) => { const value = generatedColumn.isPrimary && result.insertId ? result.insertId : keyValues[generatedColumn.databaseName]; if (!value) return map; return OrmUtils.mergeDeep(map, generatedColumn.createValueMap(value)); }, {} as ObjectLiteral); return { result: result, generatedMap: Object.keys(generatedMap).length > 0 ? generatedMap : undefined }; } /** * Updates rows that match given conditions in the given table. */ async update(tableName: string, valuesMap: ObjectLiteral, conditions: ObjectLiteral): Promise<void> { const updateValues = this.parametrize(valuesMap).join(", "); const conditionString = this.parametrize(conditions).join(" AND "); const sql = `UPDATE ${this.escapeTableName(tableName)} SET ${updateValues} ${conditionString ? (" WHERE " + conditionString) : ""}`; const conditionParams = Object.keys(conditions).map(key => conditions[key]); const updateParams = Object.keys(valuesMap).map(key => valuesMap[key]); const allParameters = updateParams.concat(conditionParams); await this.query(sql, allParameters); } /** * Deletes from the given table by a given conditions. */ async delete(tableName: string, conditions: ObjectLiteral|string, maybeParameters?: any[]): Promise<void> { const conditionString = typeof conditions === "string" ? conditions : this.parametrize(conditions).join(" AND "); const parameters = conditions instanceof Object ? Object.keys(conditions).map(key => (conditions as ObjectLiteral)[key]) : maybeParameters; const sql = `DELETE FROM ${this.escapeTableName(tableName)} WHERE ${conditionString}`; await this.query(sql, parameters); } /** >>>>>>>
<<<<<<< const column = this.expressionMap.aliasNamePrefixingEnabled ? this.expressionMap.mainAlias!.name + "." + metadata.discriminatorColumn.databaseName : metadata.discriminatorColumn.databaseName; const condition = `${this.replacePropertyNames(column)} IN (:discriminatorColumnValues)`; ======= const condition = `${this.replacePropertyNames(this.expressionMap.mainAlias!.name + "." + metadata.discriminatorColumn.databaseName)} IN (:...discriminatorColumnValues)`; >>>>>>> const column = this.expressionMap.aliasNamePrefixingEnabled ? this.expressionMap.mainAlias!.name + "." + metadata.discriminatorColumn.databaseName : metadata.discriminatorColumn.databaseName; const condition = `${this.replacePropertyNames(column)} IN (:...discriminatorColumnValues)`;
<<<<<<< import {UniqueMetadata} from "./UniqueMetadata"; ======= import {TreeType} from "./types/TreeTypes"; import {TreeMetadataArgs} from "../metadata-args/TreeMetadataArgs"; >>>>>>> import {TreeType} from "./types/TreeTypes"; import {TreeMetadataArgs} from "../metadata-args/TreeMetadataArgs"; import {UniqueMetadata} from "./UniqueMetadata";
<<<<<<< if (alias.metadata.discriminatorColumn) { const discriminatorValues = rawResults.map(result => result[this.buildColumnAlias(alias.name, alias.metadata.discriminatorColumn!.databaseName)]); const metadata = alias.metadata.childEntityMetadatas.find(childEntityMetadata => { ======= if (metadata.discriminatorColumn) { const discriminatorValues = rawResults.map(result => result[alias.name + "_" + alias.metadata.discriminatorColumn!.databaseName]); const discriminatorMetadata = metadata.childEntityMetadatas.find(childEntityMetadata => { >>>>>>> if (metadata.discriminatorColumn) { const discriminatorValues = rawResults.map(result => result[this.buildColumnAlias(alias.name, alias.metadata.discriminatorColumn!.databaseName)]); const discriminatorMetadata = metadata.childEntityMetadatas.find(childEntityMetadata => { <<<<<<< const value = rawResults[0][this.buildColumnAlias(alias.name, column.databaseName)]; ======= // if table inheritance is used make sure this column is not child's column if (metadata.childEntityMetadatas.length > 0 && metadata.childEntityMetadatas.map(metadata => metadata.target).indexOf(column.target) !== -1) return; const value = rawResults[0][alias.name + "_" + column.databaseName]; >>>>>>> // if table inheritance is used make sure this column is not child's column if (metadata.childEntityMetadatas.length > 0 && metadata.childEntityMetadatas.map(metadata => metadata.target).indexOf(column.target) !== -1) return; const value = rawResults[0][this.buildColumnAlias(alias.name, column.databaseName)]; <<<<<<< if (alias.metadata.parentEntityMetadata) { alias.metadata.parentEntityMetadata.columns.forEach(column => { const value = rawResults[0]["parentIdColumn_" + this.buildColumnAlias(alias.metadata.parentEntityMetadata.tableName, column.databaseName)]; ======= if (metadata.parentEntityMetadata) { // todo: revisit metadata.parentEntityMetadata.columns.forEach(column => { const value = rawResults[0]["parentIdColumn_" + metadata.parentEntityMetadata.tableName + "_" + column.databaseName]; >>>>>>> if (metadata.parentEntityMetadata) { // todo: revisit metadata.parentEntityMetadata.columns.forEach(column => { const value = rawResults[0]["parentIdColumn_" + this.buildColumnAlias(metadata.parentEntityMetadata.tableName, column.databaseName)]; <<<<<<< if (alias.metadata.discriminatorColumn) discriminatorValue = rawResults[0][this.buildColumnAlias(alias.name, alias.metadata.discriminatorColumn!.databaseName)]; ======= // let discriminatorValue: string = ""; // if (metadata.discriminatorColumn) // discriminatorValue = rawResults[0][alias.name + "_" + metadata.discriminatorColumn!.databaseName]; >>>>>>> // let discriminatorValue: string = ""; // if (metadata.discriminatorColumn) // discriminatorValue = rawResults[0][this.buildColumnAlias(alias.name, alias.metadata.discriminatorColumn!.databaseName)];
<<<<<<< import {ColumnOptions} from "../decorator/options/ColumnOptions"; import {ForeignKeyMetadata} from "../metadata/ForeignKeyMetadata"; import {LazyRelationsWrapper} from "../lazy-loading/LazyRelationsWrapper"; import {UniqueMetadata} from "../metadata/UniqueMetadata"; ======= >>>>>>> import {UniqueMetadata} from "../metadata/UniqueMetadata"; <<<<<<< // build all unique constraints (need to do it after relations and their join columns are built) entityMetadatas.forEach(entityMetadata => { entityMetadata.uniques.forEach(unique => unique.build(this.connection.namingStrategy)); }); entityMetadatas .filter(metadata => !!metadata.parentEntityMetadata && metadata.tableType === "class-table-child") .forEach(metadata => { const parentPrimaryColumns = metadata.parentEntityMetadata.primaryColumns; const parentRelationColumns = parentPrimaryColumns.map(parentPrimaryColumn => { const columnName = this.connection.namingStrategy.classTableInheritanceParentColumnName(metadata.parentEntityMetadata.tableName, parentPrimaryColumn.propertyPath); const column = new ColumnMetadata({ connection: this.connection, entityMetadata: metadata, referencedColumn: parentPrimaryColumn, args: { target: metadata.target, propertyName: columnName, mode: "parentId", options: <ColumnOptions> { name: columnName, type: parentPrimaryColumn.type, unique: false, nullable: false, primary: true } } }); metadata.registerColumn(column); column.build(this.connection); return column; }); metadata.foreignKeys = [ new ForeignKeyMetadata({ entityMetadata: metadata, referencedEntityMetadata: metadata.parentEntityMetadata, namingStrategy: this.connection.namingStrategy, columns: parentRelationColumns, referencedColumns: parentPrimaryColumns, onDelete: "CASCADE" }) ]; }); ======= >>>>>>> // build all unique constraints (need to do it after relations and their join columns are built) entityMetadatas.forEach(entityMetadata => { entityMetadata.uniques.forEach(unique => unique.build(this.connection.namingStrategy)); });
<<<<<<< import {Broadcaster} from "../subscriber/Broadcaster"; ======= import {SqlInMemory} from "../driver/SqlInMemory"; import {TableUnique} from "../schema-builder/table/TableUnique"; >>>>>>> import {SqlInMemory} from "../driver/SqlInMemory"; import {TableUnique} from "../schema-builder/table/TableUnique"; import {Broadcaster} from "../subscriber/Broadcaster"; <<<<<<< * Broadcaster used on this query runner to broadcast entity events. */ readonly broadcaster: Broadcaster; /** * Isolated entity manager working only with current query runner. ======= * Isolated entity manager working only with this query runner. >>>>>>> * Broadcaster used on this query runner to broadcast entity events. */ readonly broadcaster: Broadcaster; /** * Isolated entity manager working only with this query runner. <<<<<<< * Inserts new values into closure table. ======= * Insert a new row with given values into the given table. * Returns value of the generated column if given and generate column exist in the table. * * @deprecated todo: remove later use query builder instead */ insert(tablePath: string, valuesMap: Object): Promise<InsertResult>; /** * Updates rows that match given simple conditions in the given table. * * @deprecated todo: remove later use query builder instead */ update(tablePath: string, valuesMap: Object, conditions: Object): Promise<void>; /** * Performs a simple DELETE query by a given conditions in a given table. * * @deprecated todo: remove later use query builder instead */ delete(tablePath: string, condition: Object|string, parameters?: any[]): Promise<void>; /** * Inserts new values into closure table. * * @deprecated todo: move to ClosureQueryBuilder */ insertIntoClosureTable(tablePath: string, newEntityId: any, parentId: any, hasLevel: boolean): Promise<number>; /** * Returns all available database names including system databases. >>>>>>> * Inserts new values into closure table. * * @deprecated todo: move to ClosureQueryBuilder */ insertIntoClosureTable(tablePath: string, newEntityId: any, parentId: any, hasLevel: boolean): Promise<number>; /** * Returns all available database names including system databases.
<<<<<<< await Promise.all(entities.map(async (entity, entityIndex) => { if (this.queryRunner.connection.driver instanceof OracleDriver && insertResult.raw instanceof Array && this.expressionMap.extraReturningColumns.length > 0) { insertResult.raw = insertResult.raw.reduce((newRaw, rawItem, rawItemIndex) => { newRaw[this.expressionMap.extraReturningColumns[rawItemIndex].databaseName] = rawItem[0]; return newRaw; }, {} as ObjectLiteral); } ======= const generatedMaps = entities.map((entity, entityIndex) => { >>>>>>> const generatedMaps = entities.map((entity, entityIndex) => { if (this.queryRunner.connection.driver instanceof OracleDriver && insertResult.raw instanceof Array && this.expressionMap.extraReturningColumns.length > 0) { insertResult.raw = insertResult.raw.reduce((newRaw, rawItem, rawItemIndex) => { newRaw[this.expressionMap.extraReturningColumns[rawItemIndex].databaseName] = rawItem[0]; return newRaw; }, {} as ObjectLiteral); }
<<<<<<< this.isCascadeInsert = args.options.cascade === true || (args.options.cascade instanceof Array && args.options.cascade.indexOf("insert") !== -1); this.isCascadeUpdate = args.options.cascade === true || (args.options.cascade instanceof Array && args.options.cascade.indexOf("update") !== -1); this.isNullable = args.options.nullable !== false; ======= this.isCascadeInsert = args.options.cascadeInsert || args.options.cascadeAll || false; this.isCascadeUpdate = args.options.cascadeUpdate || args.options.cascadeAll || false; this.isCascadeRemove = args.options.cascadeRemove || args.options.cascadeAll || false; this.isNullable = args.options.nullable === false || this.isPrimary ? false : true; >>>>>>> this.isCascadeInsert = args.options.cascade === true || (args.options.cascade instanceof Array && args.options.cascade.indexOf("insert") !== -1); this.isCascadeUpdate = args.options.cascade === true || (args.options.cascade instanceof Array && args.options.cascade.indexOf("update") !== -1); this.isNullable = args.options.nullable === false || this.isPrimary ? false : true;
<<<<<<< import { getDefaultRollup } from './validations'; import { ConfigOptions, RollupSettings } from './types'; ======= import { SettingsOptions, RollupConfig } from './types'; >>>>>>> import { getDefaultRollup } from './validations'; import { SettingsOptions, RollupSettings } from './types';
<<<<<<< constructor({ context, worker = false, configOptions = {} }) { ======= hookInterface: any; shortcodes: ShortcodeDefs; constructor({ context, worker = false }) { >>>>>>> hookInterface: any; shortcodes: ShortcodeDefs; constructor({ context, worker = false, configOptions = {} }) { <<<<<<< const config = getConfig(context, configOptions); const { rootDir, srcFolder, buildFolder } = config.locations; ======= const config = getConfig(); >>>>>>> const config = getConfig(configOptions); <<<<<<< const srcPlugin = path.resolve(rootDir, srcFolder, pluginPath); ======= const srcPlugin = path.resolve(this.settings.srcDir, pluginPath); >>>>>>> const srcPlugin = path.resolve(this.settings.srcDir, pluginPath); <<<<<<< const ssrComponent = path.resolve( rootDir, this.settings.locations.svelte.ssrComponents, `${templateName}.js`, ); ======= const ssrComponent = path.resolve(this.settings.$$internal.ssrComponents, `${templateName}.js`); >>>>>>> const ssrComponent = path.resolve(this.settings.$$internal.ssrComponents, `${templateName}.js`); <<<<<<< const hookSrcPath = path.resolve(rootDir, srcFolder, './hooks.js'); const hookBuildPath = path.resolve(rootDir, buildFolder, './hooks.js'); if (this.settings.debug.automagic) { console.log( `debug.automagic::Attempting to automagically pull in hooks from your ${hookSrcPath} ${ buildFolder ? `with a fallback to ${hookBuildPath}` : '' }`, ); } try { const hookSrcFile: Array<HookOptions> = config.typescript ? require(hookSrcPath).default : require(hookSrcPath); ======= const hookSrcPath = path.resolve(this.settings.srcDir, './hooks.js'); >>>>>>> const hookSrcPath = path.resolve(this.settings.srcDir, './hooks.js');
<<<<<<< import { UnifiedCacheManager } from "../cache/UnifiedCacheManager"; import { AccountEntity } from "../cache/entities/AccountEntity"; import { IAccount } from "../account/IAccount"; import { AccountCache, InMemoryCache } from "../cache/utils/CacheTypes"; ======= import { UnifiedCacheManager } from "../unifiedCache/UnifiedCacheManager"; import { IAccount } from "../account/IAccount"; import { AccountCache } from "../unifiedCache/utils/CacheTypes"; import { AccountEntity } from "../unifiedCache/entities/AccountEntity"; >>>>>>> import { UnifiedCacheManager } from "../cache/UnifiedCacheManager"; import { AccountEntity } from "../cache/entities/AccountEntity"; import { IAccount } from "../account/IAccount"; import { AccountCache } from "../cache/utils/CacheTypes"; <<<<<<< protected updateCache(): void { const cache = this.unifiedCacheManager.getCache(); this.cacheStorage.setCache(cache as InMemoryCache); } /** * Get all currently signed in accounts. */ public getAllAccounts(): IAccount[] { const currentAccounts: AccountCache = this.unifiedCacheManager.getAllAccounts(); console.log("Current Accounts Obj: " , currentAccounts); const accountValues: AccountEntity[] = Object.values(currentAccounts); console.log("Accounts: " , accountValues); const numAccounts = accountValues.length; if (numAccounts < 1) { return null; } else { return accountValues.map<IAccount>((value) => { return { homeAccountId: value.homeAccountId, localAccountId: value.localAccountId, environment: value.environment, tenantId: value.realm, userName: value.username }; }); } ======= public getAllAccounts(): IAccount[] { const currentAccounts: AccountCache = this.unifiedCacheManager.getAllAccounts(); console.log("Current Accounts Obj: " , currentAccounts); const accountValues: AccountEntity[] = Object.values(currentAccounts); console.log("Accounts: " , accountValues); const numAccounts = accountValues.length; if (numAccounts < 1) { return null; } else { return accountValues.map<IAccount>((value) => { return { homeAccountId: value.homeAccountId, localAccountId: value.localAccountId, environment: value.environment, tenantId: value.realm, userName: value.username }; }); } >>>>>>> public getAllAccounts(): IAccount[] { const currentAccounts: AccountCache = this.unifiedCacheManager.getAllAccounts(); const accountValues: AccountEntity[] = Object.values(currentAccounts); const numAccounts = accountValues.length; if (numAccounts < 1) { return null; } else { return accountValues.map<IAccount>((value) => { return { homeAccountId: value.homeAccountId, localAccountId: value.localAccountId, environment: value.environment, tenantId: value.realm, userName: value.username }; }); }
<<<<<<< import type { ConfigOptions, PluginOptions, RollupSettings, ShortcodeDef } from './types'; ======= import type { SettingsOptions, PluginOptions, ShortcodeDef } from './types'; >>>>>>> import type { SettingsOptions, PluginOptions, ShortcodeDef, RollupSettings } from './types'; <<<<<<< const rollupSchema = yup.object({ svelteConfig: yup.object().default({}).notRequired().label('Usually imported from ./svelte.config.js'), rollupSettings: yup.object({ dev: yup.object({ splitComponents: yup .boolean() .default(false) .notRequired() .label( "Dramatically speeds up development reloads but breaks some of Svelte's core functionality such as shared stores across hydrated components.", ), }), }), }); ======= function getDefaultConfig(): SettingsOptions { const validated = configSchema.cast(); >>>>>>> const rollupSchema = yup.object({ svelteConfig: yup.object().default({}).notRequired().label('Usually imported from ./svelte.config.js'), rollupSettings: yup.object({ dev: yup.object({ splitComponents: yup .boolean() .default(false) .notRequired() .label( "Dramatically speeds up development reloads but breaks some of Svelte's core functionality such as shared stores across hydrated components.", ), }), }), replacements: yup.array().of(yup.string()), }); <<<<<<< function getDefaultConfig(): ConfigOptions { return configSchema.cast(); } ======= // function validateConfig(config = {}) { // try { // configSchema.validateSync(config); // const validated: SettingsOptions = configSchema.cast(config); // return validated; // } catch (err) { // return false; // } // } >>>>>>> function getDefaultConfig(): SettingsOptions { return configSchema.cast(); }
<<<<<<< import type { SettingsOptions, PluginOptions } from './types'; import type { ShortcodeDef } from '../shortcodes/types'; ======= import type { SettingsOptions, PluginOptions, ShortcodeDef, RollupSettings } from './types'; >>>>>>> import type { SettingsOptions, PluginOptions, RollupSettings } from './types'; import type { ShortcodeDef } from '../shortcodes/types';
<<<<<<< export class Size extends ValueWithRandom implements ISize, IOptionLoader<ISize> { ======= /** * [[include:Options/Particles/Size.md]] * @category Options */ export class Size implements ISize, IOptionLoader<ISize> { >>>>>>> /** * [[include:Options/Particles/Size.md]] * @category Options */ export class Size extends ValueWithRandom implements ISize, IOptionLoader<ISize> {
<<<<<<< import {Canvas} from "./Canvas"; import {EventListeners} from "./Utils/EventListeners"; import type {IRepulse} from "../Interfaces/IRepulse"; import type {IBubble} from "../Interfaces/IBubble"; import type {IImage} from "../Interfaces/IImage"; import type {IContainerInteractivity} from "../Interfaces/IContainerInteractivity"; import {Particles} from "./Particles"; import {Retina} from "./Retina"; import {ShapeType} from "../Enums/ShapeType"; import {PolygonMask} from "./PolygonMask"; import type {IOptions} from "../Interfaces/Options/IOptions"; import {FrameManager} from "./FrameManager"; import type {RecursivePartial} from "../Types/RecursivePartial"; import {Options} from "./Options/Options"; import {Utils} from "./Utils/Utils"; import type {IImageShape} from "../Interfaces/Options/Particles/Shape/IImageShape"; import {Presets} from "./Utils/Presets"; ======= import {Canvas} from "./Canvas"; import {EventListeners} from "./Utils/EventListeners"; import type {IRepulse} from "../Interfaces/IRepulse"; import type {IBubble} from "../Interfaces/IBubble"; import type {IImage} from "../Interfaces/IImage"; import type {IContainerInteractivity} from "../Interfaces/IContainerInteractivity"; import {Particles} from "./Particles"; import {Retina} from "./Retina"; import {ShapeType} from "../Enums/ShapeType"; import {PolygonMask} from "./PolygonMask"; import {ImageShape} from "./Options/Particles/Shape/ImageShape"; import type {IOptions} from "../Interfaces/Options/IOptions"; import {FrameManager} from "./FrameManager"; import type {RecursivePartial} from "../Types/RecursivePartial"; import {Options} from "./Options/Options"; import {Utils} from "./Utils/Utils"; import type {IImageShape} from "../Interfaces/Options/Particles/Shape/IImageShape"; import {Presets} from "./Utils/Presets"; >>>>>>> import {Canvas} from "./Canvas"; import {EventListeners} from "./Utils/EventListeners"; import type {IRepulse} from "../Interfaces/IRepulse"; import type {IBubble} from "../Interfaces/IBubble"; import type {IImage} from "../Interfaces/IImage"; import type {IContainerInteractivity} from "../Interfaces/IContainerInteractivity"; import {Particles} from "./Particles"; import {Retina} from "./Retina"; import {ShapeType} from "../Enums/ShapeType"; import {PolygonMask} from "./PolygonMask"; import type {IOptions} from "../Interfaces/Options/IOptions"; import {FrameManager} from "./FrameManager"; import type {RecursivePartial} from "../Types/RecursivePartial"; import {Options} from "./Options/Options"; import {Utils} from "./Utils/Utils"; import type {IImageShape} from "../Interfaces/Options/Particles/Shape/IImageShape"; import {Presets} from "./Utils/Presets"; <<<<<<< ======= public loadImage(optionsImage: ImageShape): Promise<IImage> { return new Promise((resolve: (value?: IImage | PromiseLike<IImage> | undefined) => void, reject: (reason?: any) => void) => { const src = optionsImage.src; const image: IImage = { type: src.substr(src.length - 3), }; if (optionsImage.src) { const img = new Image(); img.addEventListener("load", () => { image.obj = img; resolve(image); }); img.addEventListener("error", () => { reject(`Error tsParticles - loading image: ${optionsImage.src}`); }); img.src = optionsImage.src; } else { reject("Error tsParticles - No image.src"); } }); } >>>>>>> <<<<<<< try { this.images.push(await Utils.loadImage(imageShape)); } catch { } ======= this.images.push(await this.loadImage(imageShape)); >>>>>>> try { this.images.push(await Utils.loadImage(imageShape)); } catch { } <<<<<<< private checkBeforeDraw(): void { if (this.options.particles.shape.type === ShapeType.image || (this.options.particles.shape.type instanceof Array && this.options.particles.shape.type.every(v => v === ShapeType.image))) { if (!this.images.length) { this.stop(); return; } } this.init(); this.play(); } ======= >>>>>>>
<<<<<<< import { Trail } from "../Trail"; import type { RecursivePartial } from "../../../../Types"; import { Noise } from "../Noise/Noise"; ======= import { Trail } from "./Trail"; import type { RecursivePartial } from "../../../../Types/RecursivePartial"; import { Noise } from "./Noise/Noise"; >>>>>>> import { Trail } from "./Trail"; import type { RecursivePartial } from "../../../../Types"; import { Noise } from "./Noise/Noise";
<<<<<<< import { toggle } from './toggle'; ======= import { tab } from './tab'; import toggle from './toggle'; >>>>>>> import { toggle } from './toggle'; import { tab } from './tab'; <<<<<<< const toggleClasses = toggle(context); ======= const tabClasses = tab(context); >>>>>>> const toggleClasses = toggle(context); const tabClasses = tab(context);
<<<<<<< import { getIPFSURL } from './get-ipfs-url'; ======= import path = require('path'); >>>>>>> import { getIPFSURL } from './get-ipfs-url'; import path = require('path'); <<<<<<< const path = getRoot(); ======= const root = getRoot() >>>>>>> const root = getRoot(); <<<<<<< `${path}/.decentraland/linker-app/linker/index.html`, ======= path.join(root, '.decentraland', 'linker-app', 'linker', 'index.html') >>>>>>> path.join(root, '.decentraland', 'linker-app', 'linker', 'index.html') <<<<<<< router.get('/api/get-scene-data', async ctx => { ctx.body = await fs.readJson(`${path}/scene.json`); ======= router.get('/api/get-scene-data', async (ctx) => { ctx.body = await fs.readJson(path.join(root, 'scene.json')); >>>>>>> router.get('/api/get-scene-data', async (ctx) => { ctx.body = await fs.readJson(path.join(root, 'scene.json')); <<<<<<< project = JSON.parse( fs.readFileSync(`${path}/.decentraland/project.json`, 'utf-8'), ); ======= project = JSON.parse(fs.readFileSync(path.join(root, '.decentraland', 'project.json'), 'utf-8')) >>>>>>> project = JSON.parse(fs.readFileSync(path.join(root, '.decentraland', 'project.json'), 'utf-8'))
<<<<<<< import { readBody, cleanUrl, isExternalUrl, bareImportRE, removeQueryTimestamp } from '../utils' ======= import { clientPublicPath } from './serverPluginClient' import { readBody, cleanUrl, isExternalUrl, bareImportRE } from '../utils' >>>>>>> import { clientPublicPath } from './serverPluginClient' import { readBody, cleanUrl, isExternalUrl, bareImportRE, removeQueryTimestamp } from '../utils' <<<<<<< !ctx.path.startsWith(hmrClientPublicPath) && // need to rewrite for <script>\<template> part in vue files !((ctx.path.endsWith('.vue') || ctx.vue) && ctx.query.type === 'style') ======= ctx.path !== clientPublicPath && // only need to rewrite for <script> part in vue files !((ctx.path.endsWith('.vue') || ctx.vue) && ctx.query.type != null) >>>>>>> ctx.path !== clientPublicPath && // need to rewrite for <script>\<template> part in vue files !((ctx.path.endsWith('.vue') || ctx.vue) && ctx.query.type === 'style')
<<<<<<< Highcharts.charts[this.quoteChart].series[3].addPoint([time, this.positionData.quoteAmount], false); Highcharts.charts[this.quoteChart].series[4].addPoint([time, this.positionData.quoteHeldAmount], this.showStats); Highcharts.charts[this.baseChart].series[0].addPoint([time, this.positionData.value], false); Highcharts.charts[this.baseChart].series[3].addPoint([time, this.positionData.baseAmount], false); Highcharts.charts[this.baseChart].series[4].addPoint([time, this.positionData.baseHeldAmount], this.showStats); ======= Highcharts.charts[this.quoteChart].series[2].addPoint([time, this.positionData.quoteAmount], false); Highcharts.charts[this.quoteChart].series[3].addPoint([time, this.positionData.quoteHeldAmount], this.showStats); Highcharts.charts[this.baseChart].series[0].addPoint([time, this.positionData.baseValue], false); Highcharts.charts[this.baseChart].series[2].addPoint([time, this.positionData.baseAmount], false); Highcharts.charts[this.baseChart].series[3].addPoint([time, this.positionData.baseHeldAmount], this.showStats); >>>>>>> Highcharts.charts[this.quoteChart].series[3].addPoint([time, this.positionData.quoteAmount], false); Highcharts.charts[this.quoteChart].series[4].addPoint([time, this.positionData.quoteHeldAmount], this.showStats); Highcharts.charts[this.baseChart].series[0].addPoint([time, this.positionData.baseValue], false); Highcharts.charts[this.baseChart].series[3].addPoint([time, this.positionData.baseAmount], false); Highcharts.charts[this.baseChart].series[4].addPoint([time, this.positionData.baseHeldAmount], this.showStats);
<<<<<<< KEEPALIVE, ======= SUBSCRIPTION_KEEPALIVE, SUBSCRIPTION_END, >>>>>>> KEEPALIVE, SUBSCRIPTION_END, <<<<<<< it('sends back any type of error', function (done) { const client = new SubscriptionClient(`ws://localhost:${TEST_PORT}/`); ======= it('does not crash on unsub for Object.prototype member', function(done) { // Use websocket because Client.unsubscribe will only take a number. const client = new W3CWebSocket(`ws://localhost:${TEST_PORT}/`, GRAPHQL_SUBSCRIPTIONS); client.onopen = () => { client.send(JSON.stringify({type: SUBSCRIPTION_END, id: 'toString'})); // Strangely we don't send any acknowledgement for unsubbing from an // unknown sub, so we just set a timeout and implicitly assert that // there's no uncaught exception within the server code. setTimeout(done, 10); }; }); it('sends back any type of error', function(done) { const client = new Client(`ws://localhost:${TEST_PORT}/`); >>>>>>> it('does not crash on unsub for Object.prototype member', function(done) { // Use websocket because Client.unsubscribe will only take a number. const client = new W3CWebSocket(`ws://localhost:${TEST_PORT}/`, GRAPHQL_SUBSCRIPTIONS); client.onopen = () => { client.send(JSON.stringify({type: SUBSCRIPTION_END, id: 'toString'})); // Strangely we don't send any acknowledgement for unsubbing from an // unknown sub, so we just set a timeout and implicitly assert that // there's no uncaught exception within the server code. setTimeout(done, 10); }; }); it('sends back any type of error', function (done) { const client = new SubscriptionClient(`ws://localhost:${TEST_PORT}/`);
<<<<<<< import * as Backoff from 'backo2'; import {EventEmitter, ListenerFn} from 'eventemitter3'; import {MiddlewareInterface} from './middleware'; ======= >>>>>>> <<<<<<< private subscriptionTimeout: number; private waitingSubscriptions: {[id: string]: boolean}; // subscriptions waiting for SUBSCRIPTION_SUCCESS private waitingUnsubscribes: {[id: string]: boolean}; // unsubscribe calls waiting for SUBSCRIPTION_START ======= private wsTimeout: number; >>>>>>> private wsTimeout: number; <<<<<<< private middlewares: MiddlewareInterface[]; ======= private wasKeepAliveReceived: boolean; private checkConnectionTimeoutId: any; >>>>>>> private wasKeepAliveReceived: boolean; private checkConnectionTimeoutId: any; private middlewares: MiddlewareInterface[]; private pendingSubscriptions: {[id: string]: boolean}; <<<<<<< this.subscriptions = {}; this.maxId = 0; this.subscriptionTimeout = timeout; this.waitingSubscriptions = {}; this.waitingUnsubscribes = {}; ======= this.operations = {}; this.nextOperationId = 0; this.wsTimeout = timeout; >>>>>>> this.operations = {}; this.nextOperationId = 0; this.wsTimeout = timeout; <<<<<<< if (!this.subscriptions[id] && !this.waitingSubscriptions[id]) { this.waitingUnsubscribes[id] = true; return; } delete this.subscriptions[id]; delete this.waitingSubscriptions[id]; let message = { id, type: SUBSCRIPTION_END}; this.sendMessage(message); ======= if (this.operations[id]) { delete this.operations[id]; } this.sendMessage(id, MessageTypes.GQL_STOP, undefined); >>>>>>> // operation hasn't sent message yet // cancel without sending message to server if (this.pendingSubscriptions[id]) { delete this.pendingSubscriptions[id]; return; } if (this.operations[id]) { delete this.operations[id]; } this.sendMessage(id, MessageTypes.GQL_STOP, undefined); <<<<<<< public applyMiddlewares(options: SubscriptionOptions): Promise<SubscriptionOptions> { return new Promise((resolve, reject) => { const queue = (funcs: MiddlewareInterface[], scope: any) => { const next = () => { if (funcs.length > 0) { const f = funcs.shift(); if (f) { f.applyMiddleware.apply(scope, [options, next]); } } else { resolve(options); } }; next(); }; queue([...this.middlewares], this); }); } public use(middlewares: MiddlewareInterface[]): SubscriptionClient { middlewares.map((middleware) => { if (typeof middleware.applyMiddleware === 'function') { this.middlewares.push(middleware); } else { throw new Error('Middleware must implement the applyMiddleware function'); } }); return this; } private checkSubscriptionParams(options: SubscriptionOptions, handler: (error: Error[], result?: any) => void) { const { query, variables, operationName, context } = options; if (!query) { throw new Error('Must provide `query` to subscribe.'); } if (!handler) { throw new Error('Must provide `handler` to subscribe.'); } if ( !isString(query) || ( operationName && !isString(operationName)) || ( variables && !isObject(variables)) ) { throw new Error('Incorrect option types to subscribe. `subscription` must be a string,' + '`operationName` must be a string, and `variables` must be an object.'); } }; // send message, or queue it if connection is not open private sendMessage(message: Object) { switch (this.client.readyState) { ======= private executeOperation(options: OperationOptions, handler: (error: Error[], result?: any) => void): number { const { query, variables, operationName } = options; if (!query) { throw new Error('Must provide a query.'); } if (!handler) { throw new Error('Must provide an handler.'); } if ( ( !isString(query) && !getOperationAST(query, operationName)) || ( operationName && !isString(operationName)) || ( variables && !isObject(variables)) ) { throw new Error('Incorrect option types. query must be a string or a document,' + '`operationName` must be a string, and `variables` must be an object.'); } const opId = this.generateOperationId(); this.operations[opId] = { options, handler }; this.sendMessage(opId, MessageTypes.GQL_START, options); return opId; } private buildMessage(id: number, type: string, payload: any) { const payloadToReturn = payload && payload.query ? { ...payload, query: typeof payload.query === 'string' ? payload.query : print(payload.query), } : payload; return { id, type, payload: payloadToReturn, }; } // ensure we have an array of errors private formatErrors(errors: any): FormatedError[] { if (Array.isArray(errors)) { return errors; } // TODO we should not pass ValidationError to callback in the future. // ValidationError if (errors && errors.errors) { return this.formatErrors(errors.errors); } if (errors && errors.message) { return [errors]; } return [{ name: 'FormatedError', message: 'Unknown error', originalError: errors, }]; } >>>>>>> public applyMiddlewares(options: OperationOptions): Promise<OperationOptions> { return new Promise((resolve, reject) => { const queue = (funcs: MiddlewareInterface[], scope: any) => { const next = () => { if (funcs.length > 0) { const f = funcs.shift(); if (f) { f.applyMiddleware.apply(scope, [options, next]); } } else { resolve(options); } }; next(); }; queue([...this.middlewares], this); }); } public use(middlewares: MiddlewareInterface[]): SubscriptionClient { middlewares.map((middleware) => { if (typeof middleware.applyMiddleware === 'function') { this.middlewares.push(middleware); } else { throw new Error('Middleware must implement the applyMiddleware function'); } }); return this; } private checkSubscriptionOptions(options: OperationOptions, handler: (error: Error[], result?: any) => void) { const { query, variables, operationName } = options; if (!query) { throw new Error('Must provide a query.'); } if ( ( !isString(query) && !getOperationAST(query, operationName)) || ( operationName && !isString(operationName)) || ( variables && !isObject(variables)) ) { throw new Error('Incorrect option types. query must be a string or a document,' + '`operationName` must be a string, and `variables` must be an object.'); } } private executeOperation(options: OperationOptions, handler: (error: Error[], result?: any) => void): number { this.checkSubscriptionOptions(options, handler); const opId = this.generateOperationId(); // add subscription to operation this.pendingSubscriptions[opId] = true; this.applyMiddlewares(options).then(opts => { this.checkSubscriptionOptions(opts, handler); // if operation is unsubscribed already // this.pendingSubscriptions[opId] will be deleted if (this.pendingSubscriptions[opId]) { delete this.pendingSubscriptions[opId]; this.operations[opId] = { options: opts, handler }; this.sendMessage(opId, MessageTypes.GQL_START, options); } }).catch((e: Error) => { this.unsubscribe(opId); handler([e]); }); return opId; } private buildMessage(id: number, type: string, payload: any) { const payloadToReturn = payload && payload.query ? { ...payload, query: typeof payload.query === 'string' ? payload.query : print(payload.query), } : payload; return { id, type, payload: payloadToReturn, }; } // ensure we have an array of errors private formatErrors(errors: any): FormatedError[] { if (Array.isArray(errors)) { return errors; } // TODO we should not pass ValidationError to callback in the future. // ValidationError if (errors && errors.errors) { return this.formatErrors(errors.errors); } if (errors && errors.message) { return [errors]; } return [{ name: 'FormatedError', message: 'Unknown error', originalError: errors, }]; } <<<<<<< // console.log('MSG', JSON.stringify(parsedMessage, null, 2)); switch (parsedMessage.type) { case INIT_FAIL: if (this.connectionCallback) { this.connectionCallback(parsedMessage.payload.error); } break; case INIT_SUCCESS: if (this.connectionCallback) { this.connectionCallback(); } break; case SUBSCRIPTION_SUCCESS: delete this.waitingSubscriptions[subId]; break; case SUBSCRIPTION_FAIL: if (!this.subscriptions[subId]) { delete this.waitingSubscriptions[subId]; break; } this.subscriptions[subId].handler(this.formatErrors(parsedMessage.payload.errors), null); delete this.subscriptions[subId]; delete this.waitingSubscriptions[subId]; break; case SUBSCRIPTION_DATA: if (!this.subscriptions[subId]) { break; } const payloadData = parsedMessage.payload.data || null; const payloadErrors = parsedMessage.payload.errors ? this.formatErrors(parsedMessage.payload.errors) : null; this.subscriptions[subId].handler(payloadErrors, payloadData); break; case KEEPALIVE: break; default: throw new Error('Invalid message type!'); } }; ======= case MessageTypes.GQL_CONNECTION_ACK: if (this.connectionCallback) { this.connectionCallback(); } break; case MessageTypes.GQL_COMPLETE: delete this.operations[opId]; break; case MessageTypes.GQL_ERROR: this.operations[opId].handler(this.formatErrors(parsedMessage.payload), null); delete this.operations[opId]; break; case MessageTypes.GQL_DATA: const parsedPayload = !parsedMessage.payload.errors ? parsedMessage.payload : {...parsedMessage.payload, errors: this.formatErrors(parsedMessage.payload.errors)}; this.operations[opId].handler(null, parsedPayload); break; case MessageTypes.GQL_CONNECTION_KEEP_ALIVE: this.wasKeepAliveReceived = true; if (this.checkConnectionTimeoutId) { clearTimeout(this.checkConnectionTimeoutId); } this.checkConnectionTimeoutId = setTimeout(this.checkConnection, this.wsTimeout); break; default: throw new Error('Invalid message type!'); } >>>>>>> case MessageTypes.GQL_CONNECTION_ACK: if (this.connectionCallback) { this.connectionCallback(); } break; case MessageTypes.GQL_COMPLETE: delete this.operations[opId]; break; case MessageTypes.GQL_ERROR: this.operations[opId].handler(this.formatErrors(parsedMessage.payload), null); delete this.operations[opId]; break; case MessageTypes.GQL_DATA: const parsedPayload = !parsedMessage.payload.errors ? parsedMessage.payload : {...parsedMessage.payload, errors: this.formatErrors(parsedMessage.payload.errors)}; this.operations[opId].handler(null, parsedPayload); break; case MessageTypes.GQL_CONNECTION_KEEP_ALIVE: this.wasKeepAliveReceived = true; if (this.checkConnectionTimeoutId) { clearTimeout(this.checkConnectionTimeoutId); } this.checkConnectionTimeoutId = setTimeout(this.checkConnection, this.wsTimeout); break; default: throw new Error('Invalid message type!'); }
<<<<<<< const KEEP_ALIVE_TEST_PORT = TEST_PORT + 1; const DELAYED_TEST_PORT = TEST_PORT + 2; const CAPTURE_TEST_PORT = TEST_PORT + 3; ======= const KEEP_ALIVE_TEST_PORT = TEST_PORT + 1; const DELAYED_TEST_PORT = TEST_PORT + 2; const RAW_TEST_PORT = TEST_PORT + 4; >>>>>>> const KEEP_ALIVE_TEST_PORT = TEST_PORT + 1; const DELAYED_TEST_PORT = TEST_PORT + 2; const CAPTURE_TEST_PORT = TEST_PORT + 3; const RAW_TEST_PORT = TEST_PORT + 4; <<<<<<< const httpServerWithDelay = createServer(notFoundRequestListener); httpServerWithDelay.listen(DELAYED_TEST_PORT); new SubscriptionServer(Object.assign({}, options, { onSubscribe: (msg: SubscribeMessage, params: SubscriptionOptions) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(Object.assign({}, params, { context: msg['context'] })); }, 100); }); }, }), httpServerWithDelay); let capturedParams: SubscriptionOptions; const httpServerWithCapture = createServer(notFoundRequestListener); httpServerWithCapture.listen(CAPTURE_TEST_PORT); new SubscriptionServer(Object.assign({}, options, { onSubscribe: (msg: SubscribeMessage, params: SubscriptionOptions) => { capturedParams = params; return params; }, }), httpServerWithCapture); ======= const httpServerWithDelay = createServer(notFoundRequestListener); httpServerWithDelay.listen(DELAYED_TEST_PORT); new SubscriptionServer(Object.assign({}, options, { onSubscribe: (msg: SubscribeMessage, params: SubscriptionOptions) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(Object.assign({}, params, { context: msg['context'] })); }, 100); }); }, }), httpServerWithDelay); const httpServerRaw = createServer(notFoundRequestListener); httpServerRaw.listen(RAW_TEST_PORT); >>>>>>> const httpServerWithDelay = createServer(notFoundRequestListener); httpServerWithDelay.listen(DELAYED_TEST_PORT); new SubscriptionServer(Object.assign({}, options, { onSubscribe: (msg: SubscribeMessage, params: SubscriptionOptions) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(Object.assign({}, params, { context: msg['context'] })); }, 100); }); }, }), httpServerWithDelay); let capturedParams: SubscriptionOptions; const httpServerWithCapture = createServer(notFoundRequestListener); httpServerWithCapture.listen(CAPTURE_TEST_PORT); new SubscriptionServer(Object.assign({}, options, { onSubscribe: (msg: SubscribeMessage, params: SubscriptionOptions) => { capturedParams = params; return params; }, }), httpServerWithCapture); const httpServerRaw = createServer(notFoundRequestListener); httpServerRaw.listen(RAW_TEST_PORT);
<<<<<<< this.wsServer.on('connection', (socket: WebSocket) => { // NOTE: the old GRAPHQL_SUBSCRIPTIONS protocol support should be removed in the future if (socket.protocol === undefined || (socket.protocol.indexOf(GRAPHQL_WS) === -1 && socket.protocol.indexOf(GRAPHQL_SUBSCRIPTIONS) === -1)) { // Close the connection with an error code, and // then terminates the actual network connection (sends FIN packet) ======= this.wsServer.on('connection', (request: WebSocket) => { if (request.protocol === undefined || request.protocol.indexOf(GRAPHQL_SUBSCRIPTIONS) === -1) { // Close the connection with an error code, ws v2 ensures that the // connection is cleaned up even when the closing handshake fails. >>>>>>> this.wsServer.on('connection', (socket: WebSocket) => { // NOTE: the old GRAPHQL_SUBSCRIPTIONS protocol support should be removed in the future if (socket.protocol === undefined || (socket.protocol.indexOf(GRAPHQL_WS) === -1 && socket.protocol.indexOf(GRAPHQL_SUBSCRIPTIONS) === -1)) { // Close the connection with an error code, ws v2 ensures that the // connection is cleaned up even when the closing handshake fails. <<<<<<< socket.close(1002); socket.terminate(); ======= request.close(1002); >>>>>>> socket.close(1002); <<<<<<< this.sendMessage( connectionContext, reqId, sanitizedOverrideDefaultErrorType, errorPayload, ); ======= private sendInitResult(connection: WebSocket, result: any): void { connection.send(JSON.stringify(result), () => { if (result.type === INIT_FAIL) { // Close the connection with an error code, ws v2 ensures that the // connection is cleaned up even when the closing handshake fails. // 1011: an unexpected condition prevented the request from being fulfilled // We are using setTimeout because we want the message to be flushed before // disconnecting the client setTimeout(() => { connection.close(1011); }, 10); } }); >>>>>>> this.sendMessage( connectionContext, reqId, sanitizedOverrideDefaultErrorType, errorPayload, );
<<<<<<< const connectionSubscriptions: ConnectionSubscriptions = {}; const connectionContext: ConnectionContext = {}; request.on('message', this.onMessage(request, connectionSubscriptions, connectionContext)); request.on('close', () => { this.onClose(request, connectionSubscriptions)(); if (this.onDisconnect) { this.onDisconnect(request); } }); ======= const connectionSubscriptions: ConnectionSubscriptions = Object.create(null); connection.on('message', this.onMessage(connection, connectionSubscriptions, request)); connection.on('close', this.onClose(connection, connectionSubscriptions)); >>>>>>> const connectionSubscriptions: ConnectionSubscriptions = Object.create(null); const connectionContext: ConnectionContext = Object.create(null); request.on('message', this.onMessage(request, connectionSubscriptions, connectionContext)); request.on('close', () => { this.onClose(request, connectionSubscriptions)(); if (this.onDisconnect) { this.onDisconnect(request); } });
<<<<<<< getUpdateMenuItem(): MenuOpts { // TODO - localization if (AppUpdater.status === UpdateStatus.UpdateReadyToInstall) { return { id: 'auto-update', label: 'Restart to Update...', click: () => AppUpdater.quitAndInstall(), enabled: true, }; } else if (AppUpdater.status === UpdateStatus.UpdateDownloading) { return { id: 'auto-update', label: `Update downloading...`, enabled: false, }; } else { return { id: 'auto-update', label: 'Check for Update...', click: () => AppUpdater.checkForUpdates(true), enabled: true, }; } } getConversationMenu(): MenuOpts { const getState = () => mainWindow.commandService.remoteCall(SharedConstants.Commands.Misc.GetStoreState); const getConversationId = async () => { const state = await getState(); const { editors, activeEditor } = state.editor; const { activeDocumentId } = editors[activeEditor]; return state.chat.chats[activeDocumentId].conversationId; }; const getServiceUrl = () => emulator.framework.serverUrl.replace('[::]', 'localhost'); const createClickHandler = serviceFunction => { return () => { getConversationId() .then(conversationId => serviceFunction(getServiceUrl(), conversationId)); }; }; return { label: 'Conversation', submenu: [ { label: 'Send System Activity', submenu: [ { label: 'conversationUpdate ( user added )', click: createClickHandler(ConversationService.addUser) }, { label: 'conversationUpdate ( user removed )', click: createClickHandler(ConversationService.removeUser) }, { label: 'contactRelationUpdate ( bot added )', click: createClickHandler(ConversationService.botContactAdded) }, { label: 'contactRelationUpdate ( bot removed )', click: createClickHandler(ConversationService.botContactRemoved) }, { label: 'typing', click: createClickHandler(ConversationService.typing) }, { label: 'ping', click: createClickHandler(ConversationService.ping) }, { label: 'deleteUserData', click: createClickHandler(ConversationService.deleteUserData) } ] }, ] }; } /** * Takes a file menu template and places it at the * right position in the app menu template according to platform */ setFileMenu(fileMenuTemplate: MenuOpts, appMenuTemplate: MenuOpts[]): MenuOpts[] { if (process.platform === 'darwin') { appMenuTemplate[1] = fileMenuTemplate; } else { appMenuTemplate[0] = fileMenuTemplate; } return appMenuTemplate; } refreshAppUpdateMenu() { const helpMenu = this.menuTemplate.find(menuItem => menuItem.role === 'help'); const autoUpdateMenuItem = (helpMenu.submenu as Array<any>).find(menuItem => menuItem.id === 'auto-update'); Object.assign(autoUpdateMenuItem, this.getUpdateMenuItem()); Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate(this.menuTemplate)); } ======= >>>>>>>
<<<<<<< AppUpdater.on('update-available', async (update: UpdateInfo) => { ======= AppUpdater.on('checking-for-update', async (...args) => { await AppMenuBuilder.refreshAppUpdateMenu(); }); AppUpdater.on('update-available', async (update: UpdateInfo) => { await AppMenuBuilder.refreshAppUpdateMenu(); >>>>>>> AppUpdater.on('update-available', async (update: UpdateInfo) => { await AppMenuBuilder.refreshAppUpdateMenu(); <<<<<<< AppUpdater.on('up-to-date', () => { ======= AppUpdater.on('up-to-date', async (update: UpdateInfo) => { >>>>>>> AppUpdater.on('up-to-date', async () => { <<<<<<< AppUpdater.on('download-progress', async (info: ProgressInfo) => { // update the progress bar component const { UpdateProgressIndicator } = SharedConstants.Commands.UI; const progressPayload = { label: 'Downloading...', progress: info.percent }; await mainWindow.commandService.remoteCall(UpdateProgressIndicator, progressPayload).catch(e => console.error(e)); ======= AppUpdater.on('download-progress', async (progress: ProgressInfo) => { await AppMenuBuilder.refreshAppUpdateMenu(); >>>>>>> AppUpdater.on('download-progress', async (info: ProgressInfo) => { await AppMenuBuilder.refreshAppUpdateMenu(); // update the progress bar component const { UpdateProgressIndicator } = SharedConstants.Commands.UI; const progressPayload = { label: 'Downloading...', progress: info.percent }; await mainWindow.commandService.remoteCall(UpdateProgressIndicator, progressPayload).catch(e => console.error(e)); <<<<<<< const template: Electron.MenuItemConstructorOptions[] = AppMenuBuilder.getAppMenuTemplate(); Menu.setApplicationMenu(Menu.buildFromTemplate(template)); ======= // Start auto-updater AppUpdater.startup(); AppMenuBuilder.getMenuTemplate().then((template: Electron.MenuItemConstructorOptions[]) => { Menu.setApplicationMenu(Menu.buildFromTemplate(template)); }); >>>>>>> AppMenuBuilder.getMenuTemplate().then((template: Electron.MenuItemConstructorOptions[]) => { Menu.setApplicationMenu(Menu.buildFromTemplate(template)); });
<<<<<<< import { FileInfo, SharedConstants } from '@bfemulator/app-shared'; ======= import { FileInfo } from '@bfemulator/app-shared'; import { CommandService } from '@bfemulator/sdk-shared'; >>>>>>> import { FileInfo, SharedConstants } from '@bfemulator/app-shared'; import { CommandService } from '@bfemulator/sdk-shared'; <<<<<<< await mainWindow.commandService.remoteCall(SharedConstants.Commands.File.Clear); ======= await this.commandService.remoteCall('file:clear'); >>>>>>> await this.commandService.remoteCall(SharedConstants.Commands.File.Clear); <<<<<<< mainWindow.commandService.remoteCall(SharedConstants.Commands.File.Add, fileInfo); ======= this.commandService.remoteCall('file:add', fileInfo); >>>>>>> this.commandService.remoteCall(SharedConstants.Commands.File.Add, fileInfo); <<<<<<< mainWindow.commandService.remoteCall(SharedConstants.Commands.File.Remove, file); ======= this.commandService.remoteCall('file:remove', file); >>>>>>> this.commandService.remoteCall(SharedConstants.Commands.File.Remove, file); <<<<<<< mainWindow.commandService.remoteCall(SharedConstants.Commands.Bot.SetActive, bot, botDir); mainWindow.commandService.call(SharedConstants.Commands.Bot.RestartEndpointService); ======= this.commandService.remoteCall('bot:set-active', bot, botDir); this.commandService.call('bot:restart-endpoint-service'); >>>>>>> this.commandService.remoteCall(SharedConstants.Commands.Bot.SetActive, bot, botDir); this.commandService.call(SharedConstants.Commands.Bot.RestartEndpointService);
<<<<<<< width: safeLowerBound(settings.windowState.width, 0), height: safeLowerBound(settings.windowState.height, 0), x: safeLowerBound(settings.windowState.left, 0), y: safeLowerBound(settings.windowState.top, 0) ======= width: initBounds.width, height: initBounds.height, x: initBounds.x, y: initBounds.y, webPreferences: { directWrite: false } >>>>>>> width: initBounds.width, height: initBounds.height, x: initBounds.x, y: initBounds.y,
<<<<<<< import { SharedConstants, newNotification, Notification } from '@bfemulator/app-shared'; ======= import { PersistentSettings, Settings, SharedConstants } from '@bfemulator/app-shared'; >>>>>>> import { PersistentSettings, Settings, SharedConstants, newNotification, Notification } from '@bfemulator/app-shared'; <<<<<<< import { ngrokEmitter } from './ngrok'; import { sendNotificationToClient } from './utils/sendNotificationToClient'; ======= import { Store } from 'redux'; import { azureLoggedInUserChanged } from './settingsData/actions/azureAuthActions'; >>>>>>> import { Store } from 'redux'; import { azureLoggedInUserChanged } from './settingsData/actions/azureAuthActions'; import { ngrokEmitter } from './ngrok'; import { sendNotificationToClient } from './utils/sendNotificationToClient';
<<<<<<< ======= import StoreBackend from "../../data/StoreBackend" import { Hypermerge } from "../../modules/hypermerge" import CloudClient from "../../modules/discovery-cloud/Client" let racf = require("random-access-chrome-file") import { setupControlPanel, toggleControl } from "./control" process.hrtime = require("browser-process-hrtime") >>>>>>> import Queue from "../../data/Queue" import * as Msg from "../../data/StoreMsg" import { setupControlPanel, toggleControl } from "./control" <<<<<<< const DebugPane = document.getElementById("DebugPane")! import Queue from "../../data/Queue" import * as Msg from "../../data/StoreMsg" ======= >>>>>>> <<<<<<< ======= if (msg.type === "ToggleControl") { toggleControl() } store.onMessage(msg) >>>>>>>
<<<<<<< import StoreBackend from "./data/StoreBackend" let commandWindow: chrome.app.window.AppWindow ======= // This should be a real typescript file but we're having trouble // finding the AppWindow type which has a contentWindow on it. let mainWindow: chrome.app.window.AppWindow >>>>>>> import StoreBackend from "./data/StoreBackend" let mainWindow: chrome.app.window.AppWindow <<<<<<< ) } }) class StoreComms { store: StoreBackend constructor(store: any) { this.store = store } onMessage = (request: any, sender: any, sendResponse: any) => { let { command, args = {} } = request let { id, doc } = args switch (command) { case "Create": this.store.create().then(id => sendResponse(id)) break case "Open": this.store.open(id).then(doc => sendResponse(doc)) break case "Replace": return this.store.replace(id, doc) } return true // indicate we will respond asynchronously } } let store = new StoreBackend() let comms = new StoreComms(store) chrome.runtime.onMessage.addListener((request, sender, sendResponse) => comms.onMessage(request, sender, sendResponse), ) ======= }, win => { mainWindow = win win.fullscreen() win.show(true) // Passing focused: true }, ) }) >>>>>>> }, win => { mainWindow = win win.fullscreen() win.show(true) // Passing focused: true }, ) }) class StoreComms { store: StoreBackend constructor(store: any) { this.store = store } onMessage = (request: any, sender: any, sendResponse: any) => { let { command, args = {} } = request let { id, doc } = args switch (command) { case "Create": this.store.create().then(id => sendResponse(id)) break case "Open": this.store.open(id).then(doc => sendResponse(doc)) break case "Replace": return this.store.replace(id, doc) } return true // indicate we will respond asynchronously } } let store = new StoreBackend() let comms = new StoreComms(store) chrome.runtime.onMessage.addListener((request, sender, sendResponse) => comms.onMessage(request, sender, sendResponse), )
<<<<<<< ======= if (docId.startsWith("98bbA")) { console.log("CHANGE", docId, changes) } >>>>>>> <<<<<<< for (const docId in this.docHandles) { const handle = this.docHandles[docId] const connections = handle.connections() ======= port.onDisconnect.addListener(() => console.log("port discon: ", port.name, chrome.runtime.lastError), ) >>>>>>> for (const docId in this.docHandles) { const handle = this.docHandles[docId] const connections = handle.connections() <<<<<<< ======= if (docId.startsWith("98bbA")) { console.log("PATCH", docId, actorId, patch) } port.postMessage({ actorId, patch }) }) >>>>>>> <<<<<<< case "Create": { const { keys } = msg let keyPair = { publicKey: Base58.decode(keys.publicKey), secretKey: Base58.decode(keys.secretKey), } ======= onMessage = (request: any) => { let { command, args } = request switch (command) { case "Create": const { keys } = args let keyPair = { publicKey: Base58.decode(keys.publicKey), secretKey: Base58.decode(keys.secretKey), } >>>>>>> case "Create": { const { keys } = msg let keyPair = { publicKey: Base58.decode(keys.publicKey), secretKey: Base58.decode(keys.secretKey), } <<<<<<< ======= // return true // indicate we will respond asynchronously >>>>>>>
<<<<<<< import { Log } from "./log"; const log = new Log("DiscordBot"); ======= import {UserSyncroniser} from "./usersyncroniser"; >>>>>>> import { Log } from "./log"; import {UserSyncroniser} from "./usersyncroniser"; const log = new Log("DiscordBot"); <<<<<<< const jsLog = new Log("discord.js"); client.on("debug", (msg) => { jsLog.verbose("discord.js", msg); }); client.on("error", (msg) => { jsLog.error("discord.js", msg); }); client.on("warn", (msg) => { jsLog.warn("discord.js", msg); }); log.info("Discord bot client logged in."); ======= this.userSync = new UserSyncroniser(this.bridge, this.config, this); client.on("userUpdate", (_, user) => this.userSync.OnUpdateUser(user)); client.on("guildMemberAdd", (user) => this.userSync.OnAddGuildMember(user)); client.on("guildMemberRemove", (user) => this.userSync.OnRemoveGuildMember(user)); client.on("guildMemberUpdate", (oldUser, newUser) => this.userSync.OnUpdateGuildMember(oldUser, newUser)); client.on("debug", (msg) => { log.verbose("discord.js", msg); }); client.on("error", (msg) => { log.error("discord.js", msg); }); client.on("warn", (msg) => { log.warn("discord.js", msg); }); log.info("DiscordBot", "Discord bot client logged in."); >>>>>>> const jsLog = new Log("discord.js"); this.userSync = new UserSyncroniser(this.bridge, this.config, this); client.on("userUpdate", (_, user) => this.userSync.OnUpdateUser(user)); client.on("guildMemberAdd", (user) => this.userSync.OnAddGuildMember(user)); client.on("guildMemberRemove", (user) => this.userSync.OnRemoveGuildMember(user)); client.on("guildMemberUpdate", (oldUser, newUser) => this.userSync.OnUpdateGuildMember(oldUser, newUser)); client.on("debug", (msg) => { jsLog.verbose(msg); }); client.on("error", (msg) => { jsLog.error(msg); }); client.on("warn", (msg) => { jsLog.warn(msg); }); log.info("Discord bot client logged in."); <<<<<<< log.verbose(`Couldn"t find room(s) for channel ${channel.id}.`); ======= log.verbose("DiscordBot", `Couldn"t find room(s) for guild id:${guild}.`); >>>>>>> log.verbose(`Couldn"t find room(s) for guild id:${guild}.`); <<<<<<< if (rooms.length === 0) { log.verbose(`Couldn"t find room(s) for guild id:${guild}.`); return Promise.reject("Room(s) not found."); } return rooms.map((room) => room.matrix.getId()); ======= if (rooms.length === 0) { log.verbose("DiscordBot", `Couldn"t find room(s) for channel ${channel.id}.`); return Promise.reject("Room(s) not found."); } return rooms.map((room) => room.matrix.getId() as string); >>>>>>> if (rooms.length === 0) { log.verbose(`Couldn"t find room(s) for channel ${channel.id}.`); return Promise.reject("Room(s) not found."); } return rooms.map((room) => room.matrix.getId() as string); <<<<<<< private AddGuildMember(guildMember: Discord.GuildMember) { return this.GetRoomIdsFromGuild(guildMember.guild.id).then((roomIds) => { return this.InitJoinUser(guildMember, roomIds); }); } private RemoveGuildMember(guildMember: Discord.GuildMember) { const intent = this.GetIntentFromDiscordMember(guildMember); return Bluebird.each(this.GetRoomIdsFromGuild(guildMember.guild.id), (roomId) => { this.presenceHandler.DequeueMember(guildMember); return intent.leave(roomId); }); } private UpdateGuildMember(guildMember: Discord.GuildMember, roomIds?: string[]) { const client = this.GetIntentFromDiscordMember(guildMember).getClient(); const userId = client.credentials.userId; let avatar = null; log.info(`Updating nick for ${guildMember.user.username}`); Bluebird.each(client.getProfileInfo(userId, "avatar_url").then((avatarUrl) => { avatar = avatarUrl.avatar_url; return roomIds || this.GetRoomIdsFromGuild(guildMember.guild.id); }), (room) => { log.verbose(`Updating ${room}`); client.sendStateEvent(room, "m.room.member", { membership: "join", avatar_url: avatar, displayname: guildMember.displayName, }, userId); }).catch((err) => { log.error("Failed to update guild member %s", err); }); } ======= >>>>>>>
<<<<<<< public determineCodeLanguage: boolean = false; ======= public disableInviteNotifications: boolean = false; >>>>>>> public disableInviteNotifications: boolean = false; public determineCodeLanguage: boolean = false;
<<<<<<< client.on("messageDelete", (msg) => {this.DeleteDiscordMessage(msg); }); ======= client.on("guildMemberAdd", (newMember) => { this.AddGuildMember(newMember); }); client.on("guildMemberRemove", (oldMember) => { this.RemoveGuildMember(oldMember); }); client.on("guildMemberUpdate", (_, newMember) => { this.UpdateGuildMember(newMember); }); client.on("messageUpdate", (oldMessage, newMessage) => { this.OnMessageUpdate(oldMessage, newMessage); }); client.on("messageDelete", (msg) => { this.DeleteDiscordMessage(msg); }); >>>>>>> client.on("messageDelete", (msg) => {this.DeleteDiscordMessage(msg); }); client.on("guildMemberAdd", (newMember) => { this.AddGuildMember(newMember); }); client.on("guildMemberRemove", (oldMember) => { this.RemoveGuildMember(oldMember); }); client.on("guildMemberUpdate", (_, newMember) => { this.UpdateGuildMember(newMember); }); client.on("messageUpdate", (oldMessage, newMessage) => { this.OnMessageUpdate(oldMessage, newMessage); }); <<<<<<< ======= private UpdateUser(discordUser: Discord.User) { let remoteUser: RemoteUser; const displayName = discordUser.username + "#" + discordUser.discriminator; const id = `_discord_${discordUser.id}:${this.config.bridge.domain}`; const intent = this.bridge.getIntent("@" + id); const userStore = this.bridge.getUserStore(); return userStore.getRemoteUser(discordUser.id).then((u) => { remoteUser = u; if (remoteUser === null) { remoteUser = new RemoteUser(discordUser.id); return userStore.linkUsers( new MatrixUser(id), remoteUser, ); } return Promise.resolve(); }).then(() => { if (remoteUser.get("displayname") !== displayName) { return intent.setDisplayName(displayName).then(() => { remoteUser.set("displayname", displayName); return userStore.setRemoteUser(remoteUser); }); } return true; }).then(() => { if (remoteUser.get("avatarurl") !== discordUser.avatarURL && discordUser.avatarURL !== null) { return Util.UploadContentFromUrl( discordUser.avatarURL, intent, discordUser.avatar, ).then((avatar) => { intent.setAvatarUrl(avatar.mxcUrl).then(() => { remoteUser.set("avatarurl", discordUser.avatarURL); return userStore.setRemoteUser(remoteUser); }); }); } return true; }); } private async SendMatrixMessage(matrixMsg: MessageProcessorMatrixResult, chan: Discord.Channel, guild: Discord.Guild, author: Discord.User, msgID: string): Promise<boolean> { const rooms = await this.GetRoomIdsFromChannel(chan); const intent = this.GetIntentFromDiscordMember(author); rooms.forEach((room) => { intent.sendMessage(room, { body: matrixMsg.body, msgtype: "m.text", formatted_body: matrixMsg.formattedBody, format: "org.matrix.custom.html", }).then((res) => { const evt = new DbEvent(); evt.MatrixId = res.event_id + ";" + room; evt.DiscordId = msgID; evt.ChannelId = chan.id; evt.GuildId = guild.id; this.store.Insert(evt); }); }); // Sending was a success return true; } >>>>>>> private async SendMatrixMessage(matrixMsg: MessageProcessorMatrixResult, chan: Discord.Channel, guild: Discord.Guild, author: Discord.User, msgID: string): Promise<boolean> { const rooms = await this.GetRoomIdsFromChannel(chan); const intent = this.GetIntentFromDiscordMember(author); rooms.forEach((room) => { intent.sendMessage(room, { body: matrixMsg.body, msgtype: "m.text", formatted_body: matrixMsg.formattedBody, format: "org.matrix.custom.html", }).then((res) => { const evt = new DbEvent(); evt.MatrixId = res.event_id + ";" + room; evt.DiscordId = msgID; evt.ChannelId = chan.id; evt.GuildId = guild.id; this.store.Insert(evt); }); }); // Sending was a success return true; }
<<<<<<< /* Caches */ private roomIdsForGuildCache: Map<string, {roomIds: string[], ts: number}>; ======= private provisioner: Provisioner; >>>>>>> private provisioner: Provisioner; /* Caches */ private roomIdsForGuildCache: Map<string, {roomIds: string[], ts: number}>;
<<<<<<< public static GetUrlFromMxc(mxc: string, homeserverUrl: string, width: number = 0, height: number = 0, method: "crop"|"scale" = "crop"): string { const part = mxc.substr("mxc://".length); if (width || height) { let u = `${homeserverUrl}/_matrix/media/r0/thumbnail/${part}?method=${method}`; if (width) { u += `&width=${width}`; } if (height) { u += `&height=${height}`; } return u; } return `${homeserverUrl}/_matrix/media/r0/download/${part}`; } public static ParseMxid(unescapedMxid: string, escape: boolean = true) { const RADIX = 16; const parts = unescapedMxid.substr(1).split(":"); const domain = parts[1]; let localpart = parts[0]; if (escape) { const badChars = new Set(localpart.replace(/([a-z0-9]|-|\.|=|_)+/g, "")); badChars.forEach((c) => { const hex = c.charCodeAt(0).toString(RADIX).toLowerCase(); localpart = localpart.replace( new RegExp(`\\${c}`, "g"), `=${hex}`, ); }); } return { domain, localpart, mxid: `@${localpart}:${domain}`, }; } ======= interface IUploadResult { mxcUrl: string; size: number; } // Type type type Type = Function; // tslint:disable-line ban-types /** * Returns true if `obj` is subtype of at least one of the given types. */ export function isInstanceOfTypes(obj: object, types: Type[]): boolean { return types.some((type) => obj instanceof type); } /** * Append the old error message to the new one and keep its stack trace. * * @example * throw wrapError(e, HighLevelError, "This error is more specific"); * * @param oldError The original error to wrap. * @param newErrorType Type of the error returned by this function. * @returns A new error of type `newErrorType` containing the information of * the original error (stacktrace and error message). */ export function wrapError<T extends Error>( oldError: object|Error, newErrorType: new (...args: any[]) => T, // tslint:disable-line no-any ...args: any[] // tslint:disable-line no-any trailing-comma ): T { const newError = new newErrorType(...args); let appendMsg; if (oldError instanceof Error) { appendMsg = oldError.message; newError.stack = oldError.stack; } else { appendMsg = oldError.toString(); } newError.message += ":\n" + appendMsg; return newError; >>>>>>> public static GetUrlFromMxc(mxc: string, homeserverUrl: string, width: number = 0, height: number = 0, method: "crop"|"scale" = "crop"): string { const part = mxc.substr("mxc://".length); if (width || height) { let u = `${homeserverUrl}/_matrix/media/r0/thumbnail/${part}?method=${method}`; if (width) { u += `&width=${width}`; } if (height) { u += `&height=${height}`; } return u; } return `${homeserverUrl}/_matrix/media/r0/download/${part}`; } public static ParseMxid(unescapedMxid: string, escape: boolean = true) { const RADIX = 16; const parts = unescapedMxid.substr(1).split(":"); const domain = parts[1]; let localpart = parts[0]; if (escape) { const badChars = new Set(localpart.replace(/([a-z0-9]|-|\.|=|_)+/g, "")); badChars.forEach((c) => { const hex = c.charCodeAt(0).toString(RADIX).toLowerCase(); localpart = localpart.replace( new RegExp(`\\${c}`, "g"), `=${hex}`, ); }); } return { domain, localpart, mxid: `@${localpart}:${domain}`, }; } } // Type type type Type = Function; // tslint:disable-line ban-types /** * Returns true if `obj` is subtype of at least one of the given types. */ export function isInstanceOfTypes(obj: object, types: Type[]): boolean { return types.some((type) => obj instanceof type); } /** * Append the old error message to the new one and keep its stack trace. * * @example * throw wrapError(e, HighLevelError, "This error is more specific"); * * @param oldError The original error to wrap. * @param newErrorType Type of the error returned by this function. * @returns A new error of type `newErrorType` containing the information of * the original error (stacktrace and error message). */ export function wrapError<T extends Error>( oldError: object|Error, newErrorType: new (...args: any[]) => T, // tslint:disable-line no-any ...args: any[] // tslint:disable-line no-any trailing-comma ): T { const newError = new newErrorType(...args); let appendMsg; if (oldError instanceof Error) { appendMsg = oldError.message; newError.stack = oldError.stack; } else { appendMsg = oldError.toString(); } newError.message += ":\n" + appendMsg; return newError;
<<<<<<< private isEmbedInBody(msg: Discord.Message, embed: Discord.MessageEmbed): boolean { if (!embed.url) { return false; } return msg.content.includes(embed.url); } } ======= >>>>>>>
<<<<<<< let ATTACHMENT = {} as any; let MSGTYPE = ""; let SENT_MSG_CONTENT = {} as any; ======= >>>>>>> let ATTACHMENT = {} as any; let MSGTYPE = ""; let SENT_MSG_CONTENT = {} as any; <<<<<<< ATTACHMENT = {}; MSGTYPE = ""; SENT_MSG_CONTENT = {}; ======= >>>>>>> ATTACHMENT = {}; MSGTYPE = ""; SENT_MSG_CONTENT = {}; <<<<<<< discord.GetIntentFromDiscordMember = (_) => {return { sendMessage: async (room, msg) => { SENT_MESSAGE = true; if (msg.info) { ATTACHMENT = msg.info; } MSGTYPE = msg.msgtype; SENT_MSG_CONTENT = msg; return { event_id: "$fox:localhost", }; }, }; }; ======= >>>>>>> discord.GetIntentFromDiscordMember = (_) => {return { sendMessage: async (room, msg) => { SENT_MESSAGE = true; if (msg.info) { ATTACHMENT = msg.info; } MSGTYPE = msg.msgtype; SENT_MSG_CONTENT = msg; return { event_id: "$fox:localhost", }; }, }; }; <<<<<<< Chai.assert.equal(checkEditEventSent, "editedid"); ======= expect(checkMsgSent).to.be.true; >>>>>>> Chai.assert.equal(checkEditEventSent, "editedid"); expect(checkMsgSent).to.be.true; <<<<<<< Chai.assert.equal(checkEditEventSent, undefined); ======= expect(deletedMessage).to.be.true; expect(sentMessage).to.be.true; >>>>>>> Chai.assert.equal(checkEditEventSent, undefined); expect(deletedMessage).to.be.true; expect(sentMessage).to.be.true;
<<<<<<< import { IMatrixEvent, IMatrixMediaInfo, IMatrixMessage } from "./matrixtypes"; ======= import { IMatrixEvent, IMatrixMediaInfo } from "./matrixtypes"; import { Appservice, Intent } from "matrix-bot-sdk"; >>>>>>> import { IMatrixEvent, IMatrixMediaInfo, IMatrixMessage } from "./matrixtypes"; import { Appservice, Intent } from "matrix-bot-sdk"; <<<<<<< new MatrixEventProcessorOpts(config, bridge, store, this), ======= new MatrixEventProcessorOpts(config, bridge, this, store), >>>>>>> new MatrixEventProcessorOpts(config, bridge, this, store), <<<<<<< if (awaitStore) { await storePromise; } ======= >>>>>>> if (awaitStore) { await storePromise; } <<<<<<< private prepareEmbedSetUserAccount(embedSet: IMatrixEventProcessorResult): string { const embed = embedSet.messageEmbed; let addText = ""; if (embedSet.replyEmbed) { for (const line of embedSet.replyEmbed.description!.split("\n")) { addText += "\n> " + line; } } return embed.description += addText; } private prepareEmbedSetBotAccount(embedSet: IMatrixEventProcessorResult): Discord.RichEmbed | undefined { if (!embedSet.imageEmbed && !embedSet.replyEmbed) { return undefined; } let sendEmbed = new Discord.RichEmbed(); if (embedSet.imageEmbed) { if (!embedSet.replyEmbed) { sendEmbed = embedSet.imageEmbed; } else { sendEmbed.setImage(embedSet.imageEmbed.image!.url); } } if (embedSet.replyEmbed) { if (!embedSet.imageEmbed) { sendEmbed = embedSet.replyEmbed; } else { sendEmbed.addField("Replying to", embedSet.replyEmbed!.author!.name); sendEmbed.addField("Reply text", embedSet.replyEmbed.description); } } return sendEmbed; } private prepareEmbedSetWebhook(embedSet: IMatrixEventProcessorResult): Discord.RichEmbed[] { const embeds: Discord.RichEmbed[] = []; if (embedSet.imageEmbed) { embeds.push(embedSet.imageEmbed); } if (embedSet.replyEmbed) { embeds.push(embedSet.replyEmbed); } return embeds; } private prepareEmbedSetBot(embedSet: IMatrixEventProcessorResult): Discord.RichEmbed { const embed = embedSet.messageEmbed; if (embedSet.imageEmbed) { embed.setImage(embedSet.imageEmbed.image!.url); } if (embedSet.replyEmbed) { embed.addField("Replying to", embedSet.replyEmbed!.author!.name); embed.addField("Reply text", embedSet.replyEmbed.description); } return embed; } private async SendMatrixMessage(matrixMsg: DiscordMessageProcessorResult, chan: Discord.Channel, ======= private async SendMatrixMessage(matrixMsg: DiscordMessageParserResult, chan: Discord.Channel, >>>>>>> private prepareEmbedSetUserAccount(embedSet: IMatrixEventProcessorResult): string { const embed = embedSet.messageEmbed; let addText = ""; if (embedSet.replyEmbed) { for (const line of embedSet.replyEmbed.description!.split("\n")) { addText += "\n> " + line; } } return embed.description += addText; } private prepareEmbedSetBotAccount(embedSet: IMatrixEventProcessorResult): Discord.RichEmbed | undefined { if (!embedSet.imageEmbed && !embedSet.replyEmbed) { return undefined; } let sendEmbed = new Discord.RichEmbed(); if (embedSet.imageEmbed) { if (!embedSet.replyEmbed) { sendEmbed = embedSet.imageEmbed; } else { sendEmbed.setImage(embedSet.imageEmbed.image!.url); } } if (embedSet.replyEmbed) { if (!embedSet.imageEmbed) { sendEmbed = embedSet.replyEmbed; } else { sendEmbed.addField("Replying to", embedSet.replyEmbed!.author!.name); sendEmbed.addField("Reply text", embedSet.replyEmbed.description); } } return sendEmbed; } private prepareEmbedSetWebhook(embedSet: IMatrixEventProcessorResult): Discord.RichEmbed[] { const embeds: Discord.RichEmbed[] = []; if (embedSet.imageEmbed) { embeds.push(embedSet.imageEmbed); } if (embedSet.replyEmbed) { embeds.push(embedSet.replyEmbed); } return embeds; } private prepareEmbedSetBot(embedSet: IMatrixEventProcessorResult): Discord.RichEmbed { const embed = embedSet.messageEmbed; if (embedSet.imageEmbed) { embed.setImage(embedSet.imageEmbed.image!.url); } if (embedSet.replyEmbed) { embed.addField("Replying to", embedSet.replyEmbed!.author!.name); embed.addField("Reply text", embedSet.replyEmbed.description); } return embed; } private async SendMatrixMessage(matrixMsg: DiscordMessageParserResult, chan: Discord.Channel, <<<<<<< ======= this.lastEventIds[roomId] = eventId; >>>>>>> this.lastEventIds[roomId] = eventId; <<<<<<< const sendContent = { ======= const trySend = async () => intent.sendEvent(room, { >>>>>>> const trySend = async () => intent.sendEvent(room, { <<<<<<< } as IMatrixMessage; if (editEventId) { sendContent.body = `* ${result.body}`; sendContent.formatted_body = `* ${result.formattedBody}`; sendContent["m.new_content"] = { body: result.body, format: "org.matrix.custom.html", formatted_body: result.formattedBody, msgtype: result.msgtype, }; sendContent["m.relates_to"] = { event_id: editEventId, rel_type: "m.replace", }; } const trySend = async () => intent.sendMessage(room, sendContent); const afterSend = async (re) => { ======= }); const afterSend = async (eventId) => { this.lastEventIds[room] = eventId; >>>>>>> }); if (editEventId) { sendContent.body = `* ${result.body}`; sendContent.formatted_body = `* ${result.formattedBody}`; sendContent["m.new_content"] = { body: result.body, format: "org.matrix.custom.html", formatted_body: result.formattedBody, msgtype: result.msgtype, }; sendContent["m.relates_to"] = { event_id: editEventId, rel_type: "m.replace", }; } const trySend = async () => intent.sendMessage(room, sendContent); const afterSend = async (eventId) => { this.lastEventIds[room] = eventId;
<<<<<<< import { IRoomStoreEntry } from "./db/roomstore"; import { Appservice, MatrixClient } from "matrix-bot-sdk"; import { DiscordStore } from "./store"; ======= import { TimedCache } from "./structures/timedcache"; import { MetricPeg } from "./metrics"; >>>>>>> import { IRoomStoreEntry } from "./db/roomstore"; import { Appservice, MatrixClient } from "matrix-bot-sdk"; import { DiscordStore } from "./store"; import { TimedCache } from "./structures/timedcache"; import { MetricPeg } from "./metrics"; <<<<<<< this.store = opts.store; this.matrixMsgProcessor = new MatrixMessageProcessor(this.discord, this.config.bridge.homeserverUrl); ======= this.matrixMsgProcessor = new MatrixMessageProcessor(this.discord); this.mxUserProfileCache = new TimedCache(PROFILE_CACHE_LIFETIME); >>>>>>> this.store = opts.store; this.matrixMsgProcessor = new MatrixMessageProcessor(this.discord, this.config.bridge.homeserverUrl); this.mxUserProfileCache = new TimedCache(PROFILE_CACHE_LIFETIME); <<<<<<< await this.mxCommandHandler.Process(event, rooms[0] || null); return; } else if (remoteRoom) { const srvChanPair = remoteRoom.remote!.roomId.substr("_discord".length).split("_", ROOM_NAME_PARTS); ======= await this.mxCommandHandler.Process(event, context); } else if (context.rooms.remote) { const srvChanPair = context.rooms.remote.roomId.substr("_discord".length).split("_", ROOM_NAME_PARTS); >>>>>>> await this.mxCommandHandler.Process(event, rooms[0] || null); return; } else if (remoteRoom) { const srvChanPair = remoteRoom.remote!.roomId.substr("_discord".length).split("_", ROOM_NAME_PARTS); <<<<<<< } else if (event.type === "m.room.encryption" && remoteRoom) { ======= return; } else if (event.type === "m.room.encryption" && context.rooms.remote) { >>>>>>> return; } else if (event.type === "m.room.encryption" && remoteRoom) { <<<<<<< const mxClient = this.bridge.botIntent.underlyingClient; let profile: IMatrixEvent | null = null; try { profile = await mxClient.getRoomStateEvent(event.room_id, "m.room.member", event.sender); if (!profile) { profile = await mxClient.getUserProfile(event.sender); } if (!profile) { log.warn(`User ${event.sender} has no member state and no profile. That's odd.`); } } catch (err) { log.warn(`Trying to fetch member state or profile for ${event.sender} failed`, err); } ======= const mxClient = this.bridge.getClientFactory().getClientAs(); const profile = await this.GetUserProfileForRoom(event.room_id, event.sender); >>>>>>> const mxClient = this.bridge.botIntent.underlyingClient; const profile = await this.GetUserProfileForRoom(event.room_id, event.sender); <<<<<<< private async SetEmbedAuthor(embed: Discord.RichEmbed, sender: string, profile?: IMatrixEvent | null) { const intent = this.bridge.botIntent; ======= private async SetEmbedAuthor(embed: Discord.RichEmbed, sender: string, profile?: { displayname: string, avatar_url: string|undefined }) { >>>>>>> private async SetEmbedAuthor(embed: Discord.RichEmbed, sender: string, profile?: { displayname: string, avatar_url: string|undefined }) { <<<<<<< if (!profile) { try { profile = await intent.underlyingClient.getUserProfile(sender); } catch (ex) { log.warn(`Failed to fetch profile for ${sender}`, ex); } } ======= >>>>>>>
<<<<<<< log.info(`Skipping event due to age ${event.unsigned.age} > ${AGE_LIMIT}`); ======= // throw new Unstable.EventTooOldError( // `Skipping event due to age ${event.unsigned.age} > ${AGE_LIMIT}`, // ); return; >>>>>>> log.info(`Skipping event due to age ${event.unsigned.age} > ${AGE_LIMIT}`); // throw new Unstable.EventTooOldError( // `Skipping event due to age ${event.unsigned.age} > ${AGE_LIMIT}`, // ); return; <<<<<<< // throw new Unstable.EventUnknownError(`${event.event_id} not processed by bridge`); log.verbose(`${event.event_id} not processed by bridge`); ======= log.verbose(`${event.event_id} not processed by bridge`); //throw new Unstable.EventUnknownError(`${event.event_id} not processed by bridge`); >>>>>>> // throw new Unstable.EventUnknownError(`${event.event_id} not processed by bridge`); log.verbose(`${event.event_id} not processed by bridge`);
<<<<<<< import { DiscordBridgeConfig } from "./config"; ======= import { DiscordBridgeConfig, DiscordBridgeConfigChannelDeleteOptions } from "./config"; import { Bridge } from "matrix-appservice-bridge"; >>>>>>> import { DiscordBridgeConfig, DiscordBridgeConfigChannelDeleteOptions } from "./config"; <<<<<<< const intent = await this.bridge.botIntent; const options = this.config.channel.deleteOptions; ======= const intent = await this.bridge.getIntent(); const options = overrideOptions || this.config.channel.deleteOptions; >>>>>>> const intent = this.bridge.botIntent; const options = overrideOptions || this.config.channel.deleteOptions; <<<<<<< try { const mIntent = await this.bot.GetIntentFromDiscordMember(member); mIntent.underlyingClient.leaveRoom(roomId); log.info(`${member.id} left ${roomId}.`); } catch (e) { log.warn(`Failed to make ${member.id} leave `); } ======= const mIntent = await this.bot.GetIntentFromDiscordMember(member); // Not awaiting this because we want to do this in the background. mIntent.leave(roomId).then(() => { log.verbose(`${member.id} left ${roomId}.`); }).catch(() => { log.warn(`Failed to make ${member.id} leave.`); }); >>>>>>> try { const mIntent = this.bot.GetIntentFromDiscordMember(member); await mIntent.underlyingClient.leaveRoom(roomId); log.verbose(`${member.id} left ${roomId}.`); } catch (e) { log.warn(`Failed to make ${member.id} leave `); }
<<<<<<< import { AppserviceMock } from "./mocks/appservicemock"; import { MockUser } from "./mocks/user"; ======= import { MockChannel } from "./mocks/channel"; >>>>>>> import { AppserviceMock } from "./mocks/appservicemock"; import { MockUser } from "./mocks/user"; import { MockChannel } from "./mocks/channel"; import { DiscordBot } from "../src/bot"; <<<<<<< ======= describe("locks", () => { it("should lock and unlock a channel", async () => { const bot = new modDiscordBot.DiscordBot( "", config, mockBridge, {}, ) as DiscordBot; const chan = new MockChannel("123") as any; const t = Date.now(); bot.lockChannel(chan); await bot.waitUnlock(chan); const diff = Date.now() - t; expect(diff).to.be.greaterThan(config.limits.discordSendDelay - 1); }); it("should lock and unlock a channel early, if unlocked", async () => { const discordSendDelay = 500; const SHORTDELAY = 100; const MINEXPECTEDDELAY = 95; const bot = new modDiscordBot.DiscordBot( "", { bridge: { domain: "localhost", }, limits: { discordSendDelay, }, }, mockBridge, {}, ) as DiscordBot; const chan = new MockChannel("123") as any; setTimeout(() => bot.unlockChannel(chan), SHORTDELAY); const t = Date.now(); bot.lockChannel(chan); await bot.waitUnlock(chan); const diff = Date.now() - t; // Date accuracy can be off by a few ms sometimes. expect(diff).to.be.greaterThan(MINEXPECTEDDELAY); }); }); // }); // describe("ProcessMatrixMsgEvent()", () => { // // }); // describe("UpdateRoom()", () => { // // }); // describe("UpdateUser()", () => { // // }); // describe("UpdatePresence()", () => { // // }); // describe("OnTyping()", () => { // const discordBot = new modDiscordBot.DiscordBot( // config, // ); // discordBot.run(); // it("should reject an unknown room.", () => { // return assert.isRejected(discordBot.OnTyping( {id: "512"}, {id: "12345"}, true)); // }); // it("should resolve a known room.", () => { // return assert.isFulfilled(discordBot.OnTyping( {id: "321"}, {id: "12345"}, true)); // }); // }); >>>>>>> describe("locks", () => { it("should lock and unlock a channel", async () => { const bot = new modDiscordBot.DiscordBot( "", config, mockBridge, {}, ) as DiscordBot; const chan = new MockChannel("123") as any; const t = Date.now(); bot.lockChannel(chan); await bot.waitUnlock(chan); const diff = Date.now() - t; expect(diff).to.be.greaterThan(config.limits.discordSendDelay - 1); }); it("should lock and unlock a channel early, if unlocked", async () => { const discordSendDelay = 500; const SHORTDELAY = 100; const MINEXPECTEDDELAY = 95; const bot = new modDiscordBot.DiscordBot( "", { bridge: { domain: "localhost", }, limits: { discordSendDelay, }, }, mockBridge, {}, ) as DiscordBot; const chan = new MockChannel("123") as any; setTimeout(() => bot.unlockChannel(chan), SHORTDELAY); const t = Date.now(); bot.lockChannel(chan); await bot.waitUnlock(chan); const diff = Date.now() - t; // Date accuracy can be off by a few ms sometimes. expect(diff).to.be.greaterThan(MINEXPECTEDDELAY); }); });
<<<<<<< public nickname: string; ======= public roles = []; >>>>>>> public nickname: string; public roles = [];
<<<<<<< // 2020-12-07: If this fails to build in TypeScript with // "Namespace 'serveStatic' has no exported member 'RequestHandlerConstructor'.", // remove @types/express-serve-static-core and @types/serve-static from yarn.lock // and run yarn. // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/49595 appservice.expressAppInstance.get("/health", (_, res: Response) => { res.status(201).send(""); ======= // tslint:disable-next-line:no-any appservice.expressAppInstance.get("/health", (_, res: any) => { res.status(200).send(""); >>>>>>> // 2020-12-07: If this fails to build in TypeScript with // "Namespace 'serveStatic' has no exported member 'RequestHandlerConstructor'.", // remove @types/express-serve-static-core and @types/serve-static from yarn.lock // and run yarn. // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/49595 appservice.expressAppInstance.get("/health", (_, res: Response) => { res.status(200).send("");
<<<<<<< import * as cliArgs from "command-line-args"; import * as usage from "command-line-usage"; import * as uuid from "uuid/v4"; import { IMatrixEvent } from "./matrixtypes"; ======= import { MetricPeg, PrometheusBridgeMetrics } from "./metrics"; >>>>>>> import * as cliArgs from "command-line-args"; import * as usage from "command-line-usage"; import * as uuid from "uuid/v4"; import { IMatrixEvent } from "./matrixtypes"; import { MetricPeg, PrometheusBridgeMetrics } from "./metrics"; <<<<<<< async function run() { const opts = cliArgs(commandOptions); if (opts.help) { /* tslint:disable:no-console */ console.log(usage([ { content: "The matrix appservice for discord", header: "Matrix Discord Bridge", }, { header: "Options", optionList: commandOptions, }, ])); process.exit(0); ======= // tslint:disable-next-line no-any type callbackFn = (...args: any[]) => Promise<any>; async function run(port: number, fileConfig: DiscordBridgeConfig) { const config = new DiscordBridgeConfig(); config.applyConfig(fileConfig); config.applyEnvironmentOverrides(process.env); Log.Configure(config.logging); log.info("Starting Discord AS"); const yamlConfig = yaml.safeLoad(fs.readFileSync(cli.opts.registrationPath, "utf8")); const registration = AppServiceRegistration.fromObject(yamlConfig); if (registration === null) { throw new Error("Failed to parse registration file"); >>>>>>> function setupLogging() { const logMap = new Map<string, Log>(); const logFunc = (level: string, module: string, args: any[]) => { if (!Array.isArray(args)) { args = [args]; } if (args.find((s) => s.includes && s.includes("M_USER_IN_USE"))) { // Spammy logs begon return; } const mod = "bot-sdk" + module; let logger = logMap.get(mod); if (!logger) { logger = new Log(mod); logMap.set(mod, logger); } logger[level](args); }; LogService.setLogger({ debug: (mod: string, args: any[]) => logFunc("silly", mod, args), error: (mod: string, args: any[]) => logFunc("error", mod, args), info: (mod: string, args: any[]) => logFunc("info", mod, args), warn: (mod: string, args: any[]) => logFunc("warn", mod, args), }); } async function run() { const opts = cliArgs(commandOptions); if (opts.help) { /* tslint:disable:no-console */ console.log(usage([ { content: "The matrix appservice for discord", header: "Matrix Discord Bridge", }, { header: "Options", optionList: commandOptions, }, ])); process.exit(0); <<<<<<< const config = new DiscordBridgeConfig(); const port = opts.port || config.bridge.port; if (!port) { throw Error("Port not given in command line or config file"); } config.ApplyConfig(yaml.safeLoad(fs.readFileSync(configPath, "utf8"))); Log.Configure(config.logging); const registration = yaml.safeLoad(fs.readFileSync(registrationPath, "utf8")) as IAppserviceRegistration; const appservice = new Appservice({ bindAddress: config.bridge.bindAddress || "0.0.0.0", homeserverName: config.bridge.domain, ======= const bridge = new Bridge({ clientFactory, controller: { // onUserQuery: userQuery, onAliasQueried: async (alias: string, roomId: string) => { try { return await callbacks.onAliasQueried(alias, roomId); } catch (err) { log.error("Exception thrown while handling \"onAliasQueried\" event", err); } }, onAliasQuery: async (alias: string, aliasLocalpart: string) => { try { return await callbacks.onAliasQuery(alias, aliasLocalpart); } catch (err) { log.error("Exception thrown while handling \"onAliasQuery\" event", err); } }, onEvent: async (request) => { const data = request.getData(); try { MetricPeg.get.registerRequest(data.event_id); // Build our own context. if (!store.roomStore) { log.warn("Discord store not ready yet, dropping message"); MetricPeg.get.requestOutcome(data.event_id, false, "dropped"); return; } const roomId = data.room_id; const context: BridgeContext = { rooms: {}, }; if (roomId) { const entries = await store.roomStore.getEntriesByMatrixId(roomId); context.rooms = entries[0] || {}; } await request.outcomeFrom(callbacks.onEvent(request, context)); MetricPeg.get.requestOutcome(data.event_id, false, "success"); } catch (err) { MetricPeg.get.requestOutcome(data.event_id, false, "fail"); log.error("Exception thrown while handling \"onEvent\" event", err); await request.outcomeFrom(Promise.reject("Failed to handle")); } }, onLog: (line, isError) => { log.verbose("matrix-appservice-bridge", line); }, thirdPartyLookup: async () => { try { return await callbacks.thirdPartyLookup(); } catch (err) { log.error("Exception thrown while handling \"thirdPartyLookup\" event", err); } }, }, disableContext: true, domain: config.bridge.domain, >>>>>>> const config = new DiscordBridgeConfig(); const port = opts.port || config.bridge.port; if (!port) { throw Error("Port not given in command line or config file"); } config.applyConfig(yaml.safeLoad(fs.readFileSync(configPath, "utf8"))); Log.Configure(config.logging); const registration = yaml.safeLoad(fs.readFileSync(registrationPath, "utf8")) as IAppserviceRegistration; setupLogging(); const appservice = new Appservice({ bindAddress: config.bridge.bindAddress || "0.0.0.0", homeserverName: config.bridge.domain, <<<<<<< ======= await bridge.run(port, config); log.info(`Started listening on port ${port}`); if (config.bridge.enableMetrics) { log.info("Enabled metrics"); MetricPeg.set(new PrometheusBridgeMetrics().init(bridge)); } >>>>>>> if (config.bridge.enableMetrics) { log.info("Enabled metrics"); MetricPeg.set(new PrometheusBridgeMetrics().init()); }
<<<<<<< public async resolveEndpointsAsync(telemetryManager?: TelemetryManager, correlationId?: string): Promise<ITenantDiscoveryResponse> { ======= public async resolveEndpointsAsync(telemetryManager: TelemetryManager, correlationId: string): Promise<Authority> { >>>>>>> public async resolveEndpointsAsync(telemetryManager: TelemetryManager, correlationId: string): Promise<ITenantDiscoveryResponse> {
<<<<<<< import { MatrixClient } from "matrix-bot-sdk"; ======= import { Client as MatrixClient } from "matrix-js-sdk"; import { IMatrixMessageParserCallbacks, IMatrixMessageParserOpts, MatrixMessageParser, } from "matrix-discord-parser"; >>>>>>> import { MatrixClient } from "matrix-bot-sdk"; import { IMatrixMessageParserCallbacks, IMatrixMessageParserOpts, MatrixMessageParser, } from "matrix-discord-parser"; <<<<<<< private params?: IMatrixMessageProcessorParams; constructor(public bot: DiscordBot, private homeserverUrl: string) { } ======= private parser: MatrixMessageParser; constructor(public bot: DiscordBot) { this.parser = new MatrixMessageParser(); } >>>>>>> private parser: MatrixMessageParser; constructor(public bot: DiscordBot) { this.parser = new MatrixMessageParser(); }
<<<<<<< import { CompletionItemProvider, TextDocument, Position, CompletionItem, CompletionItemKind, workspace } from 'vscode' import { readFile, statSync } from 'fs'; import { join, resolve as pathResolve, dirname as pathDir } from 'path'; ======= import { CompletionItemProvider, TextDocument, Position, CompletionItem, workspace } from 'vscode' import { readFile } from 'fs'; import { join } from 'path'; import { getTextWithinString, getCurrentLine } from './text-parser'; import PackageCompletionItem from './PackageCompletionItem'; >>>>>>> import { CompletionItemProvider, TextDocument, Position, CompletionItem, CompletionItemKind, workspace } from 'vscode' import { readFile, statSync } from 'fs'; import { join, resolve as pathResolve, dirname as pathDir } from 'path'; import { getTextWithinString, getCurrentLine } from './text-parser'; import PackageCompletionItem from './PackageCompletionItem'; <<<<<<< return this.getNpmPackages(document).then(dependencies => dependencies.map(d => this.toCompletionItem(d))); ======= return this.getNpmPackages().then(dependencies => { return dependencies.map(d => this.toCompletionItem(d, document, position)) }); >>>>>>> return this.getNpmPackages(document).then(dependencies => { return dependencies.map(d => this.toCompletionItem(d, document, position)) });
<<<<<<< import { RadioButtonModule } from 'app/lib/radio-button/radio-button.module'; import { RadioButtonDemoComponent } from 'app/lib/radio-button/radio-button-demo/radio-button-demo.component'; ======= import { IconModule } from '../lib/icon'; import { FormsModule } from '@angular/forms'; import { HomeComponent } from 'app/home/home.component'; import { DrawerDemoComponent } from '../lib/drawer/drawer-demo/drawer-demo.component'; import { DrawerModule } from '../lib/drawer'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; >>>>>>> import { RadioButtonModule } from 'app/lib/radio-button/radio-button.module'; import { RadioButtonDemoComponent } from 'app/lib/radio-button/radio-button-demo/radio-button-demo.component'; import { IconModule } from '../lib/icon'; import { FormsModule } from '@angular/forms'; import { HomeComponent } from 'app/home/home.component'; import { DrawerDemoComponent } from '../lib/drawer/drawer-demo/drawer-demo.component'; import { DrawerModule } from '../lib/drawer'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; <<<<<<< imports: [ BrowserModule, ButtonModule, CheckboxModule, RadioButtonModule, RouterModule.forRoot(routes) ], exports: [ ButtonModule ], declarations: [ DemoComponent, SideNavComponent, ButtonDemoComponent, CheckboxDemoComponent, RadioButtonDemoComponent, ColorDemoComponent, SwatchDemoComponent, SelectComponent, SelectDemoComponent ] ======= imports: [ BrowserAnimationsModule, BrowserModule, FormsModule, ButtonModule, CheckboxModule, IconModule, DrawerModule, TabsModule, SelectModule, RouterModule.forRoot(routes) ], declarations: [ DemoComponent, HomeComponent, SideNavComponent, ButtonDemoComponent, CheckboxDemoComponent, ColorDemoComponent, SwatchDemoComponent, SelectDemoComponent, DrawerDemoComponent, TabsDemoComponent ] >>>>>>> imports: [ BrowserAnimationsModule, BrowserModule, FormsModule, ButtonModule, CheckboxModule, RadioButtonModule, IconModule, DrawerModule, TabsModule, SelectModule, RouterModule.forRoot(routes) ], exports: [ ButtonModule ], declarations: [ DemoComponent, HomeComponent, SideNavComponent, ButtonDemoComponent, CheckboxDemoComponent, RadioButtonDemoComponent, ColorDemoComponent, SwatchDemoComponent, SelectDemoComponent, DrawerDemoComponent, TabsDemoComponent ]